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 Zero → The Number Zero → Counting to Five → Counting to 10 → Counting to 20 → Counting a Set of Objects Up to 20 → Cardinality: The Last Number Counted → Matching Numerals to Quantities → Subitizing Small Quantities → Addition Within 10 → Number Bonds to 10 → Addition Within 20 → Doubles and Near Doubles → Doubles Facts Within 10 → Near Doubles Facts Within 20 → Mental Math Strategies for Addition → Mental Math: Adding and Subtracting Tens → Addition Within 100 → Repeated Addition as Multiplication → Multiplication as Equal Groups → Multiplication: Arrays → Basic Multiplication Facts (0s, 1s, 2s, 5s, 10s) → Multiplication Facts Within 100 → Division as Equal Sharing → Division as Grouping (Measurement Division) → Division: Grouping (Repeated Subtraction) Model → Division: Fair Sharing Model → Division as Equal Sharing → Division as Grouping → Basic Division Facts → Division Facts Within 100 → Multiplication and Division Fact Families → Relationship Between Multiplication and Division → Division Facts as Inverse of Multiplication → Remainders and Quotients in Division → Division Word Problems → Multi-Step Word Problems → Solving Multi-Step Word Problems → Multiplication Word Problems → Division Word Problems → Introduction to Long Division → Factors and Multiples → Prime and Composite Numbers → Equivalent Fractions → Relating Fractions and Decimals → Decimal Place Value → Integers and the Number Line → Comparing and Ordering Integers → Absolute Value → Adding Integers → Subtracting Integers → Multiplying Integers → Introduction to Exponents → Order of Operations → Integer Order of Operations → Variable Expressions → The Distributive Property → Variables and Expressions Review → Introduction to Polynomials → Adding and Subtracting Polynomials → Multiplying Polynomials → Factorial → Permutations → Combinations → Counting Principles: Addition and Multiplication Rules → Introduction to Graph Theory → Propositional Logic Foundations → Logical Equivalences → Boolean Algebra → Boolean Type and Truth Values → Comparison Operators and Boolean Tests → Logical Operators and Boolean Algebra → Boolean Algebra and Fundamental Laws → Logic Gates Fundamentals → Implementing Boolean Functions with Gates → Karnaugh Map Simplification → Combinational Circuit Design → Flip-Flops and Latches → Binary Counters: Design and Analysis → Binary Arithmetic → Fixed-Point Number Representation → Two's Complement Representation → Overflow and Underflow Detection → Binary Adders: Half-Adders and Full-Adders → Full Adder and Carry Propagation → Carry Lookahead Adder Design → Half Adder Circuit Design → Multiplication Circuit Design → Sequential Circuit Design → Registers and Register Files → Instruction Set Architecture (ISA) → Kernel Architecture and OS Structure → System Calls and User/Kernel Mode → Processes and the Process Control Block → Process Creation: fork() and exec() → Process Termination and Resource Cleanup → Process States and State Transitions → Process Model Formalization → Context Switching and CPU Dispatch → CPU Scheduling Fundamentals → Round-Robin (RR) Scheduling → First-Come-First-Served (FCFS) Scheduling → Scheduling Fairness and Starvation Prevention → Thread Scheduling and Coordination → Semaphores → Monitors and Condition Variables → Condition 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.