【发布时间】:2019-08-16 03:56:06
【问题描述】:
等待多个异步函数并不是真正异步工作,例如,我期望下面的代码在 ~6 秒内运行,但它像同步代码一样运行并在 ~10 秒内执行。 但是当我在 asyncio.gather 中尝试它时,它会在大约 6 秒内执行。
谁能解释为什么会这样?
#Not working concurrently
async def async_sleep(n):
await asyncio.sleep(n+2)
await asyncio.sleep(n)
start_time = time.time()
asyncio.run(async_sleep(4))
end_time = time.time()
print(end_time-start_time)
#Working concurrently
async def async_sleep(n):
await asyncio.gather(asyncio.sleep(n+2),
asyncio.sleep(n))
【问题讨论】:
标签: python python-asyncio