名稱空間
變體
操作

std::jthread::join

來自 cppreference.com
< cpp‎ | thread‎ | jthread
 
 
併發支援庫
執行緒
(C++11)
(C++20)
this_thread 名稱空間
(C++11)
(C++11)
(C++11)
協同取消
互斥
(C++11)
通用鎖管理
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
條件變數
(C++11)
訊號量
門閂和屏障
(C++20)
(C++20)
期值
(C++11)
(C++11)
(C++11)
(C++11)
安全回收
(C++26)
危險指標
原子型別
(C++11)
(C++20)
原子型別的初始化
(C++11)(C++20 中已棄用)
(C++11)(C++20 中已棄用)
記憶體排序
(C++11)(C++26 中已棄用)
原子操作的自由函式
原子標誌的自由函式
 
 
void join();
(C++20 起)

阻塞當前執行緒,直到由 *this 標識的執行緒完成執行。

*this 標識的執行緒的完成與 join() 對應的成功返回**同步**。

*this 本身不執行同步。從多個執行緒併發呼叫同一個 jthread 物件的 join() 構成資料競爭,導致未定義行為。

目錄

[編輯] 引數

(無)

[編輯] 返回值

(無)

[編輯] 後置條件

joinable()false

[編輯] 異常

如果發生錯誤,丟擲 std::system_error

[編輯] 錯誤條件

[編輯] 示例

#include <chrono>
#include <iostream>
#include <thread>
 
void foo()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
void bar()
{
    // simulate expensive operation
    std::this_thread::sleep_for(std::chrono::seconds(1));
}
 
int main()
{
    std::cout << "starting first helper...\n";
    std::jthread helper1(foo);
 
    std::cout << "starting second helper...\n";
    std::jthread helper2(bar);
 
    std::cout << "waiting for helpers to finish..." << std::endl;
    helper1.join();
    helper2.join();
 
    std::cout << "done!\n";
}

輸出

starting first helper...
starting second helper...
waiting for helpers to finish...
done!

[編輯] 引用

  • C++23 標準 (ISO/IEC 14882:2024)
  • 33.4.4.3 成員 [thread.jthread.mem]
  • C++20 標準 (ISO/IEC 14882:2020)
  • 32.4.3.2 成員 [thread.jthread.mem]

[編輯] 參閱

允許執行緒獨立於執行緒控制代碼執行
(public member function) [編輯]
檢查執行緒是否可join,即是否可能在並行上下文中執行
(public member function) [編輯]
C documentation for thrd_join