4

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,362
  • 2
  • 20
  • 35
Lucas
  • 2,124
  • 4
  • 21
  • 36

3 Answers3

11

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
  • 770
  • 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,124
  • 4
  • 21
  • 36
  • 2
    I used to do that too. From now, resist the temptation to post a question, first search it thoroughly on google as well as SO and then spend another minute reevaluating it inside your head. You'll answer most of your questions easily. – Abhinav Gauniyal Jul 09 '15 at 16:26
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.