std::get<C++11多线程库>(04): join() 调用位置的讨论

 1 #include <QCoreApplication>
 2 #include <iostream>
 3 #include <thread>
 4 
 5 
 6 /*
 7  * 话题:join() 如果打算等待对应线程,则需要细心挑选调用join()的位置。
 8  *      当在线程运行之后产生异常,在join()调用之前抛出,就意味着这次调用会被跳过。
 9  *
10  * 要避免应用被抛出的异常所终止,继而导致调用不到 join(),造成生命周期问题,需要在异常处理过程中调用join(),
11  *
12  * try/catch只能捕获轻量级的错误,所以这种方案,并非放之四海皆准。
13  *
14  * 因此,务必确定新线程中有无使用局部变量的引用,或者初始线程后有多个return分支。
15 */
16 void hello(){
17     std::cout<<"hello word "<<std::endl;
18 }
19 
20 int main(int argc, char *argv[])
21 {
22     QCoreApplication a(argc, argv);
23 
24     std::thread t(hello); // thread t 对象 关联着新线程
25 
26     try{
27         int _b = 0;
28         int _a = 10/_b;
29     }catch(...){
30         t.join();  //1
31         std::cout<<"exception..."<<std::endl;  //没打印输出,奇怪的很
32     }
33 
34     t.join();  //2
35 
36     std::cout<<"no exception..."<<std::endl;
37     return a.exec();
38 }
原文地址:https://www.cnblogs.com/azbane/p/15334385.html