Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to detach or join a boost thread?

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?

like image 738
Pier Avatar asked Mar 02 '12 03:03

Pier


People also ask

When should I detach a thread?

detach() is mainly useful when you have a task that has to be done in background, but you don't care about its execution. This is usually a case for some libraries. They may silently create a background worker thread and detach it so you won't even notice it.

What is the purpose of detaching threads?

thread::detachSeparates the thread of execution from the thread object, allowing execution to continue independently. Any allocated resources will be freed once the thread exits. After calling detach *this no longer owns any thread.

How do I detach a boost thread?

A thread can also be detached by explicitly invoking the detach() member function on the boost::thread object. In this case, the boost::thread object ceases to represent the now-detached thread, and instead represents Not-a-Thread.

What happens if a thread is not joined?

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.


1 Answers

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.

like image 53
Alan Stokes Avatar answered Oct 27 '22 06:10

Alan Stokes