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 <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 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


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





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值