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

C++11 std::thread 進階:join/detach/joinable 與函數對象線程

     編輯:關於C++

join 與 detach 的關鍵區別

  • join():阻塞當前線程,等待子線程結束,回收資源
  • detach():分離線程,子線程獨立運行,資源由運行時自動回收(守護線程)
  • 關鍵規則: 一旦 detach(),不能再 join(),否則拋異常/未定義行為

int main() {
    std::thread t([]{ /* work */ });
    // t.join(); // 選項 1
    t.detach(); // 選項 2
    // t.join(); // 錯誤!已 detach 不能 join
    return 0;
}

joinable():安全檢查

在 join() 或 detach() 前檢查 joinable(),避免重複操作或對空線程對象操作。


#include <iostream>
#include <thread>

void mythread() { /* do stuff */ }

int main() {
    std::thread foo;           // 默認構造,無關聯線程
    std::thread bar(mythread); // 關聯線程

    cout << boolalpha;
    cout << "foo joinable: " << foo.joinable() << " ";  // false
    cout << "bar joinable: " << bar.joinable() << "\n"; // true

    if (foo.joinable()) foo.join();
    if (bar.joinable()) bar.join();

    cout << "After join - foo: " << foo.joinable() << " "; // false
    cout << "bar: " << bar.joinable() << "\n";             // false
    return 0;
}

線程函數的多種形式

  1. 普通函數:std::thread t(func);
  2. 函數對象(仿函數):
    
    class MyFunctor {
    public:
        void operator()() { std::cout << "functor\n"; }
    };
    int main() {
        MyFunctor fnctor;
        std::thread t(fnctor); // 拷貝 fnctor 到線程內部
        t.join();
    }
    
    
  3. 臨時對象(最 vexing parse 陷阱):
    
    // std::thread t(MyFunctor()); // 錯誤!聲明函數 t 返回 thread,參數為函數指針
    std::thread t((MyFunctor())); // 正確:額外括號強制構造臨時對象
    // 或 C++11 統一初始化
    std::thread t{MyFunctor()};
    
    
  4. Lambda 表達式:
    
    std::thread t([]{ std::cout << "lambda thread\n"; });
    
    
  5. 成員函數:
    
    class A { public: void func(int x) {} };
    A obj;
    std::thread t(&A::func, &obj, 42); // 對象指針作為第一參數
    
    

最佳實踐總結

  • 優先用 join() 確保線程結束,資源確定性釋放
  • 只在明確不需要等待(如守護任務)時用 detach()
  • 析構前必須 join() 或 detach(),否則 std::terminate
  • 用 joinable() 守護所有線程操作
  • 傳遞參數時注意生命週期,避免懸空引用(用 std::ref 或傳值)
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved