std::jthread::join
來自 cppreference.com
void join(); |
(C++20 起) | |
阻塞當前執行緒,直到由 *this 標識的執行緒完成執行。
由 *this 標識的執行緒的完成與 join()
對應的成功返回**同步**。
在 *this 本身不執行同步。從多個執行緒併發呼叫同一個 jthread 物件的 join() 構成資料競爭,導致未定義行為。
目錄 |
[編輯] 引數
(無)
[編輯] 返回值
(無)
[編輯] 後置條件
joinable() 為 false。
[編輯] 異常
如果發生錯誤,丟擲 std::system_error。
[編輯] 錯誤條件
- 如果 this->get_id() == std::this_thread::get_id()(檢測到死鎖),丟擲 resource_deadlock_would_occur。
- 如果執行緒無效,丟擲 no_such_process。
- 如果 joinable() 為 false,丟擲 invalid_argument。
[編輯] 示例
執行此程式碼
#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
|