C ++ 11可以判断std :: thread是否处于活动状态?

时间:2013-08-05 17:35:36

标签: c++ multithreading c++11

令我惊讶的是,一个已经完成执行但尚未加入的C ++ 11 std :: thread对象仍然是considered一个活动的执行线程。下面的代码示例(在Xubuntu 13.03和g ++ 4.7.3上构建)说明了这一点。有谁知道C ++ 11标准是否提供了一种方法来检测std :: thread对象是否仍在主动运行代码?

#include <thread>
#include <chrono>
#include <iostream>
#include <pthread.h>
#include <functional>
int main() {
    auto lambdaThread = std::thread([](){std::cout<<"Excuting lambda thread"<<std::endl;});
    std::this_thread::sleep_for(std::chrono::milliseconds(250));
    if(lambdaThread.joinable()) {
        std::cout<<"Lambda thread has exited but is still joinable"<<std::endl;
        lambdaThread.join();
    }
    return 0;
}

2 个答案:

答案 0 :(得分:6)

不,我不认为这是可能的。我也会尝试考虑你的设计,如果真的有必要进行这样的检查,也许你正在寻找类似于来自boost的可中断线程的东西。

但是,您可以使用std::async - 无论如何我会这样做 - 然后依靠std::future为您提供的功能。

即,您可以使用std::chrono::seconds(0)之类的内容来致电std::future::wait_for。这样,您就可以进行零费用检查,并可以比较wait_for返回的std::future_status

auto f = std::async(foo);
...
auto status = f.wait_for(std::chrono::seconds(0));
if(status == std::future_status::timeout) {
    // still computing
}
else if(status == std::future_status::ready) {
    // finished computing
}
else {
    // There is still std::future_status::defered
}

答案 1 :(得分:2)

“主动运行代码”的定义是什么?不是我所知道的,我不确定线程​​在变为可连接之后处于什么状态,在大多数情况下我可以想到你实际上想要细粒度控制,就像在该线程中运行的代码设置的标志一样,无论如何

对于特定于平台的解决方案,您可以使用GetThreadTimes