Code

Gather the Scouts

Awaiting jobs one after another adds their waits together: three 1-second waits take 3 seconds. asyncio.gather() starts them all at once and waits for every one, so the total is about 1 second.

async def main():
    a, b, c = await asyncio.gather(
        fetch_map("Ember"),
        fetch_map("Frost"),
        fetch_map("Moss"),
    )

Two things to remember:

  • Results come back in the order you passed the jobs, not the order they finished.
  • With a list of jobs, unpack it with *: await asyncio.gather(*jobs).
jobs = [fetch_map(name) for name in islands]
maps = await asyncio.gather(*jobs)  # a list

This works because each job hits an await and yields control. The event loop then starts the next job instead of sitting idle.

Assignment

scout() is ready, and it records start/end events in log. scout_all(routes) works but runs scouts one at a time.

  1. Rewrite scout_all(routes) so all scouts run concurrently with asyncio.gather. routes is a list of (island, delay) tuples.
  2. Return the list of results in the same order as routes.