Predict the output
Three 1-second sleeps run concurrently. Roughly how long does it take?
import asyncio
import time
async def main() -> None:
t = time.perf_counter()
async with asyncio.TaskGroup() as tg:
for _ in range(3):
tg.create_task(asyncio.sleep(1))
print(round(time.perf_counter() - t))
asyncio.run(main())Hint 1 of 1
Do the sleeps wait one after another?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 1
Correct. The three sleeps wait at the same time on one loop.
asyncio.sleep gives control back to the event loop, so all three timers wait together. The TaskGroup exits once the last finishes, after about 1 second in total.
Why not the others?
- B
3. That's sequential awaiting. - C
0. Each sleep still takes a second. - D It raises: TaskGroup needs results. Tasks can return None.