boost::asio::deadline_timer with std::chrono time values

回眸只為那壹抹淺笑 提交于 2019-12-04 23:08:19

If you are using boost 1.49 or later, ASIO introduced the basic_waitable_timer, which uses C++11 compatible clocks, either from std::chrono or boost::chrono. They also provided pre-defined typedefs for the boost versions of steady_clock, system_clock, and high_resolution_clock. Its functionality is the same as deadline_timer, but uses the C++11 clock mechanisms instead of the boost::posix_time structures.

For earlier versions, you're going to have to pass a traits structure to handle conversion to the type expected by deadline_timer. See the ASIO TimeTraits requirements. Most are trivial, the last is not. So, for example

template<typename Clock>
struct CXX11Traits
{
  typedef typename Clock::time_point time_type;
  typedef typename Clock::duration   duration_type;
  static time_type now()
  {
      return Clock::now();
  }
  static time_type add(time_type t, duration_type d)
  {
      return t + d;
  }
  static duration subtract(time_type t1, time_type t2)
  {
      return t1-t2;
  }
  static bool less_than(time_type t1, time_type t2)
  {
      return t1 < t2;
  }

  static  boost::posix_time::time_duration 
  to_posix_duration(duration_type d1)
  {
    using std::chrono::duration_cast;
    auto in_sec = duration_cast<std::chrono::seconds>(d1);
    auto in_usec = duration_cast<std::chrono::microseconds>(d1 - in_sec);
    boost::posix_time::time_duration result =
      boost::posix_time::seconds(in_sec.count()) + 
      boost::posix_time::microseconds(in_usec.count());
    return result;
  }
};

You would then create deadline timers for each C++11 clock you want to use. The example here is for std::system_clock. You would use this deadline timer as normal.

typedef boost::asio::basic_deadline_timer< 
        std::system_clock,  
        CXX11Traits<std::system_clock>> my_system_clock_deadline_timer 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!