std::condition_variable_any::wait_until
template< class Lock, class Clock, class Duration > std::cv_status |
(1) | (自 C++11 起) |
template< class Lock, class Clock, class Duration, class Predicate > bool wait_until( Lock& lock, |
(2) | (自 C++11 起) |
template< class Lock, class Clock, class Duration, class Predicate > bool wait_until( Lock& lock, std::stop_token stoken, |
(3) | (自 C++20 起) |
wait_until
导致当前线程阻塞,直到条件变量被通知、给定持续时间已过或发生虚假唤醒为止。pred 可以选择性地提供以检测虚假唤醒。
if (wait_until(lock, abs_time) == std::cv_status::timeout)
return pred();
return true;。
{
if (pred())
return true;
if (wait_until(lock, abs_time) == std::cv_status::timeout)
return pred();
}
return pred();。
在 wait_until
返回后,调用线程将锁定 lock。如果无法满足此后置条件[1],则调用 std::terminate。
- ↑ 如果互斥锁的重新锁定抛出异常,则可能发生这种情况。
目录 |
[编辑] 参数
lock | - | 一个锁,必须由调用线程锁定 |
stoken | - | 一个停止令牌,用于注册中断 |
abs_time | - | 等待到期的时间点 |
pred | - | 用于检查等待是否可以完成的谓词 |
类型要求 | ||
-Lock 必须满足 BasicLockable 的要求。 | ||
-Predicate 必须满足 FunctionObject 的要求。 | ||
-pred() 必须是有效的表达式,并且其类型和值类别必须满足 BooleanTestable 的要求。 |
[编辑] 返回值
[编辑] 异常
[编辑] 注意
标准建议与 abs_time 绑定的时钟应用于测量时间;该时钟不需要是单调时钟。如果时钟不连续调整,则无法保证此函数的行为,但现有实现将 abs_time 从 Clock
转换为 std::chrono::system_clock 并委托给 POSIX pthread_cond_timedwait
,以便等待尊重对系统时钟的调整,但不尊重用户提供的 Clock
。在任何情况下,由于调度或资源争用延迟,该函数也可能等待的时间比达到 abs_time 之后更长。
即使使用的时钟是 std::chrono::steady_clock 或另一个单调时钟,系统时钟调整也可能导致虚假唤醒。
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; // 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
[编辑] 缺陷报告
以下行为更改缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 2093 | C++11 | 规范中缺少与超时相关的异常 | 提及这些异常 |
LWG 2114 (P2167R3) |
C++11 | 到 bool 的可转换性太弱,无法反映实现的期望 | 要求已加强 |
LWG 2135 | C++11 | 如果 lock.lock() 抛出异常,则行为不明确 | 在这种情况下调用 std::terminate |
[编辑] 参见
阻塞当前线程,直到条件变量被唤醒 (public member function) | |
wait_until |
阻塞当前线程,直到条件变量被唤醒或直到达到指定时间点 (public member function) |