c++ thread 笔记1

今天看 c++ Concurrency In Action, 读到:

Once you’ve started your thread, you need to explicitly decide whether to wait for it tofinish (by joining with it—see section 2.1.2) or leave it to run on its own (by detachingit—see section 2.1.3). If you don’t decide before the std::thread object is destroyed,then your program is terminated (the std::thread destructor calls std::terminate()). 

就是说定义了一个thread对象后,一定要在对象析构之前调用 join 或者 detach,否则该 thread 对象的析构会让调用 terminate ,

是的就是一般遇到没有被catch的异常时候调用的,默认是调用 abort 终止进程。

怎么会这样?!

但是就是这样。

标准库中 thread 的析构函数定义:

如果 thread 是 joinable 的,就 terminate;join 或者 detach 的调用会让 thread 变成 non joinable 。

140     ~thread()
141     {
142       if (joinable())
143   std::terminate();
144     }

测试程序:

  1 #include 
  2 #include 
  3 #include 
  4 
  5 using namespace std;
  6 
  7 void hah() {
  8   cout << "hah" << endl;
  9 }
 10 void fun() {
 11   thread trd(hah);
 12 //  trd.join();
 13 //  trd.detach();
 14 }
 15 
 16 int main() {
 17   fun();
 18   for (int i = 0; i < 3; ++i) {
 19     cout << i << endl;
 20     std::this_thread::sleep_for (std::chrono::seconds(1));
 21   }
 22 }


运行结果:

[root@licchen-test-dev001-bjdxt tests]# g++ thread_terminate.cpp -lpthread
[root@licchen-test-dev001-bjdxt tests]# ./a.out 
terminate called without an active exception
Aborted

如果取消注释 join 或者 detach,会正常运行结束:

[root@licchen-test-dev001-bjdxt tests]# g++ thread_terminate.cpp -lpthread
[root@licchen-test-dev001-bjdxt tests]# ./a.out 
0
hah
1
2


但是为什么要这样设计呢?





你可能感兴趣的:(C/C++)