演示boost::asio::deadline_timer如何使用

  1. /* 
  2. 标题:演示boost::asio::deadline_timer如何使用 
  3. 作者:Kagula 
  4. 知识点:[1]boost::asio::strand实例让多根线程逐个执行 
  5.        [2]boost::asio::io_service的run会等待boost::asio::strand实例 
  6.        中的线程全部执行完毕。 
  7. 测试环境:Visual Studio 2013 Update2 
  8. 最后更新日期:2014-06-04 
  9. */  
  10. #include "stdafx.h"  
  11.   
  12. #include <stdio.h>  
  13. #include <boost/asio.hpp>  
  14. #include <boost/thread.hpp>  
  15. #include <boost/bind.hpp>  
  16. #include <boost/date_time/posix_time/posix_time.hpp>  
  17.   
  18. class printer  
  19. {  
  20. public:  
  21.     printer(boost::asio::io_service& io)  
  22.         : strand_(io),  
  23.         timer1_(io, boost::posix_time::seconds(1)),  
  24.         timer2_(io, boost::posix_time::seconds(1)),  
  25.         count_(0)  
  26.     {  
  27.         //boost::asio::strand::wrap()确保print1和pirnt2线程不会同时运行  
  28.         timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));  
  29.         timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));  
  30.     }  
  31.     ~printer()  
  32.     {  
  33.         printf("Final count is %d\n", count_);  
  34.     }  
  35.     //两个回调函数共享 count_ 变量  
  36.     void print1()  
  37.     {  
  38.         if (count_ < 10)  
  39.         {  
  40.             printf("Timer 1: %d \n", count_++);  
  41.             timer1_.expires_at(timer1_.expires_at() + boost::posix_time::seconds(1));  
  42.             timer1_.async_wait(strand_.wrap(boost::bind(&printer::print1, this)));  
  43.         }  
  44.     }  
  45.     void print2()  
  46.     {  
  47.         if (count_ < 10)  
  48.         {  
  49.             printf("Timer 2: %d \n", count_++);  
  50.             timer2_.expires_at(timer2_.expires_at() + boost::posix_time::seconds(1));  
  51.             timer2_.async_wait(strand_.wrap(boost::bind(&printer::print2, this)));  
  52.         }  
  53.     }  
  54. private:  
  55.     boost::asio::strand strand_;  
  56.     boost::asio::deadline_timer timer1_;  
  57.     boost::asio::deadline_timer timer2_;  
  58.     int count_;  
  59. };  
  60.   
  61.   
  62. int _tmain(int argc, _TCHAR* argv[])  
  63. {  
  64.     //等待deadline_timer实例运行完毕  
  65.     boost::asio::io_service io;  
  66.     printer p(io);  
  67.     io.run();  
  68.   
  69.     return 0;  
  70. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值