std::condition_variable_any:: notify_all
From cppreference.net
<
cpp
|
thread
|
condition variable any
C++
Concurrency support library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
std::condition_variable_any
| Member functions | ||||
| Notification | ||||
|
condition_variable_any::notify_all
|
||||
| Waiting | ||||
|
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; // 此互斥锁用于三个目的: // 1) 同步对 i 的访问 // 2) 同步对 std::cerr 的访问 // 3) 用于条件变量 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
参见
|
通知一个等待线程
(公开成员函数) |
|
|
C 文档
for
cnd_broadcast
|
|