Sweaty Imposter

Condition Variable / Monitor

TechniqueConcurrencyMidSeniorUpdated
Wait on a predicate while holding a lock; another thread signals when the predicate may now be true, atomically releasing and re-acquiring the lock.

When to Use Condition Variable / Monitor

Producer-consumer coordination, bounded queues, anything where a thread needs to block until 'state X is true' without busy-waiting.

In Practice

Java's Object.wait/notify and Condition.await/signal (used inside ArrayBlockingQueue). pthread pthread_cond_t. Python's threading.Condition.

Sketch

Python

lock = threading.Lock()
cv = threading.Condition(lock)
queue = []

def consume():
    with cv:
        while not queue:
            cv.wait()
        return queue.pop(0)

def produce(item):
    with cv:
        queue.append(item)
        cv.notify()

How Condition Variable / Monitor Comes Up in Interviews

Scenario

You're implementing a bounded blocking queue from primitives. A consumer arrives and the queue is empty. Busy-waiting burns CPU; you need the consumer to sleep until a producer enqueues, then wake exactly when that happens.

A condition variable atomically releases the lock and sleeps until signaled. On signal it re-acquires the lock and rechecks the predicate. Two semaphores can encode the same pattern but condition variables are the textbook primitive and what ArrayBlockingQueue uses internally.