BoostAsioTest.cc 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <iostream>
  2. #include <boost/asio.hpp>
  3. #include <boost/thread.hpp>
  4. #include <boost/bind.hpp>
  5. #include <boost/date_time/posix_time/posix_time.hpp>
  6. class printer
  7. {
  8. public:
  9. printer(boost::asio::io_service& io) :
  10. strand_(io), timer1_(io, boost::posix_time::seconds(1)), timer2_(io,
  11. boost::posix_time::seconds(1)), count_(0)
  12. {
  13. timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
  14. timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
  15. }
  16. ~printer()
  17. {
  18. std::cout << "Final count is " << count_ << "\n";
  19. }
  20. void print1()
  21. {
  22. if (count_ < 10)
  23. {
  24. std::cout << "Timer 1: " << count_ << "\n";
  25. ++count_;
  26. timer1_.expires_at(timer1_.expires_at()
  27. + boost::posix_time::seconds(1));
  28. timer1_.async_wait(
  29. strand_.wrap(boost::bind(&printer::print1, this)));
  30. }
  31. }
  32. void print2()
  33. {
  34. if (count_ < 10)
  35. {
  36. std::cout << "Timer 2: " << count_ << "\n";
  37. ++count_;
  38. timer2_.expires_at(timer2_.expires_at()
  39. + boost::posix_time::seconds(1));
  40. timer2_.async_wait(
  41. strand_.wrap(boost::bind(&printer::print2, this)));
  42. }
  43. }
  44. private:
  45. boost::asio::strand strand_;
  46. boost::asio::deadline_timer timer1_;
  47. boost::asio::deadline_timer timer2_;
  48. int count_;
  49. };
  50. int main()
  51. {
  52. boost::asio::io_service io;
  53. printer p(io);
  54. boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
  55. io.run();
  56. t.join();
  57. return 0;
  58. }