簡體   English   中英

如何將 std::chrono::duration 轉換為提高持續時間

[英]How to convert std::chrono::duration to boost duration

我的代碼中有兩個 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 的東西?

我會做我一直做的事情:通過對 UDL 值使用算術來避免duration_cast

您必須為此選擇一個分辨率,讓我們選擇微秒:

#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>
>]

我必須說我無法理解將條件的等待時間指定為絕對時間點之間的差異的情況,但我想這更像是一個“你的問題”:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM