我试图了解 pythons asynico 模块,并在https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task 上遇到了以下代码
import time
import asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
task1 = asyncio.create_task(
say_after(1, 'hello'))
task2 = asyncio.create_task(
say_after(2, 'world'))
print('started at', time.strftime('%X'))
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
print('finished at', time.strftime('%X'))
asyncio.run(main())
事实证明, 可以简单地删除await task2, (或task1,但不能同时删除两者),并且代码似乎在做完全相同的事情。我觉得这很违反直觉,这里发生了什么?感谢您的时间。
相关分类