Gather: Running Multiple Coroutines in Parallel
When working with asyncio, you’ll often want to start several operations at once and wait for all of them to complete. This is exactly what asyncio.gather()
is designed for.
How Gather Works
The gather()
function takes multiple coroutines, turns them into tasks, runs them concurrently, and collects all their results in a single list.
|
|
This example fetches data from three different sources at the same time. Even though the total time of all requests is 6 seconds (3+1+2), the entire operation takes only about 3 seconds - the time of the longest request.
The Shopping Analogy
Think of gather()
like sending multiple family members to shop for different items:
- Mom goes to the bakery (3 minutes)
- Dad goes to the butcher (1 minute)
- Child goes to the produce section (2 minutes)
Instead of taking 6 minutes sequentially, the shopping only takes 3 minutes total (the time of the longest errand) because everyone shops simultaneously.
Key Features of Gather
- Ordered results: Results are returned in the same order as the input coroutines
- Error handling: By default, an error in any coroutine raises an exception
- Cancellation: Cancelling the gather will cancel all unfinished coroutines
Error Handling with Gather
When using gather()
, you can choose how to handle errors:
|
|
Practical Use Cases
gather()
shines when performing multiple independent operations that all need to complete:
- Loading multiple API resources for a dashboard
- Downloading several files simultaneously
- Running database queries in parallel
- Processing multiple items in a batch
By using gather()
effectively, you can dramatically speed up operations that would otherwise run sequentially, making your applications much more efficient.