std::condition_variable::notify_all
来自 cppreference.cn
| 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) | |
| C documentation for cnd_broadcast
| |