boost asio high_resolution_timer 的正确用法

#include   
#include 
#include 
#include 
using namespace std;

#define NOW_TICKS_US  chrono::duration_cast(chrono::steady_clock::now().time_since_epoch()).count()

class TestUnit
{
public:
  TestUnit():
  m_io_(),
  m_ht_(m_io_)
  {
    m_ht_.expires_after(std::chrono::milliseconds(m_interval_));
    m_ht_.async_wait(boost::bind(&TestUnit::Print, this,&m_ht_));
    m_thread_ = std::make_shared(&TestUnit::Run, this);
  }
  ~TestUnit()
  {
    m_io_.stop(); 
    m_thread_->join();
  };
  TestUnit(const TestUnit& other) = default;
  TestUnit(TestUnit&& other) noexcept = default;
  TestUnit& operator=(const TestUnit& other) = default;
  TestUnit& operator=(TestUnit&& other) noexcept = default;
  void Print(boost::asio::high_resolution_timer* pt)
  {
    cout <<"Test "<< NOW_TICKS_US - m_d_ << endl;
    m_d_ = NOW_TICKS_US;
    pt->expires_after(std::chrono::milliseconds(m_interval_));
    pt->async_wait(boost::bind(&TestUnit::Print,this, pt));
  }
  void Run() { m_io_.run(); }
private:
  int m_interval_ = 100;
  boost::asio::io_service m_io_;
  boost::asio::high_resolution_timer m_ht_;
  long long m_d_ = 0;
  std::shared_ptr m_thread_;
};

int main()
{
  TestUnit u;
  system("pause");
  return 0;
}

 

你可能感兴趣的:(boost)