You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

协程笔记.py 748B

1 year ago
12345678910111213141516171819202122232425262728293031323334
  1. import asyncio
  2. import time
  3. async def sleep(delay):
  4. time.sleep(delay)
  5. print("1111")
  6. async def say_after(delay, what):
  7. await sleep(delay)
  8. print(what)
  9. async def main():
  10. task1 = asyncio.create_task(say_after(1, 'hello'))
  11. task2 = asyncio.create_task(say_after(2, 'world'))
  12. # await task1
  13. # await task2
  14. await asyncio.gather(task1, task2)
  15. # await say_after(1, 'hello')
  16. # await say_after(2, 'world')
  17. start = time.time()
  18. loop = asyncio.new_event_loop()
  19. print(loop)
  20. asyncio.set_event_loop(loop)
  21. task1 = loop.create_task(say_after(1, 'hello'))
  22. task2 = loop.create_task(say_after(2, 'world'))
  23. loop.run_until_complete(asyncio.wait([task1, task2]))
  24. loop.close()
  25. # asyncio.run(main())
  26. print(time.time() - start)