我的代碼中有兩個 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
....
如何轉換b - a為可通過 boost 使用的東西?
uj5u.com熱心網友回復:
我會做我一直做的事情:避免duration_cast使用 UDL 值的算術。
您必須為此選擇一個解析度,讓我們選擇微秒:
#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";
}
列印(每個延遲 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>
>]
我必須說我無法理解將條件的等待時間指定為絕對時間點之間的差異的情況,但我想這更像是一個“你的問題”:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/486141.html
