Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 1 · Concurrency internals · Recapasyncio.Semaphore for backpressurepredict26 / 161
+100 XP
Task
📝 **Question:** Predict the exact output. Five tasks (A-E) all try to enter \`async with sem\` where \`sem = Semaphore(2)\`. They're scheduled by \`gather\` in order. What's the peak in-flight count? In what order do they acquire and release? 📋 Pick the right answer. 💡 **Hint:** Re-read the theory above if unsure.
Predict the output

Read the code carefully

import asyncio

state = {"in_flight": 0, "peak": 0}


async def task(name, sem):
    async with sem:
        state["in_flight"] += 1
        state["peak"] = max(state["peak"], state["in_flight"])
        print(f"acquire:{name}:inflight={state['in_flight']}")
        await asyncio.sleep(0)
        await asyncio.sleep(0)
        state["in_flight"] -= 1
        print(f"release:{name}")


async def main():
    sem = asyncio.Semaphore(2)
    await asyncio.gather(*[task(c, sem) for c in "ABCDE"])
    print(f"peak:{state['peak']}")


asyncio.run(main())

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…