Lucas
Lucas

Reputation: 2642

Initialize C++ Thread and Run Later

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?

Upvotes: 5

Views: 15097

Answers (3)

FunkMasterP
FunkMasterP

Reputation: 21

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.

Upvotes: 0

Lucas
Lucas

Reputation: 2642

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...

Upvotes: 0

Fran&#231;ois Moisan
Fran&#231;ois Moisan

Reputation: 790

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);
}

Upvotes: 13

Related Questions