Predict the output
What does the program print?
import asyncio
async def handle(i: int, done: list[int]) -> None:
await asyncio.sleep(0.05)
done.append(i)
async def main() -> None:
done: list[int] = []
accepting = True
in_flight = {asyncio.create_task(handle(i, done)) for i in range(3)}
# SIGTERM arrives: stop taking new work, finish what's in flight
accepting = False
await asyncio.wait_for(asyncio.gather(*in_flight), timeout=5)
print(accepting, sorted(done))
asyncio.run(main())Hint 1 of 1
What does gather wait for?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A False [0, 1, 2]
Correct. Intake stops, and all three in-flight requests finish before exit.
On SIGTERM the server stops accepting, then waits for in-flight work with a deadline. The flag is cleared before the wait, and gather lets all three 50 ms handlers finish well inside the 5-second timeout.
Why not the others?
- B
True [0, 1, 2]. accepting is set to False before draining. - C
False []. gather waits for the in-flight tasks. - D A TimeoutError. Each takes 0.05 s, well inside 5 s.