小编Ven*_*Ram的帖子

在 python 中等待多个异步函数

等待多个异步函数并不是真正的异步工作。

例如,我期望下面运行多个await函数的代码在大约 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)
Run Code Online (Sandbox Code Playgroud)
# Working concurrently 
async def async_sleep(n):
    await asyncio.gather(
        asyncio.sleep(n+2),
        asyncio.sleep(n)
    )
Run Code Online (Sandbox Code Playgroud)

python python-asyncio

12
推荐指数
1
解决办法
2万
查看次数

标签 统计

python ×1

python-asyncio ×1