std::condition_variable::wait_until
template< class Clock, class Duration > std::cv_status |
(1) | (自 C++11 起) |
template< class Clock, class Duration, class Predicate > bool wait_until( std::unique_lock<std::mutex>& lock, |
(2) | (自 C++11 起) |
wait_until
导致当前线程阻塞,直到条件变量被通知、给定的时间点到达或发生伪唤醒为止。pred 可以选择性地提供以检测伪唤醒。
if (wait_until(lock, abs_time) == std::cv_status::timeout)
return pred();
return true;。
在 wait_until
返回后,lock.owns_lock() 为 true,并且 lock.mutex() 由调用线程锁定。如果这些后置条件无法满足[1],则调用 std::terminate。
如果满足以下任何条件,则行为未定义
- lock.owns_lock() 为 false。
- lock.mutex() 未被调用线程锁定。
- 如果其他一些线程也在 *this 上等待,则 lock.mutex() 与由在 *this 上调用的等待函数(wait、wait_for 和
wait_until
)解锁的互斥量不同。
- ↑ 如果互斥量的重新锁定抛出异常,则可能发生这种情况。
目录 |
[edit] 参数
lock | - | 一个锁,必须由调用线程锁定 |
abs_time | - | 等待到期的时间点 |
pred | - | 用于检查等待是否可以完成的谓词 |
类型要求 | ||
-Predicate 必须满足 FunctionObject 的要求。 | ||
-pred() 必须是有效的表达式,并且其类型和值类别必须满足 BooleanTestable 的要求。 |
[edit] 返回值
[edit] 异常
[edit] 注意
标准建议使用与 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()
之后立即开始等待的线程。
[edit] 示例
#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
[edit] 缺陷报告
以下行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 2093 | C++11 | 规范中缺少与超时相关的异常 | 提及这些异常 |
LWG 2114 (P2167R3) |
C++11 | 转换为 bool 的可转换性太弱,无法反映实现的预期 | 要求已加强 |
LWG 2135 | C++11 | 如果 lock.lock() 抛出异常,则行为不明确 | 在这种情况下调用 std::terminate |
[edit] 参见
阻塞当前线程,直到条件变量被唤醒 (公共成员函数) | |
阻塞当前线程,直到条件变量被唤醒或在指定的超时持续时间之后 (公共成员函数) |