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.Lock — FIFO-fair, NOT reentrant, cancellation-safepredict130 / 161
+150 XP
Task
📝 **Task:** Predict the exact output. Three tasks named A / B / C are scheduled via gather. Each acquires the lock, does some work, and releases. A holds for 20ms; B and C hold for 10ms each. Predict the 6 events in the order they fire. 📋 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


events: list[str] = []


async def critical(lock: asyncio.Lock, name: str, work: float) -> None:
    async with lock:
        events.append(f"{name} acquired")
        await asyncio.sleep(work)
        events.append(f"{name} releasing")


async def main() -> None:
    lock = asyncio.Lock()
    await asyncio.gather(
        critical(lock, "A", 0.02),
        critical(lock, "B", 0.01),
        critical(lock, "C", 0.01),
    )
    for e in events:
        print(e)


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…