简体   繁体   中英

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

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. In test , that makes the function wait for 2 seconds until asyncio.sleep has returned, before printing. 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 .

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 :

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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