Skip to content

Condition Variables

A Condition is used when threads need to:

  • wait until a condition becomes true (e.g., “buffer not empty”)
  • notify others when the state changes

It combines:

  • a lock
  • a wait/notify mechanism
condition_example.py
import threading
import time
 
items = []
cond = threading.Condition()
 
 
def producer():
    for i in range(5):
        time.sleep(0.2)
        with cond:
            items.append(i)
            print("produced", i)
            cond.notify()  # wake one waiting consumer
 
 
def consumer():
    for _ in range(5):
        with cond:
            while not items:
                cond.wait()  # release lock and wait
            v = items.pop(0)
        print("consumed", v)
 
 
p = threading.Thread(target=producer)
c = threading.Thread(target=consumer)
 
p.start(); c.start()
p.join(); c.join()
sketch wait_for re-checks the condition; wait just believes you p5.js
A waiting thread can be woken before the thing it is waiting for has actually happened -- by a premature notify, or by a spurious wake-up the operating system is allowed to deliver. Measured: with a notify sent while the predicate was still False, the plain wait thread woke and carried straight on with ready still False. The wait_for thread woke, re-checked, found the predicate false and went back to waiting, proceeding only once the value really changed. That re-check is the entire difference.

Always re-check the condition after waking:

  • spurious wakeups can happen
  • another consumer might have consumed the item first

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading