asyncio1.py 652 B

1234567891011121314151617181920212223242526272829303132
  1. """
  2. 异步I/O操作 - asyncio模块
  3. Version: 0.1
  4. Author: 骆昊
  5. Date: 2018-03-21
  6. """
  7. import asyncio
  8. import threading
  9. # import time
  10. @asyncio.coroutine
  11. def hello():
  12. print('%s: hello, world!' % threading.current_thread())
  13. # 休眠不会阻塞主线程因为使用了异步I/O操作
  14. # 注意有yield from才会等待休眠操作执行完成
  15. yield from asyncio.sleep(2)
  16. # asyncio.sleep(1)
  17. # time.sleep(1)
  18. print('%s: goodbye, world!' % threading.current_thread())
  19. loop = asyncio.get_event_loop()
  20. tasks = [hello(), hello()]
  21. # 等待两个异步I/O操作执行结束
  22. loop.run_until_complete(asyncio.wait(tasks))
  23. print('game over!')
  24. loop.close()