2013-08-05 142 views
4

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

的可能重复的[C++ 11安全地加入一个线程不使用try/catch块(http://stackoverflow.com/questions/15994650/c11-safely-join-a-thread-without -using-a-try-catch-block) –

+3

'joinable'与线程是否正在执行无关。 –

+2

这个链接的答案是不相关的,我想知道如何检查一个线程是否仍然活动,而不是当它是安全的加入,bamboon的回答解决这个完美 –

回答

6

不,我不认为这是可能的。我也会尝试考虑你的设计,如果这样的检查是非常必要的,也许你正在寻找类似于来自提升的可中断线程。

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

也就是说,你可以拨打std::future::wait_for,如std::chrono::seconds(0)。这将为您提供零成本检查,并使您能够比较由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 
} 
+0

这就是一个不错的解决方案 –

+0

值得注意的是,这是c + + 11,所以如果你没有可用的信号灯可能必须是解决方案 – Yann

2

什么定义的“积极运行的代码”?不是我所知道的,我不确定在线程变为可联接后线程处于什么状态,在大多数情况下,我可以想到您实际上需要细粒度控制,就像由该线程中运行的代码设置的标志,反正

一个平台特定的解决方案,你可以使用GetThreadTimes

+0

感谢您的答案,但我正在寻找一个通用的机制 –

相关问题