经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C » 查看文章
c/c++ 基本线程管理 join detach
来源:cnblogs  作者:小石王  时间:2018/10/8 9:14:13  对本文有异议

基本线程管理 join detach

join:主线程等待被join线程结束后,主线程才结束。

detach:主线程不等待被detach线程。

问题1:子线程什么时点开始执行?

std::thread t(fun);执行后,就开始执行了。

问题2:在哪里调用join或者detach

1,使用detach的话,直接在std::thread t(fun);后面加上t.detach()即可

2,使用join的话,就要自己选择在代码的哪个位置调用join。因为在子线程开始之后,但又在join被调用之前发生了异常,所以join的调用就没有实际发生。

解决方案1:使用try catch

  1. void f(){
  2. std::thread t(my_func);
  3. try{
  4. do_some_work();
  5. }
  6. catch{
  7. t.join();
  8. throw;
  9. }
  10. t.join();
  11. }

解决方案2:使用一个类包装thread对象,在这个类的析构函数里调用join。

  1. #include <iostream>
  2. #include <thread>
  3. using namespace std;
  4. class my_thread{
  5. public:
  6. explicit my_thread(thread& t_):t(t_){}
  7. ~my_thread(){
  8. if(t.joinable()){ // -------->①
  9. t.join();// -------->②
  10. }
  11. }
  12. my_thread(my_thread const&) = delete;// -------->③
  13. my_thread& operator=(const my_thread&) = delete;
  14. private:
  15. thread& t;
  16. };
  17. class func{
  18. public:
  19. int& data;
  20. func(int& d):data(d){}
  21. void operator()(){
  22. cout << "thread started@@@@@@@@@@@@@@@@@@@@@@@@@@" << endl;
  23. for(unsigned j = 0; j < 100; ++j){
  24. cout << j << endl;
  25. }
  26. }
  27. };
  28. int main(){
  29. int state = 0;
  30. func f(state);
  31. thread t(f);
  32. my_thread mt(t);
  33. //do_something_in_current_thread();
  34. }// -------->④

github源代码

知识点1:当程序执行到④处时,局部对象会被销毁,所以mt的析构函数就会被调用。即使在do_something_in_current_thread();处发生异常了,mt的析构函数也会被调用,所以,join函数不管在什么情况下都会被调用。

知识点2:在②处调用join前,必须要先判断是不是joinable①。这很重要,因为只能join一次,多次join就会出下面错误。

  1. terminate called after throwing an instance of 'std::system_error'
  2. what(): Invalid argument
  3. Aborted (core dumped)

知识点3:拷贝构造函数和赋值运算符被标记成delete了③,一确保它们不会被编译器自动提供。复制或赋值一个thread对象是很危险的,因为它可能比它要结合的线程的作用域存在更久。

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号