Predict the output
Twenty tasks share a semaphore of 3. What's the highest number running at once?
import asyncio
running = peak = 0
async def call(sem: asyncio.Semaphore) -> None:
global running, peak
async with sem:
running += 1
peak = max(peak, running)
await asyncio.sleep(0.01)
running -= 1
async def main() -> None:
sem = asyncio.Semaphore(3)
async with asyncio.TaskGroup() as tg:
for _ in range(20):
tg.create_task(call(sem))
print(peak)
asyncio.run(main())Hint 1 of 1
What does Semaphore(3) admit?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 3
Correct. The semaphore admits three at a time; the rest wait.
A semaphore is a counter of free slots: async with takes one and gives it back on exit. With 3 slots, a fourth task waits until one of the first three finishes, so the peak is 3.
Why not the others?
- B
20. That's unbounded fan-out. - C
1. The semaphore allows three. - D
17. Waiting tasks don't run.