std::thread使用

join & detach

定义区别:

  • join 会阻塞,调用线程等待子线程执行完毕,然后再往下执行
  • detach 分离,调用线程不再等待子线程结束,执行 detach 后,子线程和调用线程失去关联,驻留在后台,由 C++ 运行时库接管

使用方式区别:

  • join 需要注意代码逻辑调用顺序,在需要阻塞等待的地方执行
  • detach 只要在构造之后都可以

joinable() 函数

joinable : 代表该线程是可执行线程。

not-joinable :通常一下几种情况会导致线程成为not-joinable

 1) 由thread的缺省构造函数构造而成(thread()没有参数)。

 2) 该thread被move过(包括move构造和move赋值)

 3) 该线程调用过join或者detac

代码演示

// 文件名为test.cpp
// 编译时需链接thread库,不然会报错 undefined reference to 'pthread_create' 
// g++ -Wall -pthread -g -o test test.cpp

主线程不做操作

#include <thread>
#include <iostream>
using namespace std;

void functionToThread()
{
  cout << "线程启动......" << endl;

  cout << "1......" <<endl;

  cout << "2......" <<endl;

  cout << "3......" <<endl;

  cout << "4......" <<endl;

  cout << "5......" <<endl;

  cout << "线程结束......" << endl;
}

int main()
{
  thread myThread(&functionToThread);
  cout << "主线程结束......" <<endl;
  return 0;
}

/*
 主线程结束......
 terminate called without an active exception
 已放弃 (核心已转储)
 */

join

#include <thread>
#include <iostream>
using namespace std;
void functionToThread()
{
  cout << "线程启动......" << endl;

  cout << "1......" <<endl;

  cout << "2......" <<endl;

  cout << "3......" <<endl;

  cout << "4......" <<endl;

  cout << "5......" <<endl;

  cout << "线程结束......" << endl;
}

int main()
{

  thread myThread(&functionToThread);
  if( myThread.joinable() )//可联结
  {
      myThread.join();//阻塞等待线程结束
  }

  cout << "主线程结束......" <<endl;
  return 0;
}

 /*
 线程启动......
 1......
 2......
 3......
 4......
 5......
 线程结束......
 主线程结束......
 */

detach

#include <thread>
#include <iostream>
using namespace std;
void functionToThread()
{
  cout << "线程启动......" << endl;

  cout << "1......" <<endl;

  cout << "2......" <<endl;

  cout << "3......" <<endl;

  cout << "4......" <<endl;

  cout << "5......" <<endl;

  cout << "线程结束......" << endl;
}

int main()
{
  thread myThread(&functionToThread);
  if( myThread.joinable() )//可联结
  {
      myThread.detach();//不会等待线程结束
  }

  cout << "主线程结束......" <<endl;
  return 0;
}
/*
 主线程结束......
 */

参考文章:
1、joinable
https://blog.csdn.net/bobbypeng/article/details/100055167
2、join 和 detach
https://blog.csdn.net/lizhichao410/article/details/123572144
3、编译问题
https://blog.csdn.net/qq907482638/article/details/104542871

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值