2015-03-24 115 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