boost asio io_service 原理及与strand的比较
来源:互联网 发布:走心机编程指令代码 编辑:程序博客网 时间:2024/05/29 09:06
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/
- boost asio io_service 原理及与strand的比较
- boost::asio::Io_service strand
- boost asio io_service与 strand 分析
- 【Boost】boost库asio详解1——strand与io_service区别
- 【Boost】boost库asio详解1——strand与io_service区别
- 【Boost】boost库asio详解2——strand与io_service区别
- boost库asio详解1——strand与io_service区别
- boost::asio::io_service与socket(C++)
- boost::asio::Io_service
- boost::asio::Io_service
- boost::asio::Io_service
- boost::asio::Io_service
- boost::asio 之io_service
- boost::asio::io_service(之一)
- Boost::asio io_service
- Boost::asio io_service
- io_service类 boost asio
- boost asio strand 类分析
- 单片机中时延函数易常范的错误
- [Windows][VC]开机自动启动程序的几种方法
- vmware linux ubuntu network information(静态和动态桥接以前可以上的,现在都不能上网解决办法)
- 容器find_if函数定义和其第三个参数重载的疑问
- 网络测试工具netperf
- boost asio io_service 原理及与strand的比较
- stl 下字符串匹配与string 相关函数的调用
- C/C++编写dll动态链接库使用操作与非基本类型参数声明错误
- C/C++编写dll动态链接库使用操作与非基本类型参数声明错误(2)
- dll动态链接库之用类写配置文件和调用判断方法接口的实现中遇到的若干问题
- VS2010 如何添加H文件目录和LIB目录
- ubuntu linux mysql 开发模式与连接编译
- 软件版本命名格式
- 建立一个不能打开的文件(占坑)---C语言高级API调用