简体   繁体   English

多个异步调用阻塞

[英]Multiple async calls blocking

My code: 我的代码:

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())

I was expecting for it to sleep for three seconds, then print out 'test' three times, but instead it waits 2 seconds before every 'test' separately (so last 'test' gets printed at 6 seconds). 我期待它睡三秒钟,然后打印出'test'三次,而是在每次'test'之前分别等待2秒(所以最后'test'在6秒打印)。

What have I understood wrong, and how do I fix this to work as I expected? 我理解错了什么,如何按照我的预期解决这个问题呢?

await suspends the execution of the current function until the future has returned. await暂停当前​​函数的执行,直到将来返回。 In test , that makes the function wait for 2 seconds until asyncio.sleep has returned, before printing. test ,这使得函数等待2秒直到asyncio.sleep返回,然后才打印。 In main , it makes the function wait until test has returned (which it does after print which it does after sleep has returned), before continuing on the next line with the next await test . main ,它使函数等待直到test返回(它在print之后它会在sleep返回后执行),然后继续下一行await test

If you want to execute all test at the same time and have them each print at once after two seconds, you can use asyncio.gather : 如果要同时执行所有test并在两秒钟后立即打印它们,则可以使用asyncio.gather

async def main():
    await asyncio.gather(test(2), test(2), test(2))

This schedules three test coroutines on the event loop at the same time and awaits all their combined results, which will arrive in ~2 seconds. 这将同时在事件循环上安排三个test协同程序,并等待它们的所有组合结果,这将在~2秒内到达。

You could also fire and forget the coroutines without awaiting their completion: 你也可以在没有等待完成的情况下解雇并忘记协同程序:

def main():
    asyncio.ensure_future(test(2))
    asyncio.ensure_future(test(2))
    asyncio.ensure_future(test(2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM