Skip to content

Condition Variables

What is a Condition?

A ConditionCondition 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

Producer-consumer with Condition

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()
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()

Why the while loop?

Always re-check the condition after waking:

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

πŸ§ͺ Try It Yourself

Exercise 1 – Condition notify and wait

Exercise 2 – notify_all

Exercise 3 – Predicate Wait

If this helped you, consider buying me a coffee β˜•

Buy me a coffee

Was this page helpful?

Let us know how we did