-1

I've been trying to get the hang of threading for a while, but it seems no matter how many examples or similar SOflow questions I look at, nothing is enlightening me to the answer. I need to call a member function of a class as a thread from the constructor of the class.

I've tried various different changes (very few of which I've actually understood the purpose of, since I'm new to threading - sorry guys!) such as setting the target function to static (which caused a massive number of errors to occur in it's place - even though it seemed to resolve the invalid use).

The basic of what I've got so far is:

class VideoController
{
    VideoController()
    {
        //initialise everything else
        std::thread t(VideoController::Heartbeat)//originally: t(Heartbeat);
        //                                       //and have tried: (Heartbeat, NULL);
    }

    void Heartbeat() //tried: static void Heartbeat() && void Heartbeat(void)
    {
        while(true) //(why threading is essential)
        {
            //carry out function
        }
    }
}

The error that this is giving me is:
VideoController.cpp: In constructor 'VideoController::VideoController(std::__cxx11::string, std::__cxx11::string, std::__cxx11::string)': VideoController.cpp:115:49: error: invalid use of non-static member function 'void VideoController::Heartbeat()'
std::thread t(Heartbeat);
.......................^

If someone could learn me a thing or two about exactly why this isn't working for me, it'd be greatly appreciated!

David Cox
  • 3
  • 3

1 Answers1

0
class A
{
  void threadfunc() { ... }

  void foo()
  { 
       std::thread t(&A::threadfunc,this);
       ... 
  }
};

Well creating a thread using a member function, you must also pass this (as all non static member functions take a hidden pointer to the class as their first argument).

Michael Chourdakis
  • 10,345
  • 3
  • 42
  • 78
  • In addition to passing `this`, the ampersand reference was also something I'd managed to miss out. Thank you very much Michael! – David Cox Apr 12 '19 at 17:26