c++ thread 笔记1

来源:互联网 发布:c语言基础教程视频 编辑:程序博客网 时间:2024/05/07 11:53

今天看 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 <chrono>  2 #include <thread>  3 #include <iostream>  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 exceptionAborted

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

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


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





0 0
原创粉丝点击