您的位置:首页 > 其它

boost asio io_service与 strand 分析

2012-04-10 17:58 405 查看


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:

注意 保证线程安全
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: