[英]How to convert std::chrono::duration to boost duration
I have two time_point objects in my code and I need to use Boost condition variable for the difference:我的代码中有两个 time_point 对象,我需要使用 Boost 条件变量来区分:
template<class Clock, class Dur = typename Clock::duration>
class Time {
std::chrono::time_point<Clock, Dur> a;
std::chrono::time_point<Clock, Dur> b;
}
....
boost::condition_variable var;
....
var.wait_for(lock, b - a, [](){ /* something here */}); //<---boost cond var
....
How can I convert b - a
to something usable with boost?如何将
b - a
转换为可用于 boost 的东西?
I'd do what I always do: avoid duration_cast
by using arithmetic with UDL values.我会做我一直做的事情:通过对 UDL 值使用算术来避免
duration_cast
。
You have to select a resolution for this, let's choose microseconds:您必须为此选择一个分辨率,让我们选择微秒:
#include <boost/thread.hpp>
#include <chrono>
#include <iostream>
using namespace std::chrono_literals;
template <class Clock, class Dur = typename Clock::duration> //
struct Time {
std::chrono::time_point<Clock, Dur> a = Clock::now();
std::chrono::time_point<Clock, Dur> b = a + 1s;
boost::mutex mx;
void foo() {
//....
boost::condition_variable var;
//....
boost::unique_lock<boost::mutex> lock(mx);
std::cout << "Waiting " << __PRETTY_FUNCTION__ << "\n";
auto s = var.wait_for(lock, boost::chrono::microseconds((b - a) / 1us),
[] { /* something here */
return false;
}); //<---boost cond var
assert(!s);
//....
}
};
int main() {
Time<std::chrono::system_clock>{}.foo();
Time<std::chrono::steady_clock>{}.foo();
std::cout << "\n";
}
Prints (1 second delay each):打印(每个延迟 1 秒):
Waiting void Time<Clock, Dur>::foo() [with Clock = std::chrono::_V2::system_clock; Dur = std::chrono::duration<long int, std::ratio<1, 1000000000>
>]
Waiting void Time<Clock, Dur>::foo() [with Clock = std::chrono::_V2::steady_clock; Dur = std::chrono::duration<long int, std::ratio<1, 1000000000>
>]
I must say I can't fathom a scenario where the wait time for a condition would be specified as the difference between absolute time points, but I guess that's more of a "your problem" here :)我必须说我无法理解将条件的等待时间指定为绝对时间点之间的差异的情况,但我想这更像是一个“你的问题”:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.