std::thread joinable()用于检测线程是否有效

std::thread  joinable()函数,用于检测线程是否有效。

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

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

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

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

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

bool joinable() const noexcept;

check if joinable

Returns whether the thread object is joinable.

thread object is joinable if it represents a thread of execution.

thread object is not joinable in any of these cases:


 

代码示例

// example for thread::joinable
#include <iostream>       // std::cout
#include <thread>         // std::thread
 
void mythread() 
{
  // do stuff...
}
 
int main() 
{
  std::thread foo;
  std::thread bar(mythread);
 
  std::cout << "Joinable after construction:\n" << std::boolalpha;
  std::cout << "foo: " << foo.joinable() << '\n';
  std::cout << "bar: " << bar.joinable() << '\n';
 
  if (foo.joinable()) foo.join();
  if (bar.joinable()) bar.join();
 
  std::cout << "Joinable after joining:\n" << std::boolalpha;
  std::cout << "foo: " << foo.joinable() << '\n';
  std::cout << "bar: " << bar.joinable() << '\n';
 
  return 0;
}

输出结果
Joinable after construction:
foo: false
bar: true
Joinable after joining:
foo: false
bar: false

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值