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

Mutual Exclusion and Locks

College Depth 99 in the knowledge graph ☐ I know this ☆ Set as goal
39topics build on this
364prerequisites beneath it
See this on the map →
The Critical Section Problem and Race Conditions→→Concurrency Control in DatabasesCondition Variables: Usage Patterns and Pitfalls+5 more
synchronization locks critical-sections

Core Idea

Mutual exclusion ensures only one thread executes in a critical section (shared resource access) at a time. Simple locks (mutexes) achieve this via atomic operations. Spinlocks busy-wait; blocking locks suspend threads and use context switching. Fairness, deadlock freedom, and starvation resistance depend on lock implementation.

How It's Best Learned

Implement a spinlock and a blocking lock; measure contention, overhead, and performance under various contention levels.

Explainer

From concurrency and race conditions, you know that when multiple threads access shared data simultaneously and at least one is writing, the result depends on the unpredictable interleaving of their operations. A critical section is a region of code that accesses such shared data and must not be executed by more than one thread at a time. Mutual exclusion is the property that guarantees this: at most one thread is in the critical section at any moment.

A lock (or mutex) is the simplest mechanism to enforce mutual exclusion. The interface is minimal: `acquire()` before entering the critical section and `release()` after leaving. If thread A has acquired the lock, thread B's call to `acquire()` will not return until A calls `release()`. The critical implementation detail is how `acquire()` is made atomic — the check "is the lock free?" and the action "mark it as taken" must happen as a single indivisible step. If they were separate, two threads could both see the lock as free and both claim it, defeating the entire purpose. Hardware provides atomic instructions like test-and-set, compare-and-swap (CAS), or fetch-and-add that make this possible.

The two fundamental lock designs differ in what a thread does while waiting. A spinlock loops continuously, checking the lock in a tight loop (`while (test_and_set(&lock));`). This wastes CPU cycles but avoids the overhead of a context switch, making spinlocks efficient when the critical section is very short and the wait is brief. A blocking lock (or sleeping lock) puts the waiting thread to sleep — removing it from the CPU's run queue — and wakes it when the lock becomes available. This is better when critical sections are long, because the CPU can do useful work running other threads instead of spinning. The tradeoff is the cost of two context switches (sleep and wake) versus the cost of wasted CPU cycles from spinning.

Beyond the basic design, lock implementations must consider fairness and livelock. A naive spinlock can starve some threads if the hardware consistently favors one core's memory access over another. Ticket locks solve this by assigning each waiting thread a number and serving them in order, like a bakery queue. A correct lock must also guarantee deadlock freedom — if the lock is released, some waiting thread must eventually acquire it — and ideally starvation freedom — every thread that requests the lock eventually gets it. These properties are not automatic; they depend on the lock algorithm and the underlying hardware's memory ordering guarantees.

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 → Threads and Concurrency → The Critical Section Problem and Race Conditions → Mutual Exclusion and Locks

Longest path: 100 steps · 364 total prerequisite topics

Prerequisites (1)

Leads To (7)