【发布时间】:2019-05-22 21:19:52
【问题描述】:
在这里完成newb,阅读Asycnio Tasks,其中有这个例子:
import asyncio
import time
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(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
我对@987654323@最初的理解是阻塞当前函数的执行,等待异步函数返回。
但是在这种情况下,两个协程是同时执行的,这不太符合我对await 的理解。有人可以解释一下吗?
进一步调查,通过在say_after 中添加额外的print,在我看来协程直到await 发生才开始......
import asyncio
import time
async def say_after(delay, what):
print('Received {}'.format(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(f"started at {time.strftime('%X')}")
# Wait until both tasks are completed (should take
# around 2 seconds.)
await task1
await task2
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
打印
started at 13:41:23
Received hello
Received world
hello
world
finished at 13:41:25
【问题讨论】:
标签: python python-asyncio