名稱空間
變體
操作

std::condition_variable::notify_all

來自 cppreference.com
< cpp‎ | thread‎ | 條件變數
 
 
併發支援庫
執行緒
(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 notify_all() noexcept;
(C++11 起)

解除當前所有等待 *this 的執行緒的阻塞。

目錄

[編輯] 引數

(無)

[編輯] 返回值

(無)

[編輯] 注意

notify_one()/notify_all() 的效果和 wait()/wait_for()/wait_until() 的三個原子部分(解鎖+等待、喚醒和加鎖)以單一的總順序發生,這可以看作是原子變數的修改順序:該順序特定於這個單獨的條件變數。這使得 notify_one() 不可能,例如,延遲並喚醒在呼叫 notify_one() 後剛開始等待的執行緒。

通知執行緒不需要持有與等待執行緒所持有的相同互斥鎖。這樣做可能會是一種效能下降,因為被通知的執行緒會立即再次阻塞,等待通知執行緒釋放鎖,儘管一些實現會識別這種模式並且不嘗試喚醒在持有鎖的情況下被通知的執行緒。

[編輯] 示例

#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>
 
std::condition_variable cv;
std::mutex cv_m; // This mutex is used for three purposes:
                 // 1) to synchronize accesses to i
                 // 2) to synchronize accesses to std::cerr
                 // 3) for the condition variable cv
int i = 0;
 
void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cerr << "Waiting... \n";
    cv.wait(lk, []{ return i == 1; });
    std::cerr << "...finished waiting. i == 1\n";
}
 
void signals()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    {
        std::lock_guard<std::mutex> lk(cv_m);
        std::cerr << "Notifying...\n";
    }
    cv.notify_all();
 
    std::this_thread::sleep_for(std::chrono::seconds(1));
 
    {
        std::lock_guard<std::mutex> lk(cv_m);
        i = 1;
        std::cerr << "Notifying again...\n";
    }
    cv.notify_all();
}
 
int main()
{
    std::thread t1(waits), t2(waits), t3(waits), t4(signals);
    t1.join(); 
    t2.join(); 
    t3.join();
    t4.join();
}

可能的輸出

Waiting...
Waiting...
Waiting...
Notifying...
Notifying again...
...finished waiting. i == 1
...finished waiting. i == 1
...finished waiting. i == 1

[編輯] 參閱

通知一個等待執行緒
(public member function) [edit]
C documentation for cnd_broadcast