c++ - 我可以使用 now() 将 wait_until 转换为 wait_for 吗?

标签 c++ c++11 c++-chrono

我正在实现自己的 Future 类,该类构建在第 3 方等待函数 thirdPartyWait(int milliseconds) 之上。我希望我的 Futurestd::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());
}

我已经测试了代码并且它可以工作,但我很清楚简单的测试并不能涵盖所有极端情况。可以肯定的是,我对 stdchrono 部分还不够熟悉,因此我的问题是:

我的 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.

从中我推断当前的实现与您正在做的完全一样。

http://en.cppreference.com/w/cpp/thread/future/wait_until

关于c++ - 我可以使用 now() 将 wait_until 转换为 wait_for 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42225152/

相关文章:

c++ - boost::thread 和 std::unique_ptr

c++ - 我可以使用多线程调用一个简单的函数几次吗? C++11

C++ Chrono 32/64 位 + 发布/调试

c++信号量不考虑调用顺序

c++ - std::underlying_type :SFINAE 是否可以防止未定义的行为?

c++ - 什么是 C++11 扩展 [-Wc++11-extensions]

c++ - 我们可以从相同类型的范围中获取 `std::chrono::milliseconds` 变量吗?

C++ Chrono 判断一天是否是周末?

c++ - 以非阻塞方式打开 QDialog

c++ - 在 C++ 中,对象可以为 null 吗?