gpt4 book ai didi

c++ - std::condition_variable wait_for 无限

转载 作者:太空狗 更新时间:2023-10-29 23:13:03 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com