<thread>

公共成員函式
<thread>

std::thread::join

void join();
加入執行緒
當執行緒執行結束後,此函式返回。

此操作將此函式返回的時刻與執行緒內所有操作的完成進行同步:它會阻塞呼叫此函式的執行緒的執行,直到執行緒構造時呼叫的函式返回(如果尚未返回)。

呼叫此函式後,thread 物件將變為非joinable 狀態,並且可以安全地被銷燬

引數



返回值



示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// example for thread::join
#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds
 
void pause_thread(int n) 
{
  std::this_thread::sleep_for (std::chrono::seconds(n));
  std::cout << "pause of " << n << " seconds ended\n";
}
 
int main() 
{
  std::cout << "Spawning 3 threads...\n";
  std::thread t1 (pause_thread,1);
  std::thread t2 (pause_thread,2);
  std::thread t3 (pause_thread,3);
  std::cout << "Done spawning threads. Now waiting for them to join:\n";
  t1.join();
  t2.join();
  t3.join();
  std::cout << "All threads joined!\n";

  return 0;
}

輸出(3秒後)
Spawning 3 threads...
Done spawning threads. Now waiting for them to join:
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
All threads joined!


資料競爭

物件被修改。
請注意,對thread 物件本身的任何操作都不是同步的(與其代表的執行緒內的操作不同)。

異常安全

基本保證:如果此成員函式丟擲異常,則thread 物件將保持有效狀態。

如果呼叫失敗,將丟擲system_error 異常
異常型別錯誤程式碼描述
system_errorerrc::invalid_argument- thread 物件不是joinable
system_errorerrc::no_such_process- thread 物件無效
system_errorerrc::resource_deadlock_would_occur- 當前執行緒與嘗試加入的執行緒相同,或
- 檢測到死鎖(實現可能檢測到某些死鎖情況)。

請注意,如果物件所代表的執行緒因未捕獲的異常而終止,當前執行緒無法捕獲此異常,並且會自動呼叫terminate()

另見