boost asio io_service 原理及与strand的比较

本文通过示例代码介绍了Boost.Asio库中io_service和strand的区别,展示了如何利用io_service实现并发处理,而使用strand确保任务按顺序执行。文章强调了线程安全的重要性,并对比了io_service和strand在任务调度上的不同表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

io_service一般作为处理工作的work pool。

网络中,作为服务器接收用,可以加速处理收到的信息。主要有post, dispatch, stop, run. 几可常用方法。通常还会用到boost bind一起使用

io_service是并发的,在队列中,有几个run, 就有几个并发进行;而对于strand 是严格顺序进行的调用。

看下面的例子:

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace std;
using namespace boost;
using namespace asio;

typedef boost::asio::io_service ioType;
typedef boost::asio::strand strandType;
ioType m_service;
strandType m_strand(m_service);
boost::mutex m_mutex;

void print( int fatherID)
{
  static int count = 0;
  cout<<"fatherID "<<fatherID<<" "<<endl;
  sleep(1);
  cout<<"count "<<count++<<endl;
}

void ioRun1()
{
  while(1)    {      m_service.run();    }
}

void ioRun2()
{
  while(1)    {      m_service.run();    }
}

void print1()
{
  m_strand.dispatch(bind(print,1));
}

void print2()
{
  m_strand.post(bind(print,2));
}

void print3()
{
  m_strand.post(bind(print,3));
}

int main(void)
{
  boost::thread t0(ioRun1);
  boost::thread t(ioRun2);
  boost::thread t1(print1);
  boost::thread t2(print2);
  boost::thread t3(print3);
  cout<<"231"<<endl;
  t1.join();
  t2.join();
  t3.join();
  t0.join();
  t.join();
  cout<<"24141"<<endl;
  return 0;
}

最终输出结果:

   fatherID 3
 count 0
 fatherID 2
 count 1

 fatherID 1
   count 2

说明这是线程安全的!

但是  而 io_service 不能保证!

参考资料:http://sjtutmz.blog.163.com/blog/static/9888866020119145464870/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值