MiddleCodeCommonNot answered yet
Run three I/O tasks concurrently with asyncio
Complete main so the three fetch calls overlap and finish in ~1s, not ~3s.
Requirements:
- Schedule all three coroutines to run concurrently on one thread.
- Print the list of results once they all complete.
import asyncio
async def fetch(n):
await asyncio.sleep(1) # simulate I/O
return n * 2
async def main():
# your code here
...
asyncio.run(main())
Write the implementation.
Use asyncio.gather to schedule the coroutines concurrently on one thread: await asyncio.gather(fetch(1), fetch(2), fetch(3)). await asyncio.sleep yields control so all three overlap and finish in ~1s, not 3s. A blocking time.sleep would stall the whole loop instead.
- ✗Awaiting each coroutine sequentially, which serializes them to ~3s
- ✗Using
time.sleep(blocking) inside a coroutine and stalling the loop - ✗Calling
asyncio.runper coroutine instead of onegather
- →Why does a blocking call like
time.sleepdefeatasyncioconcurrency? - →How does
asyncio.gatherdiffer fromasyncio.as_completed?
Contents
Task
Implement main so the three fetch I/O tasks run concurrently and finish in about one second.
Solution
import asyncio
async def fetch(n):
await asyncio.sleep(1) # simulate I/O
return n * 2
async def main():
results = await asyncio.gather(fetch(1), fetch(2), fetch(3))
print(results) # [2, 4, 6] after ~1s, not 3s
asyncio.run(main())
Key points
asyncio.gatherschedules the coroutines concurrently on the single event-loop thread.await asyncio.sleepyields control, letting the three waits overlap.- A blocking call (
time.sleep) would stall the whole loop — only non-blocking awaitables work.
Contents