我正在尝试使用以下代码对条件变量进行无限等待(只是显示问题的示例):
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
不是单调的).因此不信任等待时间。
最佳答案
Note that
rel_time
must be small enough not to overflow when added tostd::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 POSIXpthread_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 aftertimeout_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/