2017-01-23 93 views
0

我知道很多人問這個問題,但我不是「很多人」,我需要一個不同的,更好的解釋來理解。線程上的「detach()」是什麼? CPP

成員函數「detach()」到底是什麼? 我試着運行一個代碼示例:

#include <iostream> 
#include <chrono> 
#include <thread> 

void independentThread() 
{ 
    std::cout << "Starting concurrent thread.\n"; 
    std::this_thread::sleep_for(std::chrono::seconds(200)); 
    std::cout << "Exiting concurrent thread.\n"; 
} 

void threadCaller() 
{ 
    std::cout << "Starting thread caller.\n"; 
    std::thread t(independentThread); 
    t.detach(); 
    std::this_thread::sleep_for(std::chrono::seconds(1)); 
    std::cout << "Exiting thread caller.\n"; 
} 

int main() 
{ 
    threadCaller(); 
    std::this_thread::sleep_for(std::chrono::seconds(5)); 
} 

並在5秒內的所有程序關閉。 我認爲程序會在「main」關閉後的另一個195秒後打開,因爲「detach」的所有概念都是與main無關的,所以以獨立的方式,它應該仍然運行直到所有分離的遊戲都終止... 我閱讀文檔並來到這裏。 更好的解釋 - 請! :)

+0

通過使用['std :: async'](http://en.cppreference.com/w/cpp/thread/async)使您的生活更輕鬆。 –

回答

0

分離線程是一個線程,你不能等待完成。析構函數會檢查線程是分離的還是加入的,如果兩者都不存在,則會中止一個程序(調用std::terminate)。

main()終止後,程序無條件終止,不等待任何線程,分離或其他。

+0

我不明白你......那麼爲什麼它需要?!例如,在python中,沒有任何「分離」,程序本身不會中止!爲什麼我必須使用它?它是什麼讓我噁心? –

+0

@fdwfgwdfwdfv,可能不會以任何方式幫助你。你可能想要堅持使用Python。 – SergeyA

+0

只是請更好地解釋它,所以我可以理解..我沒有問那個男人更多:\ –