Doing waits together: gather and tasks
🌍 In real life. A good waiter takes table 1's order to the kitchen, and while that food cooks, takes table 2's order. They don't stand at the kitchen door until table 1's plate is ready. Nobody works faster; the waits just overlap.
Two ways to make waits overlap, step by step:
await asyncio.gather(a(), b(), c())starts all of them, waits until every one is finished, and gives back their results in a list, in the order you passed them (not the order they finished)- the whole thing takes about as long as the longest wait, not all the waits added up
task = asyncio.create_task(a())startsa()as soon as the current coroutine pauses;await tasklater collects its result. It's like ordering at the counter, then doing something else until it's ready
The idea in one sentence: asyncio.gather(a(), b()) (or tasks made with asyncio.create_task) runs several coroutines at once, so their waits overlap and the total time is about the longest wait, not the sum.
Its words:
- concurrency: making progress on several jobs by switching while each waits
await asyncio.gather(...): run them together and get all results, in the order given- task: a coroutine scheduled to run in the background,
asyncio.create_task(coro)
Watch the waits overlap. The same tea and toast as last lesson, now with gather. Both start at 0.0 s; the event loop hops between lanes, and toast finishes first. It's all done at 0.3 s instead of 0.4 s, and the results still come back as ['tea', 'toast'].
With three dishes the saving grows: 0.2 + 0.5 + 0.1 would be 0.8 seconds one after the other, but together it's just the longest wait, 0.5.
import asyncio
async def cook(dish, secs):
print("start", dish)
await asyncio.sleep(secs)
print("done", dish)
return dish
async def main():
kettle = asyncio.create_task(cook("tea", 0.2))
print("kettle ordered")
toast = await cook("toast", 0.1)
tea = await kettle
print([toast, tea])
asyncio.run(main())Why does it save time? Nothing runs faster: the tea still takes 0.2 s and the toast 0.1 s. But while one is waiting, the event loop starts the other, so the waits happen at the same time. Three dishes of 0.2, 0.5 and 0.1 s take 0.5 s together instead of 0.8 s.
Mistakes and edge cases.
- Awaiting one by one.
await a()thenawait b()waits for a before starting b: no overlap. - Forgetting await on gather.
asyncio.gather(...)withoutawaitnever waits for the results. - Expecting results in finishing order. gather returns them in the order you gave, even if the second finished first.
- A CPU-heavy coroutine. Overlapping only helps with waiting; a long calculation with no
awaitblocks everyone else.
Quiz
What does this print?
import asyncio async def slow(name, secs): await asyncio.sleep(secs) return name async def main(): print(await asyncio.gather(slow("a", 0.2), slow("b", 0.1))) asyncio.run(main())What does this print?
import asyncio async def cook(dish, secs): print("start", dish) await asyncio.sleep(secs) print("done", dish) async def main(): await asyncio.gather(cook("rice", 0.2), cook("egg", 0.1)) asyncio.run(main())Roughly how long does
await asyncio.gather(asyncio.sleep(0.3), asyncio.sleep(0.1))take?- About 0.3 seconds
- About 0.4 seconds
- About 0.1 seconds
What does
asyncio.create_task(cook())do?- Schedules cook to start soon and gives back a task you can await later
- Runs cook to the end before going on
- Starts cook on another thread
What does this print?
import asyncio async def job(name): print("run", name) await asyncio.sleep(0.1) async def main(): task = asyncio.create_task(job("a")) print("made task") await task asyncio.run(main())These two waits should overlap, but the program takes their sum. Which line should gather them instead?
import asyncio async def cook(name, secs): await asyncio.sleep(secs) return name async def main(): tea = await cook("tea", 0.2) toast = await cook("toast", 0.1) print(tea, toast) asyncio.run(main())
Coding tasks
fetchis written for you: it waits a little and gives back the name in capitals, writing tolog. Writeasync def fetch_all(names)withasyncio.gather: fetch every name at the same time and give back the results in a list, in the order ofnames.boilandtoastare written for you. Finishasync def breakfast(): startboil()as a task withasyncio.create_task, thenawait toast(), then await the task, so the kettle boils while the toast cooks. Give backlog.