boost::asio学习之[二]boost::asio::strand

https://blog.csdn.net/xiaoliangsky/article/details/23568671

boost::asio学习之[二]boost::asio::strand

2014年04月13日 00:51:38

阅读数:1456

 
  1. #pragma once

  2.  
  3. #include <boost/bind.hpp>

  4. #include <boost/thread.hpp>

  5. #include <boost/asio.hpp>

  6.  
  7. namespace Strand

  8. {

  9. using namespace boost::asio;

  10. boost::mutex mutex;

  11. void io_run(const boost::shared_ptr<io_service>& io)

  12. {

  13. mutex.lock();

  14. std :: cout << "[" << boost::this_thread::get_id() << "] Thread Start" << std::endl ;

  15. mutex.unlock();

  16.  
  17. io->run();

  18.  
  19. mutex.lock();

  20. std :: cout << "[" << boost::this_thread::get_id() << "] Thread End" << std::endl ;

  21. mutex.unlock();

  22. }

  23.  
  24. void print_num(int x)

  25. {

  26. mutex.lock();

  27. std :: cout << "[" << boost::this_thread::get_id() << "] x: " << x << std::endl ;

  28. mutex.unlock();

  29. }

  30.  
  31. /*

  32. *我们知道在多条thread的程式设计中,对于执行的结果我们是无法预期的。虽然使用mutex可以保证thread-safety,

  33. *但却无法保证工作能够照我们所期望的顺序执行。

  34. *在boost ASIO中提供了strand来解决既能保证thread-safety又能够让工作的顺序能够依照post的顺序执行。执行

  35. *并观察以下的程式结果:

  36. */

  37. void fun_01()

  38. {

  39. boost::shared_ptr<io_service> io(new io_service);

  40. boost::shared_ptr<io_service::work> work(new io_service::work(*io));

  41. io_service::strand strand(*io);

  42. boost::thread_group group;

  43.  
  44. for (int x = 0 ; x < 2; ++x)

  45. {

  46. group.create_thread(boost::bind(&io_run, io));

  47. }

  48.  
  49. boost::this_thread::sleep(boost::posix_time::seconds(1));

  50.  
  51. /* 按顺序执行

  52. strand.post(boost::bind(&print_num, 1));

  53. strand.post(boost::bind(&print_num, 2));

  54. strand.post(boost::bind(&print_num, 3));

  55. strand.post(boost::bind(&print_num, 4));

  56. strand.post(boost::bind(&print_num, 5)); */

  57.  
  58. //随机执行

  59. io->post(boost::bind(&print_num, 1));

  60. io->post(boost::bind(&print_num, 2));

  61. io->post(boost::bind(&print_num, 3));

  62. io->post(boost::bind(&print_num, 4));

  63. io->post(boost::bind(&print_num, 5));

  64.  
  65. work.reset();

  66. group. join_all();

  67.  
  68. system ( "pause" ) ;

  69. }

  70. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值