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

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐