std::condition_variable_any::wait
性病:情况[医]变量[医]A:等等
template< class Lock > void wait( Lock& lock | (1) | (since C++11) |
---|---|---|
template< class Lock, class Predicate > void wait( Lock& lock, Predicate pred | (2) | (since C++11) |
wait
导致当前线程阻塞,直到通知条件变量或出现虚假唤醒为止,还可以选择循环直到满足某个谓词。
1%29原子释放lock
,阻止当前正在执行的线程,并将其添加到等待执行的线程列表中。*this
.线程将在notify_all()
或notify_one()
被处决了。它也可能是伪造的。不管原因是什么,lock
重新获得和wait
出口。如果此函数通过异常退出,lock
也被重新获得。%28直到C++14%29
2%29相当于
二次
while (!pred()) {
wait(lock
}
二次
这种过载可能被用来忽略虚假的唤醒,而等待特定的条件成为现实。请注意,在输入此方法之前lock
必须获得,之后wait(lock)
退出也会被重新获取,即lock
可以用作警卫pred()
进入。
If these functions fail to meet the postconditions (lock is locked by the calling thread), std::terminate is called. For example, this could happen if relocking the mutex throws an exception, | (since C++14) |
---|
参数
lock | - | an object of type Lock that meets the BasicLockable requirements, which must be locked by the current thread |
---|---|---|
pred | - | predicate which returns false if the waiting should be continued. The signature of the predicate function should be equivalent to the following: bool pred( |
返回值
%280%29
例外
1%29
May throw std::system_error, may also propagate exceptions thrown by lock.lock() or lock.unlock(). | (until C++14) |
---|---|
Does not throw. | (since C++14) |
2%29与%281%29相同,但也可能传播由pred
注记
对…的影响notify_one()
/notify_all()
三个原子部分wait()
/wait_for()
/wait_until()
%28解锁+等待、唤醒和锁定%29按一个总顺序进行,可视为修改顺序原子变量的顺序是特定于这个单独的条件的。[医]变量。这使得不可能notify_one()
,例如,延迟并取消阻塞在调用之后才开始等待的线程。notify_one()
被制造出来了。
例
二次
#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>
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
二次
另见
wait_for | blocks the current thread until the condition variable is woken up or after the specified timeout duration (public member function) |
---|---|
wait_until | blocks the current thread until the condition variable is woken up or until specified time point has been reached (public member function) |
c CND文件[医]等待
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。