Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asyncio gather scheduling order guarantee

Is it guaranteed that coroutines that are arguments to asyncio.gather will be scheduled with order preserved? Consider following example:

import asyncio

async def coro(i):
    print('{i} finished'.format(i=i))

async def main():
    await asyncio.gather(
            coro(0),
            coro(1),
            coro(2),
            coro(3),
            coro(4),
    )

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

and the result:

0 finished
1 finished
2 finished
3 finished
4 finished
like image 642
pbn Avatar asked Feb 13 '19 11:02

pbn


People also ask

Does Asyncio gather return in the same order?

gather() runs multiple asynchronous operations and wraps a coroutine as a task. The asyncio. gather() returns a tuple of results in the same order of awaitables.

What is Asyncio ensure Future?

ensure_future is a method to create Task from coroutine . It creates tasks in different ways based on argument (including using of create_task for coroutines and future-like objects).

Is Asyncio a concurrency?

Python Concurrency with asyncio introduces asynchronous, parallel, and concurrent programming through hands-on Python examples. Hard-to-grok concurrency topics are broken down into simple flowcharts that make it easy to see how your tasks are running.

What Asyncio gather returns?

Concurrent Functions asyncio. gather : takes a sequence of awaitables, returns an aggregate list of successfully awaited values. asyncio. shield : prevent an awaitable object from being cancelled.


1 Answers

From Python documentation

awaitable asyncio.gather(*aws, loop=None, return_exceptions=False)

Run awaitable objects in the aws sequence concurrently.

If any awaitable in aws is a coroutine, it is automatically scheduled as a Task.

If all awaitables are completed successfully, the result is an aggregate list of returned values. The order of result values corresponds to the order of awaitables in aws.

So the order of result values is preserved, but the execution order is not.

like image 97
Vlad Bezden Avatar answered Sep 28 '22 14:09

Vlad Bezden