函式
<condition_variable>

std::notify_all_at_thread_exit

void notify_all_at_thread_exit (condition_variable& cond, unique_lock<mutex> lck);
線上程退出時通知所有等待的執行緒
當呼叫執行緒退出時,所有在 cond等待 的執行緒都會被通知恢復執行。

該函式還獲取 lck 管理的 mutex 物件的鎖的擁有權,該物件由函式內部儲存,並在執行緒退出時(在通知所有執行緒之前)解鎖,其行為如同呼叫了以下內容,在所有具有 執行緒儲存持續時間 的物件被銷燬之後:
1
2
lck.unlock();
cond.notify_all();

引數

cond
用於線上程退出時通知所有等待執行緒的 condition_variable 物件。
lck
一個 unique_lock 物件,其互斥量物件當前被該執行緒鎖定。
該物件被函式獲取(它應該是一個 右值)。
cond 上所有等待的執行緒(如果有)應使用與 lck 相同的底層 互斥量物件

返回值



示例

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
26
27
28
29
30
31
32
33
34
35
36
37
// notify_all_at_thread_exit
#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id (int id) {
  std::unique_lock<std::mutex> lck(mtx);
  while (!ready) cv.wait(lck);
  // ...
  std::cout << "thread " << id << '\n';
}

void go() {
  std::unique_lock<std::mutex> lck(mtx);
  std::notify_all_at_thread_exit(cv,std::move(lck));
  ready = true;
}

int main ()
{
  std::thread threads[10];
  // spawn 10 threads:
  for (int i=0; i<10; ++i)
    threads[i] = std::thread(print_id,i);
  std::cout << "10 threads ready to race...\n";

  std::thread(go).detach();   // go!

  for (auto& th : threads) th.join();

  return 0;
}

可能的輸出(執行緒順序可能不同)

10 threads ready to race...
thread 9
thread 0
thread 7
thread 2
thread 5
thread 4
thread 6
thread 8
thread 3
thread 1


資料競爭

該函式執行兩次原子操作:
  • 解鎖 lck
  • 通知 cond 上所有等待的執行緒。
執行緒區域性儲存 的變數的銷燬與等待執行緒中的喚醒通知同步。

異常安全

基本保證: 如果丟擲異常,則作為引數傳遞的物件處於有效狀態。
在失敗時,它可能會丟擲 system_error(將 unlock 的任何錯誤條件傳遞)。

另見