Boost.Asio基础(五) 异步编程初探
异步编程
本节深入讨论异步编程将遇到的若干问题。建议多次阅读,以便吃透这一节的内容,这一节是对整个boost.asio来说是非常重要的。
为什么须要异步
如前所述,通常同步编程要比异步编程更简单。同步编程下,我们非常easy线性地对问题进行考量。函数A调用完,继续运行B。B运行完,继续运行C。以此类推。相对照较直观。而对于异步编程,如果有5个事件,我们非常难知道它们详细的运行顺序,你甚至不知道,它究竟会不会被运行。
尽管编写异步的程序,非常难,可是依旧须要使用这样的方法。
由于server程序须要同一时候并行的处理大量的客户端。并行的客户端越多,异步编程的优势就越明显。
如果有一个server程序,须要同一时候处理1000个并行的客户端,客户端和server之间的通信消息。以’\n’来结尾。
这是同步模式下的代码,使用1个线程:
using namespace boost::asio;
struct client{
ip::tcp::socket sock;
char buff[1024]; //每一个消息最大1024个字节
int already_read; //已经读取了多少字节
};
std::vector<client> clients;
void handle_clients() {
while(true) {
for(int i=0; i<clients.size(); ++i) {
if(clients[i].sock.available() ) on_read(clients[i]));
}
}
}
void on_read(client& c) {
int to_read = std::min(1024 - c.already_read, c.sock.available());
c.sock.read_some(buffer(c.buff + c.already_read, to_read);
c.already_read += to_read;
if(std::find(c.buff, c.buff + c.already_read, '\n') < c.buff + c.already_read) {
int pos = std::find(c.buff, c.buff + c.alread_read, '\n') - c.buff;
std::string msg(c.buff, c.buff + pos);
std::copy(c.buff + pos, c.buff + 1024, c.buff);
c.already_read -= pos;
on_read_msg(c, msg);
}
}
void on_read_msg(client & c, const std::string& msg) {
if(msg == "request_login")
c.sock.write("request_ok\n");
else if ...
}
在任务server程序中,你都须要避免代码被堵塞。看上面的代码,我们希望handle_clients()这个函数尽可能的不被堵塞。
不论什么时候函数堵塞。从客户端发来的消息就会等待。直到函数不堵塞的时候才干来处理它们。为了避免程序被堵塞,我们仅仅在socket中确实有数据的时候才去读取,实现的代码是:
if(clients[i].sock.available() ) on_read(clients[i]));
在on_read函数中,我们仅仅读取socket确实有效的数据;调用read_util(c.sock, buffer(…),’\n’);是非常不好的选择。它会堵塞程序,直到完整的读取了所有的数据才返回。
我们永远不知道究竟什么时候才干读取完成。
程序的瓶颈是on_read_msg()这个函数。所有输入的数据都被卡在这里。on_read_msg()应该尽量避免出现这样的情况,但有时这又是全然没办法避免的。(比方,当socket的缓冲区满了以后,操作必将被堵塞)。
以下是同步模式下的代码,使用10个线程:
using namespace boost::asio;
//...这里的定义和前面一样
bool set_reading() {
boost::mutex::scope_lock lk(cs_);
if(is_reading_) return false;
else { if_reading_ = true; return true; }
}
void unset_reading() {
boost::mutex::scoped_lock lk(cs_);
is_reading_ = false;
}
private:
boost::mutex cs_;
bool is_reading_;
};
std::vector<client> clients;
void handle_clients() {
for(int i=0; i<10; ++i) {
boost::thread(handle_clients_thread);
}
}
void handle_clients_thread() {
while(true) {
for(int i=0; i<clients.size(); ++i) {
if(clients[i].sock.available()) {
if(clients[i].set_reading()) {
on_read(clients[i]);
clients[i].unset_reading();
}
}
}
}
}
void on_read(client & c) {
...
}
void on_read_msg(client & c, const std::string& msg) {
...
}
为了使用多线程,我们须要同步机制,set_reading()和unset_reading()就是在做这个用的。set_reading()。非常重要。它測试当前是否有线程在做读取操作。
能够看出来代码已经比較复杂了。
另一种同步编程的方法,就是每一个client分配一个线程。可是随着并行的客户端数量的增长,这显然是不可行的。
如今我们来看看异步方法。当client请求数据的时候,on_read被调用,发送返回数据,之后又等待下一个请求(运行另一个异步的读操作)。
异步代码,10个线程:
using namespace boost::asio;
io_service service;
struct client {
ip::tcp::socket sock;
streambuf buff;
};
std::vector<client> clients;
void handle_clients() {
for(int i=0; i<clients.size(); ++i) {
async_read_util(clients[i].sock, clients[i].buff, '\n',
boost::bind(on_read, clients[i], _1, _2));
}
for(int i=0; i<10; ++i)
boost::thread(handle_clients_thread);
}
void handle_clients_thread() {
service_run();
}
void on_read(client& c, const error_code& err, size_t read_bytes) {
std::istream in(&c.buff);
std::string msg;
std::getline(in, msg);
if(msg == "request_login")
c.sock.async_write("request_ok\n", on_write);
else if ...
...
//如今在同一个socket上等待下一个读取请求
async_read_util(c.sock, c.buff, '\n',
boost::bind(on_read, c, _1, _2));
}
Boost.Asio基础(五) 异步编程初探的更多相关文章
- C#基础系列——异步编程初探:async和await
前言:前面有篇从应用层面上面介绍了下多线程的几种用法,有博友就说到了async, await等新语法.确实,没有异步的多线程是单调的.乏味的,async和await是出现在C#5.0之后,它的出现给了 ...
- 使用 boost.asio 简单实现 异步Socket 通信
客户端: class IPCClient { public: IPCClient(); ~IPCClient(); bool run(); private: bool connect(); bool ...
- boost asio tcp 多线程异步读写,服务器与客户端。
// server.cpp #if 0 多个线程对同一个io_service 对象处理 用到第三方库:log4cplus, google::protobuf 用到C++11的特性,Windows 需要 ...
- boost asio 学习(五) 错误处理
http://www.gamedev.net/blog/950/entry-2249317-a-guide-to-getting-started-with-boostasio?pg=6 5. Erro ...
- Python Twisted系列教程2:异步编程初探与reactor模式
作者:dave@http://krondo.com/slow-poetry-and-the-apocalypse/ 译者:杨晓伟(采用意译) 这个系列是从这里开始的,欢迎你再次来到这里来.现在我们可 ...
- Boost.Asio基础(三)
Socket控制 以下的函数进行处理一些高级的socket选项: get_io_service():返回io_service实例 get_option(option):返回socket option对 ...
- Boost.Asio基础
http://www.voidcn.com/article/p-exkmmuyn-po.html http://www.voidcn.com/article/p-xnxiwkrf-po.html ht ...
- 温故知新,CSharp遇见异步编程(Async/Await),聊聊异步编程最佳做法
什么是异步编程(Async/Await) Async/Await本质上是通过编译器实现的语法糖,它让我们能够轻松的写出简洁.易懂.易维护的异步代码. Async/Await是C# 5引入的关键字,用以 ...
- [Boost基础]并发编程——asio网络库——异步socket处理
异步服务器端 #include <conio.h> #include <iostream> using namespace std; #include <boost/as ...
随机推荐
- 常用Java片段
1. 字符串与整型的相互转换 String a = String.valueOf(2); //integer to numeric string int i = Integer.parseInt( ...
- js中this的四种使用方法
0x00:js中this的四种调用模式 1,方法调用模式 2,函数调用模式 3,构造器调用模式 4,apply.call.bind调用模式 0x01:第一种:方法调用模式 (也就是用.调用的)this ...
- get the execution time of a sql statement.
declare @d datetimeset @d = GETDATE()select * from dbo.spt_valuesselect [语句执行花费时间(毫秒)]= DATEDIFF(ms, ...
- Python2.7.3 学习——准备开发环境
安装环境搭建参考:http://blog.163.com/sunshine_linting/blog/static/4489332320129187464222/ 第一种方式,通过命令行方式安装Pyt ...
- c++ 学习笔记(常见问题与困惑)(转载)
本问转自: http://www.cnblogs.com/maowang1991/p/3290321.html 1.struct成员默认访问方式是public,而 class默认访问方式是privat ...
- 关于BFC
参考 http://www.html-js.com/article/1866(很棒! 还有栗子) http://www.cnblogs.com/lhb25/p/inside-block-format ...
- 一个失败的操作系统MULTICS
Unix的诞生和Multics(Multiplexed Information and Computing System)是有一定渊源的.当时开发者Brian Kernighan开玩笑地戏称这个不完善 ...
- BZOJ 2002 [Hnoi2010]Bounce 弹飞绵羊(动态树)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=2002 [题目大意] 给出一片森林,操作允许更改一个节点的父亲,查询一个节点的深度. [ ...
- Struts 上下文
Struts 上下文 ActionContext .ServletActionContext 是继承关系 ActionContext ActionContext context = Action ...
- tpopela/vips_java
tpopela/vips_java Implementation of Vision Based Page Segmentation algorithm in Java