std::condition_variable::notify_all
性病:情况[医]变量::通知[医]全
void notify_all( | | (since C++11) |
---|
取消阻塞当前等待的所有线程。*this
...
参数
%280%29
返回值
%280%29
例外
noexcept
规格:
noexcept
注记
对…的影响notify_one()
/notify_all()
三个原子部分wait()
/wait_for()
/wait_until()
%28解锁+等待、唤醒和锁定%29按一个总顺序进行,可视为修改顺序原子变量的顺序是特定于这个单独的条件的。[医]变量。这使得不可能notify_one()
,例如,延迟并取消阻塞在调用之后才开始等待的线程。notify_one()
被制造出来了。
通知线程不需要在等待线程%28s%29所持有的互斥锁上持有锁;实际上,这样做是一种悲观,因为被通知的线程将立即再次阻塞,等待通知线程释放锁。
例
二次
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
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
二次
另见
notify_one | notifies one waiting thread (public member function) |
---|
c CND文件[医]广播
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。