多个异步调用阻塞
Multiple async calls blocking
我的代码:
import asyncio
async def test(i):
await asyncio.sleep(i)
print('test')
async def main():
await test(2)
await test(2)
await test(2)
asyncio.get_event_loop().run_forever(main())
我原以为它会休眠三秒钟,然后打印出 'test'
三次,但它会在每个 'test'
之前分别等待 2 秒(所以最后一个 'test'
得到6 秒后打印)。
我哪里理解错了,我该如何解决它才能按预期工作?
await
暂停当前函数的执行,直到 future 返回。在 test
中,这使得函数等待 2 秒直到 asyncio.sleep
返回,然后再打印。在 main
中,它让函数等到 test
返回(它在 print
之后执行,它在 sleep
返回之后执行),然后在下一行继续下一个 await test
.
如果你想同时执行所有test
并让它们在两秒后一次打印,你可以使用asyncio.gather
:
async def main():
await asyncio.gather(test(2), test(2), test(2))
这会在事件循环中同时安排三个 test
协程,并等待它们的所有组合结果,这些结果将在大约 2 秒内到达。
您也可以在不等待协同程序完成的情况下触发并忘记它们:
def main():
asyncio.ensure_future(test(2))
asyncio.ensure_future(test(2))
asyncio.ensure_future(test(2))
我的代码:
import asyncio
async def test(i):
await asyncio.sleep(i)
print('test')
async def main():
await test(2)
await test(2)
await test(2)
asyncio.get_event_loop().run_forever(main())
我原以为它会休眠三秒钟,然后打印出 'test'
三次,但它会在每个 'test'
之前分别等待 2 秒(所以最后一个 'test'
得到6 秒后打印)。
我哪里理解错了,我该如何解决它才能按预期工作?
await
暂停当前函数的执行,直到 future 返回。在 test
中,这使得函数等待 2 秒直到 asyncio.sleep
返回,然后再打印。在 main
中,它让函数等到 test
返回(它在 print
之后执行,它在 sleep
返回之后执行),然后在下一行继续下一个 await test
.
如果你想同时执行所有test
并让它们在两秒后一次打印,你可以使用asyncio.gather
:
async def main():
await asyncio.gather(test(2), test(2), test(2))
这会在事件循环中同时安排三个 test
协程,并等待它们的所有组合结果,这些结果将在大约 2 秒内到达。
您也可以在不等待协同程序完成的情况下触发并忘记它们:
def main():
asyncio.ensure_future(test(2))
asyncio.ensure_future(test(2))
asyncio.ensure_future(test(2))