when to detach or join a boost thread?

Pier picture Pier · Mar 2, 2012 · Viewed 9.8k times · Source

I have a method which is fired once every 30 seconds aprox. that I need to have in a thread.

I have a method that I can call from outside the class. Something like callThreadedMethod() which creates the thread which itself calls the final threadedMethod.

These are methods of MyClass

void callThreadedMethod(){
    mThread = boost::shared_ptr<boost::thread>(new boost::thread(&MyClass::threadedMethod, this));
}

void threadedMethod(){
    //more code NOT inside a while loop
}

So do I have to detach mThread every time the method is called?

Is it enough to call join() in the MyClass destructor?

Does the thread destroys itself when threadedMethod finishes?

Answer

Alan Stokes picture Alan Stokes · Mar 2, 2012

It depends what you want to achieve. If you don't care when or if the calls to threadedMethod terminate, or whether or not they throw, then you can just detach the thread as soon as you've created it; each thread will be destroyed when the method completes. And you shouldn't store the thread in a member variable.

If you do care then you need to call join on each thread you create (so once per thread, not once in the destructor). I suspect you don't.

Do you really need to create a new thread for each call? Thread creation can be expensive, so an alternative would be to use a thread pool and submit each threadedMethod invocation to that. The pool could then have the lifetime of the MyClass instance. But perhaps that's overkill for something that is only happening once every 30s.