How can I tell reliably if a boost thread has exited its run method? How can I tell reliably if a boost thread has exited its run method? multithreading multithreading

How can I tell reliably if a boost thread has exited its run method?


Since you can join a thread even after it has terminated, joinable() will still return true until you call join() or detach(). If you want to know if a thread is still running, you should be able to call timed_join with a wait time of 0. Note that this can result in a race condition since the thread may terminate right after the call.


Use thread::timed_join() with a minimal timeout. It will return false if the thread is still running.

Sample code:

thread_->timed_join(boost::posix_time::seconds(0));


I am using boost 1.54, by which stage timed_join() is being deprecated. Depending upon your usage, you could use joinable() which works perfectly for my purposes, or alternatively you could use try_join_for() or try_join_until(), see:

http://www.boost.org/doc/libs/1_54_0/doc/html/thread/thread_management.html