How do you run multiple coroutines concurrently using asyncio.gather()?
Short answer
asyncio.gather(*coroutines) schedules all given coroutines to run CONCURRENTLY on the event loop and returns a single awaitable that resolves once ALL of them complete, collecting their results in a list matching the input order — much faster than awaiting each one sequentially…
Advertisement
AModel answer
asyncio.gather(*coroutines) schedules all given coroutines to run CONCURRENTLY on the event loop and returns a single awaitable that resolves once ALL of them complete, collecting their results in a list matching the input order — much faster than awaiting each one sequentially when they're independent.
async def fetch(url):
await asyncio.sleep(1) # simulated network call
return f"data from {url}"
async def main():
results = await asyncio.gather(fetch("a"), fetch("b"), fetch("c"))
print(results) # all three run concurrently, total time ~1s, not 3sReal-world example
Fetching data from three independent API endpoints concurrently instead of sequentially, cutting total wait time significantly.
Likely follow-ups
- What happens to the other still-running coroutines if ONE of the gathered coroutines raises an exception?
Related topics