Advertisement
Guest User

Untitled

a guest
Apr 25th, 2014
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. //
  2. // timer.cpp
  3. // ~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2013 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.  
  11. #include <iostream>
  12. #include <boost/asio.hpp>
  13. #include <boost/thread/thread.hpp>
  14. #include <boost/bind.hpp>
  15. #include <boost/date_time/posix_time/posix_time.hpp>
  16.  
  17. class printer
  18. {
  19. public:
  20. printer(boost::asio::io_service& io)
  21. : strand_(io),
  22. timer1_(io, boost::posix_time::seconds(1)),
  23. timer2_(io, boost::posix_time::seconds(1)),
  24. count_(0)
  25. {
  26. timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
  27. timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
  28. }
  29.  
  30. ~printer()
  31. {
  32. std::cout << "Final count is " << count_ << "n";
  33. }
  34.  
  35. void print1()
  36. {
  37. if (count_ < 10)
  38. {
  39. std::cout << "Timer 1: " << count_ << "n";
  40. ++count_;
  41.  
  42. timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));
  43. timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));
  44. }
  45. }
  46.  
  47. void print2()
  48. {
  49. if (count_ < 10)
  50. {
  51. std::cout << "Timer 2: " << count_ << "n";
  52. ++count_;
  53.  
  54. timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1));
  55. timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));
  56. }
  57. }
  58.  
  59. private:
  60. boost::asio::strand strand_;
  61. boost::asio::deadline_timer timer1_;
  62. boost::asio::deadline_timer timer2_;
  63. int count_;
  64. };
  65.  
  66. int main()
  67. {
  68. boost::asio::io_service io;
  69. printer p(io);
  70. boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
  71. io.run();
  72. t.join();
  73.  
  74. return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement