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.Event — one-shot broadcast that stays setpredict131 / 161
+150 XP
Task
📝 **Task:** Predict the exact output, in order. Three workers wait on the same Event. After two scheduling ticks (so all three workers reach `await event.wait()`), the main coroutine sets the event. All workers fire in submission order. A LATE waiter then arrives — the event is still set, so it passes through immediately. 📋 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 worker(ready: asyncio.Event, name: str) -> None:
    events.append(f"{name} waiting")
    await ready.wait()
    events.append(f"{name} go")


async def main() -> None:
    ready = asyncio.Event()

    w1 = asyncio.create_task(worker(ready, "w1"))
    w2 = asyncio.create_task(worker(ready, "w2"))
    w3 = asyncio.create_task(worker(ready, "w3"))

    # Two scheduling ticks so all 3 workers reach their await ready.wait().
    await asyncio.sleep(0)
    await asyncio.sleep(0)

    events.append("setting event")
    ready.set()

    await asyncio.gather(w1, w2, w3)

    # Late waiter — event stays set, so this never blocks.
    events.append("late waiter")
    await ready.wait()
    events.append("late waiter past")

    print(f"event set: {ready.is_set()}")
    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…