all Python 3threadingterm
threading.Condition
synchronization
A condition variable: a thread waits in wait() until another one changes shared state and calls notify(). The basis of the producer-consumer pattern.
Syntax
cond = threading.Condition(lock=None)
with cond: cond.wait_for(predicate, timeout=None)
with cond: cond.notify(n=1) / cond.notify_all()
wait() and notify() only work while the condition's lock is held (with cond:), otherwise RuntimeError. Waking up does not mean the state you need is there — another thread may have got in first — so the check goes in a while loop, or you call wait_for(predicate), which runs that loop for you. A notify() sent before anyone waits is lost: unlike Event, a condition remembers nothing, only your own state does. For simply passing data between threads queue.Queue is easier, and it is built on the same Condition objects.
Examples
import threading
cond = threading.Condition()
items, result = [], []
def producer():
for i in range(3):
with cond:
items.append(i)
cond.notify()
def consumer():
with cond:
cond.wait_for(lambda: len(items) == 3, timeout=1)
result.append(list(items))
c = threading.Thread(target=consumer)
p = threading.Thread(target=producer)
c.start()
p.start()
c.join()
p.join()
print(result) # → [[0, 1, 2]]
import threading
cond = threading.Condition()
try:
cond.notify() # блокировка условия не захвачена
except RuntimeError as e:
print(e) # → cannot notify on un-acquired lock
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy