A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Condition Variables: Usage Patterns and Pitfalls

College Depth 106 in the knowledge graph I know this Set as goal
413prerequisites beneath it
See this on the map →
Monitors and Condition VariablesMutual Exclusion and Locks
condition-variables patterns synchronization

Core Idea

Condition variables allow threads to wait for a condition while releasing a mutex. Correct usage requires: holding the lock during wait/signal, re-checking conditions after waking (spurious wakeups occur), and understanding broadcast vs. signal semantics.

How It's Best Learned

Implement bounded buffers and reader-writer locks using condition variables; test for spurious wakeup resilience.

Common Misconceptions

Explainer

You already know what condition variables and mutexes are — a condition variable lets a thread sleep until some condition becomes true, and a mutex protects shared data from concurrent access. The challenge is using them together correctly. The patterns here are not complex in concept, but the pitfalls are subtle enough that even experienced programmers introduce bugs. Learning the canonical patterns now saves you from debugging race conditions that only manifest under heavy load.

The most important pattern is the wait loop. Never write `if (condition) wait(cv, lock)` — always write `while (!condition) wait(cv, lock)`. The reason is spurious wakeups: a thread can be woken from `wait()` even though no other thread called `signal()` or `broadcast()`. This happens because of implementation details in how the OS manages thread scheduling and because of a race called barging — between the moment a signaling thread releases the lock and the waiting thread reacquires it, a third thread can swoop in, acquire the lock, and change the condition back. The `while` loop handles all of these cases: if the thread wakes up and the condition is not actually true, it simply goes back to sleep.

The second critical pattern is the bounded buffer (producer-consumer queue), which uses two condition variables: one for "buffer not full" and one for "buffer not empty." A producer acquires the lock, checks if the buffer is full in a `while` loop (waiting on `not_full` if it is), inserts an item, then signals `not_empty`. A consumer does the mirror image. This pattern generalizes to any situation where threads must wait for different conditions on the same shared state. Using a single condition variable for both conditions technically works with `broadcast()`, but it is wasteful — every wakeup forces all waiting threads to recheck their condition, even when only one type of condition changed.

The choice between signal and broadcast matters for correctness and performance. `signal()` wakes one waiting thread; `broadcast()` wakes all of them. Use `signal()` when any single waiter can make progress (e.g., one item was added to a buffer, so one consumer can proceed). Use `broadcast()` when the state change might allow multiple waiters to proceed, or when different waiters are waiting for different conditions on the same condition variable. A common mistake is calling `signal()` when `broadcast()` is needed — this can cause threads to remain blocked indefinitely because the one thread that was woken cannot actually use the new state, while a thread that could use it stays asleep. When in doubt, `broadcast()` is always safe (it just wastes CPU cycles on unnecessary wakeups), while `signal()` requires you to reason carefully about which waiter will be woken.

Practice Questions 5 questions

Prerequisite Chain

Understanding ZeroThe Number ZeroCounting to FiveCounting to 10Counting to 20Counting a Set of Objects Up to 20Cardinality: The Last Number CountedMatching Numerals to QuantitiesSubitizing Small QuantitiesAddition Within 10Number Bonds to 10Addition Within 20Doubles and Near DoublesDoubles Facts Within 10Near Doubles Facts Within 20Mental Math Strategies for AdditionMental Math: Adding and Subtracting TensAddition Within 100Repeated Addition as MultiplicationMultiplication as Equal GroupsMultiplication: ArraysBasic Multiplication Facts (0s, 1s, 2s, 5s, 10s)Multiplication Facts Within 100Division as Equal SharingDivision as Grouping (Measurement Division)Division: Grouping (Repeated Subtraction) ModelDivision: Fair Sharing ModelDivision as Equal SharingDivision as GroupingBasic Division FactsDivision Facts Within 100Multiplication and Division Fact FamiliesRelationship Between Multiplication and DivisionDivision Facts as Inverse of MultiplicationRemainders and Quotients in DivisionDivision Word ProblemsMulti-Step Word ProblemsSolving Multi-Step Word ProblemsMultiplication Word ProblemsDivision Word ProblemsIntroduction to Long DivisionFactors and MultiplesPrime and Composite NumbersEquivalent FractionsRelating Fractions and DecimalsDecimal Place ValueIntegers and the Number LineComparing and Ordering IntegersAbsolute ValueAdding IntegersSubtracting IntegersMultiplying IntegersIntroduction to ExponentsOrder of OperationsInteger Order of OperationsVariable ExpressionsThe Distributive PropertyVariables and Expressions ReviewIntroduction to PolynomialsAdding and Subtracting PolynomialsMultiplying PolynomialsFactorialPermutationsCombinationsCounting Principles: Addition and Multiplication RulesIntroduction to Graph TheoryPropositional Logic FoundationsLogical EquivalencesBoolean AlgebraBoolean Type and Truth ValuesComparison Operators and Boolean TestsLogical Operators and Boolean AlgebraBoolean Algebra and Fundamental LawsLogic Gates FundamentalsImplementing Boolean Functions with GatesKarnaugh Map SimplificationCombinational Circuit DesignFlip-Flops and LatchesBinary Counters: Design and AnalysisBinary ArithmeticFixed-Point Number RepresentationTwo's Complement RepresentationOverflow and Underflow DetectionBinary Adders: Half-Adders and Full-AddersFull Adder and Carry PropagationCarry Lookahead Adder DesignHalf Adder Circuit DesignMultiplication Circuit DesignSequential Circuit DesignRegisters and Register FilesInstruction Set Architecture (ISA)Kernel Architecture and OS StructureSystem Calls and User/Kernel ModeProcesses and the Process Control BlockProcess Creation: fork() and exec()Process Termination and Resource CleanupProcess States and State TransitionsProcess Model FormalizationContext Switching and CPU DispatchCPU Scheduling FundamentalsRound-Robin (RR) SchedulingFirst-Come-First-Served (FCFS) SchedulingScheduling Fairness and Starvation PreventionThread Scheduling and CoordinationSemaphoresMonitors and Condition VariablesCondition Variables: Usage Patterns and Pitfalls

Longest path: 107 steps · 413 total prerequisite topics

Prerequisites (2)

Leads To (0)

No topics depend on this one yet.