前言
 
异步操作在计算机软硬件体系中是一个普遍概念,根源在于参与协作的各实体处理速度上有明显差异。软件开发中遇到的多数情况是CPU与IO的速度不匹配,所以异步IO存在于各种编程框架中,客户端比如浏览器,服务端比如node.js。本文主要分析Python异步IO。
 
Python 3.4标准库有一个新模块asyncio,用来支持异步IO,不过目前API状态是provisional,意味着不保证向后兼容性,甚至可能从标准库中移除(可能性极低)。如果关注PEP和Python-Dev会发现该模块酝酿了很长时间,可能后续有API和实现上的调整,但毋庸置疑asyncio非常实用且功能强大,值得学习和深究。
 
示例
 
asyncio主要应对TCP/UDP socket通信,从容管理大量连接,而无需创建大量线程,提高系统运行效率。此处将官方文档的一个示例做简单改造,实现一个HTTP长连接benchmark工具,用于诊断WEB服务器长连接处理能力。
 
功能概述:
每隔10毫秒创建10个连接,直到目标连接数(比如10k),同时每个连接都会规律性的向服务器发送HEAD请求,以维持HTTP keepavlie。
 
代码如下:

点击(此处)折叠或打开

  1. import argparse
  2. import asyncio
  3. import functools
  4. import logging
  5. import random
  6. import urllib.parse
  7. loop = asyncio.get_event_loop()
  8. @asyncio.coroutine
  9. def print_http_headers(no, url, keepalive):
  10. url = urllib.parse.urlsplit(url)
  11. wait_for = functools.partial(asyncio.wait_for, timeout=3, loop=loop)
  12. query = ('HEAD {url.path} HTTP/1.1\r\n'
  13. 'Host: {url.hostname}\r\n'
  14. '\r\n').format(url=url).encode('utf-8')
  15. rd, wr = yield from wait_for(asyncio.open_connection(url.hostname, 80))
  16. while True:
  17. wr.write(query)
  18. while True:
  19. line = yield from wait_for(rd.readline())
  20. if not line: # end of connection
  21. wr.close()
  22. return no
  23. line = line.decode('utf-8').rstrip()
  24. if not line: # end of header
  25. break
  26. logging.debug('(%d) HTTP header> %s' % (no, line))
  27. yield from asyncio.sleep(random.randint(1, keepalive//2))
  28. @asyncio.coroutine
  29. def do_requests(args):
  30. conn_pool = set()
  31. waiter = asyncio.Future()
  32. def _on_complete(fut):
  33. conn_pool.remove(fut)
  34. exc, res = fut.exception(), fut.result()
  35. if exc is not None:
  36. logging.info('conn#{} exception'.format(exc))
  37. else:
  38. logging.info('conn#{} result'.format(res))
  39. if not conn_pool:
  40. waiter.set_result('event loop is done')
  41. for i in range(args.connections):
  42. fut = asyncio.async(print_http_headers(i, args.url, args.keepalive))
  43. fut.add_done_callback(_on_complete)
  44. conn_pool.add(fut)
  45. if i % 10 == 0:
  46. yield from asyncio.sleep(0.01)
  47. logging.info((yield from waiter))
  48. def main():
  49. parser = argparse.ArgumentParser(description='asyncli')
  50. parser.add_argument('url', help='page address')
  51. parser.add_argument('-c', '--connections', type=int, default=1,
  52. help='number of connections simultaneously')
  53. parser.add_argument('-k', '--keepalive', type=int, default=60,
  54. help='HTTP keepalive timeout')
  55. args = parser.parse_args()
  56. logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
  57. loop.run_until_complete(do_requests(args))
  58. loop.close()
  59. if __name__ == '__main__':
  60. main()
测试与分析
 
硬件:CPU 2.3GHz / 2 cores,RAM 2GB
软件:CentOS 6.5(kernel 2.6.32), Python 3.3 (pip install asyncio), nginx 1.4.7
参数设置:ulimit -n 10240;nginx worker的连接数改为10240
 
启动WEB服务器,只需一个worker进程:
  1. # ../sbin/nginx
  2. # ps ax | grep nginx
  3. 2007 ? Ss 0:00 nginx: master process ../sbin/nginx
  4. 2008 ? S 0:00 nginx: worker process
 
启动benchmark工具, 发起10k个连接,目标URL是nginx的默认测试页面:
  1. $ python asyncli.py http://10.211.55.8/ -c 10000
 
nginx日志统计平均每秒请求数:

  1. # tail -1000000 access.log | awk '{ print $4 }' | sort | uniq -c | awk '{ cnt+=1; sum+=$1 } END { printf "avg = %d\n", sum/cnt }'
  2. avg = 548
 
top部分输出:
  1. VIRT   RES   SHR  S %CPU  %MEM   TIME+  COMMAND
  2. 657m   115m  3860 R 60.2  6.2   4:30.02  python
  3. 54208  10m   848  R 7.0   0.6   0:30.79  nginx
 
总结:
1. Python实现简洁明了。不到80行代码,只用到标准库,逻辑直观,想象下C/C++标准库实现这些功能,顿觉“人生苦短,我用Python”。
 
2. Python运行效率不理想。当连接建立后,客户端和服务端的数据收发逻辑差不多,看上面top输出,Python的CPU和RAM占用基本都是nginx的10倍,意味着效率相差100倍(CPU x RAM),侧面说明了Python与C的效率差距。这个对比虽然有些极端,毕竟nginx不仅用C且为CPU/RAM占用做了深度优化,但相似任务效率相差两个数量级,除非是BUG,说明架构设计的出发点就是不同的,Python优先可读易用而性能次之,nginx就是一个高度优化的WEB服务器,开发一个module都比较麻烦,要复用它的异步框架,简直难上加难。开发效率与运行效率的权衡,永远都存在。
 
3. 单线程异步IO v.s. 多线程同步IO。上面的例子是单线程异步IO,其实不写demo就知道多线程同步IO效率低得多,每个线程一个连接?10k个线程,仅线程栈就占用600+MB(64KB * 10000)内存,加上线程上下文切换和GIL,基本就是噩梦。
 
ayncio核心概念
 
以下是学习asyncio时需要理解的四个核心概念,更多细节请看<参考资料>
1. event loop。单线程实现异步的关键就在于这个高层事件循环,它是同步执行的。
2. future。异步IO有很多异步任务构成,而每个异步任务都由一个future控制。
3. coroutine。每个异步任务具体的执行逻辑由一个coroutine来体现。
4. generator(yield & yield from) 。在asyncio中大量使用,是不可忽视的语法细节。
 
参考资料
 
1. asyncio – Asynchronous I/O, event loop, coroutines and tasks, https://docs.python.org/3/library/asyncio.html
2. PEP 3156, Asynchronous IO Support Rebooted: the "asyncio” Module, http://legacy.python.org/dev/peps/pep-3156/
3. PEP 380, Syntax for Delegating to a Subgenerator, http://legacy.python.org/dev/peps/pep-0380/
4. PEP 342, Coroutines via Enhanced Generators, http://legacy.python.org/dev/peps/pep-0342/
5. PEP 255, Simple Generators, http://legacy.python.org/dev/peps/pep-0255/

Python异步IO --- 轻松管理10k+并发连接的更多相关文章

  1. python异步IO编程(一)

    python异步IO编程(一) 基础概念 协程:python  generator与coroutine 异步IO (async IO):一种由多种语言实现的与语言无关的范例(或模型). asyncio ...

  2. python异步IO编程(二)

    python异步IO编程(二) 目录 开门见山 Async IO设计模式 事件循环 asyncio 中的其他顶层函数 开门见山 下面我们用两个简单的例子来让你对异步IO有所了解 import asyn ...

  3. Python - 异步IO\数据库\队列\缓存

    协程 协程,又称微线程,纤程.英文名Coroutine.一句话说明什么是线程:协程是一种用户态的轻量级线程,协程一定是在单线程运行的. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和 ...

  4. Python异步IO

    在IO操作的过程中,当前线程被挂起,而其他需要CPU执行的代码就无法被当前线程执行了. 我们可以使用多线程或者多进程来并发执行代码,为多个用户服务. 但是,一旦线程数量过多,CPU的时间就花在线程切换 ...

  5. Python异步IO之协程(一):从yield from到async的使用

    引言:协程(coroutine)是Python中一直较为难理解的知识,但其在多任务协作中体现的效率又极为的突出.众所周知,Python中执行多任务还可以通过多进程或一个进程中的多线程来执行,但两者之中 ...

  6. python -- 异步IO 协程

    python 3.4 >>> import asyncio >>> from datetime import datetime >>> @asyn ...

  7. python 异步IO

    参考链接:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143208573 ...

  8. Python 异步IO、IO多路复用

    事件驱动模型 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UT ...

  9. Day10 - Python异步IO、Pymysql、paramiko、

    IO多路复用: 参考博客:http://www.cnblogs.com/wupeiqi/p/6536518.html   socket客户端(爬虫): http://www.cnblogs.com/w ...

随机推荐

  1. [Java][RCP] 记 ProgressView的使用

    进度条效果图

  2. python2 编码问题详解

    实例对比 定义 type str unicode print encode('utf8') decode('utf8') encode('unicode-escape') encode('string ...

  3. hdu 5249 KPI

    题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=5249 KPI Description 你工作以后, KPI 就是你的全部了. 我开发了一个服务,取得了 ...

  4. LD_PRELOAD

    下面的helloworld会在屏幕上打印出什么内容? 1 2 3 4 5 6 #include <stdio.h> int main(int argc, char* argv[], cha ...

  5. php读取xml文件内容,并循环写入mysql数据库

    <?php $dbconn = mysql_connect("localhost","root","root"); $db = mys ...

  6. java判断某个字符串包含某个字符串的个数

    /** * 判断str1中包含str2的个数 * @param str1 * @param str2 * @return counter */ public static int countStr(S ...

  7. Xcode 7遇到 App Transport Security has blocked a cleartext HTTP 错误

    今天用Xcode 7 创建新项目用到 URL 发送请求时,报下面的错: “App Transport Security has blocked a cleartext HTTP (http://) r ...

  8. why does angular js rock

    angularjs 入门教程 http://angular-tips.com/blog/2013/08/why-does-angular-dot-js-rock/ Practive the previ ...

  9. 四则运算三+psp0级表格

    一.题目 在四则运算二的基础上,选择一个方向进行拓展,我选择的是增加了答题模块 二.设计思路 1.在上次的基础上,增加了答题模块,每出现一道四则运算题目,便提醒输入结果,如果结果错误,就会提示错误 2 ...

  10. hibernate 注解写在哪?

    是写在get方法上还是 还是成员变量上? 一般 成员变量是私有的,如果写在成员变量上,那么hibernate就能过通过反射机制直接访问到私有变量,破坏了数据的封装性: 所以 :推荐写在方法上,虽然写的 ...