2017-08-16 142 views
1

在學習基本線程管理時,發現難以從書中理解這些行(在加粗)。運行線程和線程對象之間的關係

一旦你開始你的線程,你需要明確地決定是否 等待它完成(通過加入安理會,見第2.1.2節)或 離開它自身的運行(由拆下它 - 參見2.1.3節)。如果 在std :: thread對象被銷燬之前沒有做出決定,那麼你的 程序被終止(std :: thread析構函數調用 std :: terminate())。因此,必須確保 線程正確連接或分離,即使存在 例外。有關處理這種情況的技術,請參見第2.1.3節。 請注意,您只需在std :: thread 對象被銷燬之前作出此決定 - 線程本身可能在您加入或脫離它之前完成了長長的 ,如果脫離它,則,然後 線程可能會在std :: thread對象被破壞 後繼續運行很久。

甚至在線程對象被銷燬後線程何時運行?任何人都有示例代碼或任何參考?

+1

'{的std ::螺紋TH(SomeLongRunningFunction); th.detach();/* th在此處被銷燬,但SomeLongRunningFunction繼續在工作線程上運行* /}' –

+2

分離之後,線程與std :: thread對象無關。 – halfelf

+0

規則很簡單:線程始終運行,直到它從其入口函數返回,或者它所屬的可執行文件終止。 – Frank

回答

3

這意味着線程的生命週期與線程對象的生命週期沒有關聯。

所以以下代碼:

#include <thread> 
#include <iostream> 

int main() { 
    { //scope the thread object 
     std::thread thr = std::thread([]() { 
      std::this_thread::sleep_for(std::chrono::seconds(1)); 
      std::cout << "Thread stuff\r\n"; 
     }); 
     thr.detach(); 
    } //thr is destroyed here 
    std::cout << "thr destroyed, start sleep\r\n"; 
    std::this_thread::sleep_for(std::chrono::seconds(10)); 
    std::cout << "sleep over\r\n"; 
} 

將輸出:

thr destroyed, start sleep 
Thread stuff 
sleep over 
+1

這是*可能的*輸出。 「線索的東西」可能會首先出現。 –

+0

的確如此,但我認爲它在大多數情況下說明了這一點。 – bsruth

+0

@Hi什麼時候可以發生? –