timer.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. //
  2. // timer.cpp
  3. // ~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2019 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #include <iostream>
  11. #include <boost/asio.hpp>
  12. #include <boost/thread/thread.hpp>
  13. #include <boost/bind.hpp>
  14. class printer
  15. {
  16. public:
  17. printer(boost::asio::io_context& io)
  18. : strand_(boost::asio::make_strand(io)),
  19. timer1_(io, boost::asio::chrono::seconds(1)),
  20. timer2_(io, boost::asio::chrono::seconds(1)),
  21. count_(0)
  22. {
  23. timer1_.async_wait(boost::asio::bind_executor(strand_,
  24. boost::bind(&printer::print1, this)));
  25. timer2_.async_wait(boost::asio::bind_executor(strand_,
  26. boost::bind(&printer::print2, this)));
  27. }
  28. ~printer()
  29. {
  30. std::cout << "Final count is " << count_ << std::endl;
  31. }
  32. void print1()
  33. {
  34. if (count_ < 10)
  35. {
  36. std::cout << "Timer 1: " << count_ << std::endl;
  37. ++count_;
  38. timer1_.expires_at(timer1_.expiry() + boost::asio::chrono::seconds(1));
  39. timer1_.async_wait(boost::asio::bind_executor(strand_,
  40. boost::bind(&printer::print1, this)));
  41. }
  42. }
  43. void print2()
  44. {
  45. if (count_ < 10)
  46. {
  47. std::cout << "Timer 2: " << count_ << std::endl;
  48. ++count_;
  49. timer2_.expires_at(timer2_.expiry() + boost::asio::chrono::seconds(1));
  50. timer2_.async_wait(boost::asio::bind_executor(strand_,
  51. boost::bind(&printer::print2, this)));
  52. }
  53. }
  54. private:
  55. boost::asio::strand<boost::asio::io_context::executor_type> strand_;
  56. boost::asio::steady_timer timer1_;
  57. boost::asio::steady_timer timer2_;
  58. int count_;
  59. };
  60. int main()
  61. {
  62. boost::asio::io_context io;
  63. printer p(io);
  64. boost::thread t(boost::bind(&boost::asio::io_context::run, &io));
  65. io.run();
  66. t.join();
  67. return 0;
  68. }