首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

C++11 thread::joinable() 詳解與實測行為

     編輯:C++ 入門

C++11 std::thread::joinable() 詳解

定義

bool joinable() const noexcept; 回傳 thread 物件是否代表一個執行緒(即可被 join 或 detach)。

非 joinable 的三種情況

  1. 預設建構(std::thread t;)
  2. 移動建構/移動賦值後的來源物件(std::thread t2 = std::move(t1); → t1 非 joinable)
  3. 已呼叫 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

GDB 觀察現象

執行 cout << "after" 後,程式像堆疊解構般逐步返回,行為詭異,待後續研究。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved