5

I'm assuming there's an easy answer to this question. I want to first define a thread as a member variable of a class, and then later start this thread in a different function.

For example:

The header file:

#include<thread>
class Foo{
public:
   void threaded_method();
   void start_thread();
private:
   std::thread m_thread;      
};

Cpp file:

void Foo::start_thread(){
    m_thread = std::thread(threaded_method);
}

Although the above does not work, thoughts?

Richard Dally
  • 1,432
  • 2
  • 21
  • 38
Lucas
  • 2,514
  • 4
  • 27
  • 37

3 Answers3

13

To pass a member function to a thread, you must also pass an instance on which to execute that function.

void Foo::start_thread(){
    m_thread = std::thread(&Foo::threaded_method, this);
}
François Moisan
  • 790
  • 6
  • 12
0

Found a good example in these pages:

I forgot to pass in a valid reference to the member function.

void Foo::start_thread(){
    m_thread = std::thread(&Foo::threaded_method, this);
}

Should work. Love finding the answer right after I post a question...

Community
  • 1
  • 1
Lucas
  • 2,514
  • 4
  • 27
  • 37
0

You might also simply change your architecture. For example, have a list and which would contain the functions you want to perform. Then multithread your way through all the functions you want to run.