Condition variables let tasks wait for a shared-state predicate while coordinating through a lock. Recheck the predicate after waking.
Before you start
You should understand processes, threads, memory and basic file operations. Track ownership and state changes over time. For concurrent scenarios, write down at least two possible execution orders; the same instructions can behave differently when scheduling or resource availability changes.
The practical goal is to reason through this situation: A consumer waits while a queue is empty, then checks again before removing an item. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.
Step-by-step walkthrough
Step 1: Write the predicate
A consumer may proceed only when the shared queue is nonempty.
Step 2: Wait under the lock
Waiting coordinates release and reacquisition of the protecting lock.
Step 3: Recheck after wake
Another consumer or a spurious wake can leave the predicate false.
Worked scenario
A consumer waits while a queue is empty, then checks again before removing an item.
acquire lock
while queue is empty:
condition.wait(lock)
item = queue.remove()
release lockThis is pseudocode. A notification is a reason to check state, not a promise that this particular consumer owns an item. Producers modify the predicate’s state under the same synchronization discipline.
Common mistake
Assuming every wake guarantees an item ignores spurious wakeups or another consumer’s progress.
Verify the behavior
Wake two consumers for one item and verify only one consumes while the other waits safely.
Interview exercise
Write the wait pattern.
Answer and reasoning
Hold the lock, loop while the predicate is false, wait, then consume only after the predicate is true.
Continue learning
Compare the scenario with the Operating Systems interview questions and test your understanding with the Operating Systems MCQs. For terminology and implementation details, consult the reference material.