all Python 3multiprocessingterm
multiprocessing.Condition
synchronization
A condition variable shared between processes: one process waits in wait() or wait_for(), another wakes it with notify() after changing shared state.
Syntax
cond = ctx.Condition(lock=None); with cond: cond.wait_for(pred, timeout); cond.notify_all()
wait() and notify() may only be called with the lock held, otherwise AssertionError, not RuntimeError as in threading. The condition itself must live in shared memory (Value, Array, Manager): a plain variable is per process, leaving the waiter nothing to check. wait_for(predicate, timeout) beats a bare wait(): it rechecks the condition after spurious wakeups and returns its value. Pass the primitive to the child as a Process argument at creation; it cannot go through a Queue or Pool arguments — RuntimeError "should only be shared between processes through inheritance".
Examples
import multiprocessing as mp
def producer(cond, ready):
with cond:
ready.value = 1
cond.notify_all()
if __name__ == '__main__':
ctx = mp.get_context('spawn')
cond, ready = ctx.Condition(), ctx.Value('i', 0, lock=False)
p = ctx.Process(target=producer, args=(cond, ready))
p.start()
with cond:
print(cond.wait_for(lambda: ready.value == 1, timeout=10)) # → True
p.join()
import multiprocessing as mp
if __name__ == '__main__':
cond = mp.get_context('spawn').Condition()
try:
cond.wait(0.1)
except AssertionError as e:
print(e) # → must acquire() condition before using wait()
See also
Open in the full glossarydocs.python.orgReport an inaccuracy