Chinaunix首页 | 论坛 | 博客
  • 博客访问: 892345
  • 博文数量: 91
  • 博客积分: 803
  • 博客等级: 准尉
  • 技术积分: 1051
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-24 13:42
文章分类

全部博文(91)

文章存档

2021年(1)

2020年(4)

2019年(4)

2018年(9)

2017年(11)

2016年(11)

2015年(6)

2014年(3)

2013年(28)

2012年(14)

分类: Python/Ruby

2019-09-24 14:24:47

asyncio 是Python3.4引入的标准库,直接内置了对异步IO的支持。
asyncio 的编程模型是一个事件循环,从 asyncio 模块中获取一个 EventLoop 的引用,然后把需要执行的协程扔到 EventLoop 中执行,就实现了异步IO。
当处理流出现IO阻塞时,线程并不会等待IO操作执行完,而是去EventLoop中执行下一个协程。
示例:

点击(此处)折叠或打开

  1. import asyncio
  2. import time
  3. import threading
  4. import sys

  5. # 1号协程
  6. @asyncio.coroutine
  7. def hello():
  8.     print('hstart...',time.time(), threading.currentThread)
  9.     sys.stdout.flush()
  10.     yield from asyncio.sleep(2)
  11.     print('hover',time.time())
  12.     sys.stdout.flush()
  13.  
  14.  
  15. # 2号协程
  16. @asyncio.coroutine
  17. def bey():
  18.     print('bstart……' , time.time(), threading.currentThread)
  19.     sys.stdout.flush()
  20.     yield from asyncio.sleep(3)
  21.     print('bover',time.time())
  22.     sys.stdout.flush()
  23.  
  24.  
  25. # 定义一个eventloop,可以理解为事件池,用于存放 协程
  26. loop = asyncio.get_event_loop()
  27.  
  28. # 当只有一个协程时, 直接加入即可。
  29. # loop.run_until_complete(hello())
  30.  
  31.  
  32. # 当有多个协程时, 要先将多个协程组成一个会话列表 tasks。
  33. # 将 asyncio.wait(tasks) 作为参数传给run_until_complete()
  34. tasks = [hello(), bey()]
  35. loop.run_until_complete(asyncio.wait(tasks))
  36.  
  37. # 关闭
  38. loop.close()

阅读(1175) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~