Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 40 ยท Synchronization and Queues

asyncio Event and Condition: Signaling Between Tasks

Learn asyncio.Event to signal tasks, set, clear and wait, asyncio.Condition for wait_for with shared state, and asyncio.Barrier to line tasks up at a checkpoint.

Locks answer "who may touch this data right now?". Often the real question is different: "tell me when something has happened". A worker must wait until configuration has loaded. A shutdown handler must wake up many tasks at once. A consumer must wait until there is data. asyncio has small primitives for these signals: Event, Condition and Barrier.

asyncio.Event: a flag tasks can wait on

An Event holds a flag that is either clear (False) or set (True). Tasks call await event.wait() and are suspended until someone calls event.set(), which wakes all waiters at once. After that, wait() returns immediately until clear() resets the flag.

Python Waiting for a start signal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All three runners were suspended, then released by one set() call. That one-to-many broadcast is the strength of Event.

Method Meaning
await event.wait() wait until the flag is set (returns immediately if already set)
event.set() set the flag and wake every waiter
event.clear() reset the flag
event.is_set() read the flag

A shutdown signal

The most common use of Event is graceful shutdown. Workers check or await a stop event, and the controller sets it when it is time to leave:

Python Graceful shutdown with an Event

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Waiting on stop.wait() with a timeout makes each worker both periodic and instantly stoppable: when stop.set() runs, the wait ends at once instead of after the remaining sleep.

Events as "ready" flags

Another common pattern is a readiness gate: a task that loads configuration or opens a connection sets an event when it is done; every task that needs the result waits for it first.

Python A readiness gate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The requests start before the configuration exists, wait, and proceed together as soon as set() is called.

asyncio.Condition: wait for a state

An Event carries only a yes/no flag. When tasks must wait for an arbitrary condition on shared data ("the queue is not empty", "at least 3 items are ready"), use a Condition. It combines a lock with a notification mechanism:

  • async with cond: acquires the underlying lock.
  • await cond.wait_for(predicate) releases the lock, sleeps until notified and the predicate is true, then re-acquires the lock.
  • cond.notify(n) / cond.notify_all() wake waiters (must hold the lock).
Python A bounded buffer with Condition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The consumer starts first and finds the buffer empty, so wait_for suspends it and releases the lock, letting the producer in. After each notify() the consumer wakes, re-checks the predicate and takes the item. Always use wait_for with a predicate (or a while loop around wait()), because a woken task must re-check the condition: another task may have consumed the item first.

In practice you rarely build a producer/consumer buffer by hand, because asyncio.Queue does it for you. Conditions shine for custom rules, such as "wait until the total weight is below 100".

asyncio.Barrier: rendezvous

Python 3.11 added asyncio.Barrier(parties). Every task calls await barrier.wait(); none passes until all parties have arrived, then all are released together. It suits phased work: "everyone finish phase 1 before anyone starts phase 2".

Python Two phases separated by a Barrier

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All three "phase 1 done" lines come before any "phase 2" line, even though the workers finish phase 1 at different times.

Choosing the right primitive

Need Use
Protect shared data from interleaving Lock
Broadcast "it happened" (one-way flag) Event
Wait for a condition on shared data Condition
Wait for N tasks to reach a point Barrier
Limit how many run at once Semaphore (next lesson)
Pass items between tasks Queue

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does event.set() do to tasks blocked in await event.wait()?

    An Event is a broadcast: set() releases every waiter, and later wait() calls return immediately until clear().
  2. 2. Why should Condition waiters re-check their predicate after waking?

    Being notified only means the state might have changed. wait_for handles this loop for you.
  3. 3. Which primitive lines up N tasks so none continues until all arrive?

    asyncio.Barrier(N) releases all N waiters once the last one calls wait().
  4. 4. You want a shutdown flag that many workers check. Which is the best fit?

    An Event can be waited on (instant wake-up) and polled with is_set().

Summary

  • Event is a broadcast flag: wait(), set(), clear(), is_set().
  • Use Events for start signals, readiness gates and graceful shutdown.
  • Condition couples a lock with notifications; use wait_for(predicate) and notify for waits on shared state.
  • Barrier(n) holds tasks until n have arrived.

Next: Semaphores and rate limiting