gpt4 book ai didi

python - 异步函数不异步工作

转载 作者:行者123 更新时间:2023-12-05 03:31:30 25 4
gpt4 key购买 nike

我有一个问题。

我写了一段模仿http请求的简单代码:

from asyncio import sleep, run


async def get():
print("Started get()")
await sleep(3)
print("Finished get()")


async def async_main():
await get()
await get()
await get()


if __name__ == "__main__":
run(async_main())

我预计结果应该是这样的:

Started get()
Started get()
Started get()
(No output, just wait 3 seconds)
Finished get()
Finished get()
Finished get()

但结果是:

Started get()
(No output, just wait 3 seconds)
Finished get()
Started get()
(No output, just wait 3 seconds)
Finished get()
Started get()
(No output, just wait 3 seconds)
Finished get()

为什么会这样?

最佳答案

像下面这样异步运行任务

async def async_main():
await asyncio.gather(get(), get(), get())

if __name__ == "__main__":
# run(async_main()) or
asyncio.run(async_main())

关于python - 异步函数不异步工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70629400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com