asyncio2.py 573 B

123456789101112131415161718192021222324252627
  1. """
  2. 异步I/O操作 - async和await
  3. Version: 0.1
  4. Author: 骆昊
  5. Date: 2018-03-21
  6. """
  7. import asyncio
  8. import threading
  9. # 通过async修饰的函数不再是普通函数而是一个协程
  10. # 注意async和await将在Python 3.7中作为关键字出现
  11. async def hello():
  12. print('%s: hello, world!' % threading.current_thread())
  13. await asyncio.sleep(2)
  14. print('%s: goodbye, world!' % threading.current_thread())
  15. loop = asyncio.get_event_loop()
  16. tasks = [hello(), hello()]
  17. # 等待两个异步I/O操作执行结束
  18. loop.run_until_complete(asyncio.wait(tasks))
  19. loop.close()