Condition Variables
What is a Condition?
Section titled “What is a Condition?”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
Producer-consumer with Condition
Section titled “Producer-consumer with Condition”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?
Section titled “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
Section titled “🧪 Try It Yourself”Exercise 1 – Condition notify and wait
Section titled “Exercise 1 – Condition notify and wait”Exercise 2 – notify_all
Section titled “Exercise 2 – notify_all”Exercise 3 – Predicate Wait
Section titled “Exercise 3 – Predicate Wait”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading