python3.4中asyncio

1340阅读 0评论2019-09-24 nuoyazhou110
分类:Python/Ruby

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()

上一篇:GO redis连接池DEMO
下一篇:go并发任务超时控制