如何可靠地判断 boost 线程是否已退出其 run 方法?

2021-12-24 00:00:00 multithreading c++ boost

我认为 joinable 会表明这一点,但是,情况似乎并非如此.

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();}

一个已经退出的线程不是不能加入吗?我错过了什么...... boost thread::joinable 是什么意思?

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

推荐答案

由于您可以在线程终止后加入,所以 joinable() 仍然会返回 true,直到您调用 join() 或 detach().如果您想知道某个线程是否仍在运行,您应该能够调用 timed_join,等待时间为 0.请注意,这可能会导致竞争条件,因为线程可能会在调用后立即终止.

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.

相关文章