2015-03-24 109 views
0

如何在C++ 11中乾淨地終止當前子std ::線程?終止決定是在主線程方法的函數調用深度爲4或5時做出的,因此我不想檢查每次返回時是否應該終止。我已經看過退出和終止,但它看起來像他們終止整個過程,而不僅僅是當前的線程。終止當前線程

例如:

void A() { B(); ... } 
void B() { C(); ... } 
void C() { D(); ... } 
void D() { /* oops! need to terminate this thread*/ } 

void main() { 
    thread t(A); 
} 
+0

只從線程main函數返回。 – 2015-03-24 23:21:39

+0

啊,那麼不,不可能使用標準的C++功能來退出線程。如果編譯器還支持[C11線程](http://en.cppreference.com/w/c/thread),則可以使用例如['thrd_exit'](http://en.cppreference.com/w/c/thread/thrd_exit),否則你不得不依賴平臺相關函數,如['pthread_exit'](http://pubs.opengroup。 org/onlinepubs/9699919799/functions/pthread_exit.html)。 – 2015-03-24 23:34:40

+0

所以如果我調用從子線程退出它保證乾淨地終止整個過程?因爲我最終想要終止所有進程,但是在SO上讀取某處調用退出子線程並不可靠。 – 2015-03-24 23:40:48

回答

0

另一種方法是使用std::async和你想終止線程拋出異常。然後,您可以在異步調用返回的future上調用get()來檢索異常並優雅地終止。例如:

#include <iostream> 
#include <thread> 
#include <future> 

void A(); 
void B(); 
void C(); 
void D(); 

void A() { while (true) B(); } 
void B() { while (true) C(); } 
void C() { while (true) D(); } 
void D() { throw -1; } 

int main() 
{ 
    auto future = std::async(A); 

    try { 
     future.get(); 
    } 
    catch (int e) { 
     // Handle thread termination 
     std::cout << "Thread threw exception " << e << '\n'; 
    } 

    std::cout << "Application terminating..." << '\n'; 
    return 0; 
} 
+0

因此,異步會在引發異步的主線程中拋出?如果是這樣的話,那麼這可能是一個問題,因爲我的主程序在創建子線程後繼續做其他工作,並且希望定期檢查子線程是否退出。我不知道是否將整個主程序封裝在try塊中是一種好的做法。 – 2015-03-24 23:59:13

+0

@SidharthMudgal不一定;我只是以此爲例。您可以在'A()'中進一步捕獲異常,並在某處(線程安全且不是終止線程的本地)設置一個標誌,指示線程已終止。該線程將終止,但您可以隨時使用主線程檢查前面提到的標誌,只要你喜歡。 – Julian 2015-03-25 00:17:38