异步函数不异步工作
Async function is not working asynchronously
我有一个问题。
我写了一个模仿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()
为什么会这样?
您需要安排协程,显式使用 asyncio.create_task()
或隐式使用 asyncio.gather()
:
from asyncio import sleep, run
async def get():
print("Started get()")
await sleep(3)
print("Finished get()")
async def async_main():
tasks = [asyncio.create_task(get()),
asyncio.create_task(get()),
asyncio.create_task(get())] # Explicit
await asyncio.gather(*tasks)
async def async_main(): # Option 2
await asyncio.gather(get(), get(), get()) # Implicit
if __name__ == "__main__":
run(async_main())
只是 运行 异步任务,如下所示
async def async_main():
await asyncio.gather(get(), get(), get())
if __name__ == "__main__":
# run(async_main()) or
asyncio.run(async_main())
我有一个问题。
我写了一个模仿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()
为什么会这样?
您需要安排协程,显式使用 asyncio.create_task()
或隐式使用 asyncio.gather()
:
from asyncio import sleep, run
async def get():
print("Started get()")
await sleep(3)
print("Finished get()")
async def async_main():
tasks = [asyncio.create_task(get()),
asyncio.create_task(get()),
asyncio.create_task(get())] # Explicit
await asyncio.gather(*tasks)
async def async_main(): # Option 2
await asyncio.gather(get(), get(), get()) # Implicit
if __name__ == "__main__":
run(async_main())
只是 运行 异步任务,如下所示
async def async_main():
await asyncio.gather(get(), get(), get())
if __name__ == "__main__":
# run(async_main()) or
asyncio.run(async_main())