std::condition_variable::notify_all
從 cppreference.com
< cpp | thread | condition variable
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; // 此互斥体用于三个目的: // 1) 同步对 i 的访问 // 2) 同步对 std::cerr 的访问 // 3) 用于条件变量 cv int i = 0; void waits() { std::unique_lock<std::mutex> lk(cv_m); std::cerr << "等待... \n"; cv.wait(lk, []{return i == 1;}); std::cerr << "...结束等待。i == 1\n"; } void signals() { std::this_thread::sleep_for(std::chrono::seconds(1)); { std::lock_guard<std::mutex> lk(cv_m); std::cerr << "通知...\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 << "再次通知...\n"; } cv.notify_all(); } int main() { std::thread t1(waits), t2(waits), t3(waits), t4(signals); t1.join(); t2.join(); t3.join(); t4.join(); }
可能的輸出:
等待... 等待... 等待... 通知... 再次通知... ...结束等待。i == 1 ...结束等待。i == 1 ...结束等待。i == 1
[編輯] 參閱
通知一個等待的線程 (公開成員函數) | |
cnd_broadcast 的 C 文檔
|