boost asio io_service与 strand 分析

1:

    io_service 与 strand 的关系是什么?

2: strand : /// Provides serialised handler execution.

      能够保证线程安全,同时被post 或 dispatch 的方法 不会被并发的执行;

      而 io_service 不能保证:

   看下面的例子:

   #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)
{
//  boost::mutex::scoped_lock lock(m_mutex);
  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));
//  cout<<"over"<<endl;
}

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

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

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

最终输出结果:

   fatherID 3
 count 0
 fatherID 2
 count 1

 fatherID 1
   count 2

说明这是线程安全的!

但是  而 io_service 不能保证:

更改程序:


void print1()
{
  m_service.dispatch(bind(print,1));
//  cout<<"over"<<endl;
}

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

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

 fatherID 3
fatherID 2
count 0
fatherID 1
count 1
count 2

很显然,这里存在并发的问题

3:

  wrapper 包裹器:

   * This function is used to create a new handler function object that, when
   * invoked, will automatically pass the wrapped handler to the strand's
   * dispatch function.

廖师兄的code:

    enum OperateResult
        {
            Success = 0,
            Failed,
            Timeout,
        };
            typedef boost::function<void(OperateResult)> ResultHandlerType;
            signal<void(const NetMessage &message, ResultHandlerType callback,
                    int timeout)> asyncWriteRequest;

 asyncWriteRequest(message, m_strand->wrap(bind(
            &NetServer::asyncResultHandler, this, _1, handler)), m_timeout);

它应该也是线程安全的。

写的很漂亮。。。。

4:

  注意 保证线程安全

转载于:https://www.cnblogs.com/wangshuai901/archive/2011/09/28/2194393.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值