Search code examples
c++boostc++-chrono

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:

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?


Solution

  • I'd do what I always do: avoid duration_cast by using arithmetic with UDL values.

    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):

    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 :)