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 8 · Async correctness patternsasyncio.Semaphore — bounded concurrency without blocking the looppredict126 / 161
+150 XP
Task
📝 **Task:** Predict the exact output. The Semaphore caps concurrency at 2; 5 named tasks are scheduled via gather. Each task returns its own name. Predict the LIST that gather returns — pay attention to whether the order in the output is the SUBMISSION order or the COMPLETION order. 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

import asyncio


async def fetch(sem: asyncio.Semaphore, name: str) -> str:
    async with sem:
        # Stand-in for a real I/O call.
        await asyncio.sleep(0.001)
        return name


async def main() -> list[str]:
    sem = asyncio.Semaphore(2)
    names = ["a", "b", "c", "d", "e"]
    results = await asyncio.gather(*[fetch(sem, n) for n in names])
    return results


print(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…