std::condition_variable_any::notify_all
來自 cppreference.com
< cpp | thread | condition variable any
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_any 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) | |
C 文件 為 cnd_broadcast
|