std::thread::joinable() 詳解bool joinable() const noexcept; 回傳 thread 物件是否代表一個執行緒(即可被 join 或 detach)。
std::thread t;)std::thread t2 = std::move(t1); → t1 非 joinable)join() 或 detach()#include
#include
#include
using namespace std;
void delay(double sec) {
time_t start, cur;
time(&start);
do { time(&cur); } while (cur - start < sec);
}
void show(int n) { cout << "n=" << n << endl; }
int main() {
thread t1(show, 1);
thread t2 = move(t1); // t1 非 joinable
thread t3; // 預設建構,非 joinable
cout << "t1.joinable()=" << t1.joinable() << endl; // false
cout << "t2.joinable()=" << t2.joinable() << endl; // true
cout << "t3.joinable()=" << t3.joinable() << endl; // false
t2.join();
cout << "t2.joinable() after join=" << t2.joinable() << endl; // false
return 0;
}
t1.joinable()=0
t2.joinable()=1
t3.joinable()=0
t2.joinable() after join=0
執行 cout << "after" 後,程式像堆疊解構般逐步返回,行為詭異,待後續研究。