Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to start a thread as a member of a C++ class?

Tags:

c++

pthreads

I'm wondering the best way to start a pthread that is a member of a C++ class? My own approach follows as an answer...

like image 537
jdt141 Avatar asked Sep 17 '08 18:09

jdt141


People also ask

How do you start a STD thread?

std::thread is the thread class that represents a single thread in C++. To start a thread we simply need to create a new thread object and pass the executing code to be called (i.e, a callable object) into the constructor of the object.

How do you call a member function in a thread C++?

To call a member function, the first argument to std::bind must be a pointer, reference, or shared pointer to an object of the appropriate type.

What happens if you don't join a thread in C?

If you don't join these threads, you might end up using more resources than there are concurrent tasks, making it harder to measure the load. To be clear, if you don't call join , the thread will complete at some point anyway, it won't leak or anything. But this some point is non-deterministic.

Do you have to join a thread C++?

If you do not specify join() or dettach() on the thread then it will result in runtime error as the main/current thread will complete its execution and the other thread created will be still running.


1 Answers

This can be simply done by using the boost library, like this:

#include <boost/thread.hpp>

// define class to model or control a particular kind of widget
class cWidget
{
public:
void Run();
}

// construct an instance of the widget modeller or controller
cWidget theWidget;

// start new thread by invoking method run on theWidget instance

boost::thread* pThread = new boost::thread(
    &cWidget::Run,      // pointer to member function to execute in thread
    &theWidget);        // pointer to instance of class

Notes:

  • This uses an ordinary class member function. There is no need to add extra, static members which confuse your class interface
  • Just include boost/thread.hpp in the source file where you start the thread. If you are just starting with boost, all the rest of that large and intimidating package can be ignored.

In C++11 you can do the same but without boost

// define class to model or control a particular kind of widget
class cWidget
{
public:
void Run();
}

// construct an instance of the widget modeller or controller
cWidget theWidget;

// start new thread by invoking method run on theWidget instance

std::thread * pThread = new std::thread(
    &cWidget::Run,      // pointer to member function to execute in thread
    &theWidget);        // pointer to instance of class
like image 110
ravenspoint Avatar answered Oct 05 '22 03:10

ravenspoint