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
- c++thread学习(1)
- c++ thread 笔记1
- Java Thread 学习笔记1
- Thread(C#)
- c thread
- thread.c
- Thread笔记
- Thread笔记
- something about thread(c#)
- linux + thread + c (一)
- C#Thread的使用
- 【c++】线程thread类
- C++/MFC-线程Thread
- C++:线程(std::thread)
- java学习笔记--Thread
- qutecom笔记-thread类
- Android Thread学习笔记。。。
- Boost Thread学习笔记
- java面向对象(接口)
- iOS7的多任务处理
- 使用staruml画类的泛化(继承)关系图
- leetcode | sqrt(x)
- Android的闪退问题
- c++ thread 笔记1
- Chord算法
- 计算客 搜狗输入法
- Java学习笔记之<JDBC连接MySQL的步骤>
- 《大话数据结构》第9章 排序 9.2 排序的基本概念与分类
- android图形系统详解一:Canvas
- CAS总结之Ticket篇(转,非常详细,后文还提到一个ppt,非常易懂)
- ASP.NET2.0下实现分布式StateServer(状态服务器)
- C++学习笔记——面向对象