c++ - std::condition_variable wait_for 无限

标签 c++ c++11 synchronization wait condition-variable

我正在尝试使用以下代码对条件变量进行无限等待(只是显示问题的示例):

std::condition_variable cond;
std::mutex mtx;
std::unique_lock<std::mutex> lock(mtx);
cond.wait_for(lock, std::chrono::steady_clock::duration::max());

但是等待会立即退出。深入研究 wait_for 的 (MS) 实现,我发现它实际上使用了 wait_until 函数。但在此之前,它会调用 chrono::system_clock::now() 并仅添加持续时间来转换时间。

当然这会导致整数溢出,因此新时间变为 <= 'now'。因此 wait_until 立即退出。 所有其他定时等待函数(例如 std::timed_mutex 类中的 try_lock_for)也是如此。

综上所述,我想问一下,这是否是定时等待函数实现中的错误,如果是,那我在哪里写呢?

此外,由于 wait_until 使用 system_clock,如果在等待期间有时间调整,实际等待时间应该会有所不同(因为 system_clock 不是单调的).因此不信任等待时间。

最佳答案

cppreference documentation说:

Note that rel_time must be small enough not to overflow when added to std::chrono::steady_clock::now().

和:

The clock tied to timeout_time is used, which is not required to be a monotonic clock.There are no guarantees regarding the behavior of this function if the clock is adjusted discontinuously, but the existing implementations convert timeout_time from Clock to std::chrono::system_clock and delegate to POSIX pthread_cond_timedwait so that the wait honors ajustments to the system clock, but not to the the user-provided Clock. In any case, the function also may wait for longer than until after timeout_time has been reached due to scheduling or resource contention delays.

Even if the clock in use is std::chrono::steady_clock or another monotonic clock, a system clock adjustment may induce a spurious wakeup.

如果你想要无限超时,你可以做这样的事情(未测试):

wait_until(lock, std::chrono::sys_time::max());

关于c++ - std::condition_variable wait_for 无限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42080709/

相关文章:

c++ - 为特定操作系统编写代码时,标准库调用与所有操作系统 API 调用之间的权衡是什么?

c++ - Netbeans v7 C++ 调试器错误

c++ - 将 freeglut 回调包装在一个类中的最优雅的方式

java - 线程同步不起作用

android - 将数据同步到 Google 帐户有哪些限制?

c++ - 如何在 CUDA 设备上更改稀疏矩阵的子矩阵

c++ - 什么是 multimap::emplace() 和 move()?

c++ - 在 C++ 中获取拉丁字符

c++ - 如果 pthread_cond_signal 是线程中的最后一次调用,是否存在数据竞争?

c++ - 验证 whitepsace 分隔的整数 c++