Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I assumed joinable would indicate this, however, it does not seem to be the case.

In a worker class, I was trying to indicate that it was still processing through a predicate:

bool isRunning(){return thread_->joinable();}

Wouldn't a thread that has exited not be joinable? What am I missing... what is the meaning of boost thread::joinable?

like image 715
JeffV Avatar asked Nov 03 '09 13:11

JeffV


4 Answers

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.

like image 91
interjay Avatar answered Nov 01 '22 02:11

interjay


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));
like image 37
Joakim Karlsson Avatar answered Nov 01 '22 02:11

Joakim Karlsson


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

like image 4
pocruadhlaoich Avatar answered Nov 01 '22 00:11

pocruadhlaoich


You fundamentally can't do this. The reason is that the two possible answers are "Yes" and "Not when I last looked but perhaps now". There is no reliable way to determine that a thread is still inside its run method, even if there was a reliable way to determine the opposite.

like image 2
MSalters Avatar answered Nov 01 '22 01:11

MSalters