Linux后台服务器编程。
分类: C/C++
2014-11-03 13:46:35
1:
io_service 与 strand 的关系是什么?
2: strand : /// Provides serialised handler execution.
能够保证线程安全,同时被post 或 dispatch 的方法 不会被并发的执行; 而 io_service 不能保证:
看下面的例子:
#include
#include
#include
#include
#include
#include
#include
#include
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 "<
sleep(1);
cout<<"count "<
}
void ioRun1()
{
while(1)
{
m_service.run();
}
}
//
void ioRun2()
{
while(1)
{
m_service.run();
}
}
void print1()
{
m_strand.dispatch(bind(print,1));
// cout<<"over"<
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"<
t2.join();
t3.join();
t0.join();
t.join();
cout<<"ads"<
}
最终输出结果:
fatherID 3
count 0
fatherID 2
count 1
fatherID 1
count 2
说明这是线程安全的!
但是 而 io_service 不能保证:
更改程序:
void print1()
{
m_service.dispatch(bind(print,1));
// cout<<"over"<
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
signal
asyncWriteRequest(message, m_strand->wrap(bind(
&NetServer::asyncResultHandler, this, _1, handler)), m_timeout);
它应该也是线程安全的。
写的很漂亮。。。。
4:
注意 保证线程安全