boost asio io_service 原理及与strand的比较
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/