Coordinate State with Events and Conditions
Core idea
Event stores a boolean flag; set wakes waiters and future wait calls succeed until clear. Condition coordinates changes to state guarded by a lock. Use wait_for(predicate) so the predicate is checked under the lock, including after waking. Notification is not a guarantee that the condition is true.
from threading import Thread, Eventready = Event()result = []def worker(): ready.wait() result.append('loaded')t = Thread(target=worker)t.start()ready.set()t.join()print(result)The worker proceeds only after the flag is set.
Expected output:
['loaded']Wait for a state predicate
from threading import Thread, Conditioncv = Condition()items = []def consume(): with cv: cv.wait_for(lambda: bool(items)) print(items.pop(0))t = Thread(target=consume)t.start()with cv: items.append('job') cv.notify()t.join()The predicate works even if the producer updates before the consumer begins waiting.
Expected output:
jobCommon mistake
An Event is not a counter of notifications. Condition.wait releases its lock while waiting and reacquires it before returning; never use a single unguarded check followed by wait.
Practice
Add two items and two consumers using wait_for and notify_all. Collect results and sort them before checking.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Events and conditions
Check your understanding of events and conditions.
What is printed?
from threading import Evente=Event(); e.set()print(e.wait(0))e.clear()print(e.wait(0))What is printed?
from threading import Conditionc=Condition()with c: print(c.wait_for(lambda: True))Why use wait_for rather than assume a notification is enough?
Which primitive represents readiness as a persistent flag?