2013-08-05 140 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

感謝您的答案,但我正在尋找一個通用的機制 –

相關問題