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.
A thread object is joinable if it represents a thread of execution.
A thread object is not joinable in any of these cases:
- if it was default-constructed.
- if it has been moved from (either constructing another thread object, or assigning to it).
- if either of its members join or detach has been called.
代码示例
// 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