liveBook · Manning

Condition

As explained in Python Concurrency with asyncio

A condition is a synchronization primitive that combines a lock for exclusive access with event-based waiting for a state or notification to become true.

A condition is an asyncio synchronization primitive that combines a lock with event-based waiting. It protects shared state while coroutines wait for a notification or a defined state. section 11.5

Use a condition when waiting and exclusive access belong to the same workflow:

  • Acquire the condition with async with before reading or changing shared state. section 11.5
  • Call wait() to release the lock and suspend until another coroutine notifies the condition; the lock is reacquired before work resumes. section 11.5
  • Call notify_all() while holding the condition to wake every waiting task, or use wait_for() to wait until a predicate reports the required state. section 11.5

Waiting for an initialized connection

A Connection can guard its state with asyncio.Condition. execute() waits for _is_initialized instead of querying an unready connection. initialize() changes the state and notifies waiting tasks after startup completes, allowing them to proceed safely.

How Python Concurrency with asyncio covers it

How deep it goes
Explains lock acquisition, notification, lock release and reacquisition, then demonstrates wait_for() for specific states.
Examples
Uses notified worker tasks and a connection that waits for initialization before executing queries.
What it assumes
Assumes basic asyncio coroutines and synchronization concerns while introducing conditions as an infrequent advanced primitive.
What you can do after
Apply asyncio.Condition to coordinate workers and protect shared state while waiting for notifications or state changes.
How it connects
Links conditions with locks, events, shared resources, coroutines, and state predicates.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Concurrency with asyncio. The section links point to the parts of the book it draws on.