我正在实现自己的 Future
类,该类构建在第 3 方等待函数 thirdPartyWait(int milliseconds)
之上。我希望我的 Future
与 std::future
接口(interface)兼容,这意味着我想同时提供 wait_for
和 wait_until
。
wait_for
很简单,因为它直接映射到 thirdPartyWait
(我可以在其中处理毫秒的转换)。然而,wait_until
的映射效果不太好。直觉上,我认为以下应该满足我的要求:
template <class Clock, class Duration>
std::future_status wait_until(const std::chrono::time_point<Clock, Duration> &timeout) const
{
return wait_for(timeout - Clock::now());
}
我已经测试了代码并且它可以工作,但我很清楚简单的测试并不能涵盖所有极端情况。可以肯定的是,我对 std
的 chrono
部分还不够熟悉,因此我的问题是:
我的 wait_until
实现中是否存在任何隐藏的陷阱,或者我可以期望它按预期工作吗?
最佳答案
cppreference 对于 std::future::wait_until
有这样的说法:
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.
从中我推断当前的实现与您正在做的完全一样。
关于c++ - 我可以使用 now() 将 wait_until 转换为 wait_for 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42225152/