Repository navigation
Operating Systems 05 synchronization
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Race condition
- Wikipedia: Mutual exclusion
- Wikipedia: Semaphore (programming)
- Wikipedia: Monitor (synchronization)
- Wikipedia: Spinlock
- Wikipedia: Producer–consumer problem
- Wikipedia: Readers–writers problem
- Wikipedia: Dining philosophers problem
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapters 6-7
When threads share data, the result can depend on the exact order in which they run. Synchronization is the set of tools (locks, semaphores, condition variables) that force the order to be safe. This is the topic interviewers probe most deeply, often by asking you to write code.
Code on this page is illustrative C with POSIX threads and semaphores. It is written to show the pattern clearly; error checking is omitted.
This page covers race conditions, critical sections and their three requirements, atomic instructions, spinlocks and mutexes, semaphores, condition variables and monitors, and the three classic problems: producer-consumer, readers-writers and dining philosophers. Deadlock is on Deadlock.
| Café | Synchronization |
|---|---|
| One bathroom | A critical section: code that touches shared data |
| One key on a hook | A mutex |
| Take the key, use it, hang it back |
lock() / unlock()
|
| Waiting by the door checking constantly | A spinlock |
| Sitting down until called | A blocking mutex |
| A car park with a "spaces: 5" counter | A counting semaphore |
// illustrative: shared by two threads
int counter = 0;
void *add(void *_) { for (int i = 0; i < 1000000; i++) counter++; return NULL; }counter++ is really three steps:
load r, counter
add r, r, 1
store counter, r
sequenceDiagram
participant A as Thread A
participant M as counter (memory)
participant B as Thread B
A->>M: load (reads 5)
B->>M: load (reads 5)
A->>A: add -> 6
B->>B: add -> 6
A->>M: store 6
B->>M: store 6
Note over M: two increments, value only went up by 1
A race condition is when the result depends on the timing of threads. The code that touches shared data is the critical section.
Sources: Wikipedia: Race condition
| Requirement | Meaning |
|---|---|
| Mutual exclusion | At most one thread is in the critical section at a time |
| Progress | If nobody is inside and someone wants in, someone gets in; no needless blocking |
| Bounded waiting | A waiting thread gets in after a bounded number of others go first (no starvation) |
Peterson's algorithm meets all three for two threads using only loads and stores, and is a common textbook question. On modern CPUs it needs memory barriers to work, because hardware may reorder its loads and stores (see the Architecture wiki: Memory and Ordering). Real systems use atomic instructions instead.
The CPU provides instructions that read and write a location as one indivisible step:
| Primitive | What it does |
|---|---|
| Test-and-set | Set a flag to 1 and return its old value |
| Compare-and-swap (CAS) | If the value equals expected, replace it with new; report success |
| Fetch-and-add | Add to a value and return the old one |
// illustrative: a fixed counter with C11 atomics
#include <stdatomic.h>
atomic_int counter = 0;
atomic_fetch_add(&counter, 1); // one indivisible incrementAll locks are built on these.
// illustrative spinlock using test-and-set
atomic_flag lock = ATOMIC_FLAG_INIT;
void acquire(void) { while (atomic_flag_test_and_set(&lock)) { /* spin */ } }
void release(void) { atomic_flag_clear(&lock); }| Spinlock | Mutex (blocking lock) | |
|---|---|---|
| While waiting | Loops, burning CPU | Thread sleeps; kernel wakes it |
| Good when | The lock is held for a very short time, on multicore | The wait might be long |
| Bad when | Lock held long, or only one core | Very short sections (sleep/wake overhead) |
| Used in | Kernels, interrupt handlers | Most application code (pthread_mutex_t) |
Real mutexes often spin briefly, then sleep (Linux futex-based mutexes do this).
// illustrative: the counter fixed with a mutex
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void *add(void *_) {
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&m);
counter++; // critical section
pthread_mutex_unlock(&m);
}
return NULL;
}Sources: Wikipedia: Spinlock, Wikipedia: Mutual exclusion
A semaphore is an integer with two atomic operations:
| Operation | Also called | Effect |
|---|---|---|
wait(S) |
P, down, sem_wait
|
Decrement; if the result would be negative, block |
signal(S) |
V, up, sem_post
|
Increment; wake one waiting thread if any |
flowchart TD
W["wait(S)"] --> C{"S > 0 ?"}
C -->|"yes"| D["S = S - 1, continue"]
C -->|"no"| B["block on S's queue"]
SG["signal(S)"] --> Q{"anyone blocked?"}
Q -->|"yes"| WK["wake one"]
Q -->|"no"| INC["S = S + 1"]
| Kind | Initial value | Used for |
|---|---|---|
| Binary semaphore | 1 | Mutual exclusion (like a mutex) |
| Counting semaphore | N | N identical resources (buffer slots, connections) |
| Signalling semaphore | 0 | "Wait until event happens" between threads |
| Mutex | Binary semaphore | |
|---|---|---|
| Ownership | Only the thread that locked it may unlock it | Any thread may signal |
| Purpose | Mutual exclusion | Mutual exclusion or signalling |
| Priority inheritance | Often supported | Usually not |
Sources: Wikipedia: Semaphore (programming)
A condition variable lets a thread sleep until some condition on shared data becomes true. It is always used with a mutex.
| Call | Effect |
|---|---|
pthread_cond_wait(&cv, &m) |
Atomically release m and sleep; re-acquire m before returning |
pthread_cond_signal(&cv) |
Wake one waiter |
pthread_cond_broadcast(&cv) |
Wake all waiters |
// illustrative pattern: always re-check in a while loop
pthread_mutex_lock(&m);
while (!ready) // not "if": spurious wakeups, other threads may get there first
pthread_cond_wait(&cv, &m);
/* ready is true and we hold m */
pthread_mutex_unlock(&m);A monitor packages shared data, a lock and condition variables together so that only one thread is inside at a time. Java synchronized methods with wait/notify are a monitor.
Sources: Wikipedia: Monitor (synchronization)
Producers put items into a buffer of N slots; consumers take them out. Producers must wait when it is full, consumers when it is empty.
flowchart LR
P1["Producer"] --> B["Buffer: N slots<br/>empty = free slots<br/>full = filled slots"]
P2["Producer"] --> B
B --> C1["Consumer"]
B --> C2["Consumer"]
// illustrative: three semaphores
sem_t empty; // sem_init(&empty, 0, N) free slots
sem_t full; // sem_init(&full, 0, 0) filled slots
sem_t mutex; // sem_init(&mutex, 0, 1) protects the buffer indices
void producer(item x) {
sem_wait(&empty); // wait for a free slot
sem_wait(&mutex);
buffer[in] = x; in = (in + 1) % N;
sem_post(&mutex);
sem_post(&full); // one more filled slot
}
item consumer(void) {
sem_wait(&full); // wait for a filled slot
sem_wait(&mutex);
item x = buffer[out]; out = (out + 1) % N;
sem_post(&mutex);
sem_post(&empty); // one more free slot
return x;
}Trap: swapping the order to sem_wait(&mutex) then sem_wait(&empty) can deadlock. A producer holding the mutex sleeps on a full buffer, and no consumer can get the mutex to empty it.
Sources: Wikipedia: Producer–consumer problem
Many readers may read together, but a writer needs exclusive access.
// illustrative: "readers-preference" solution
sem_t rw_mutex; // 1: held by a writer, or by the group of readers
sem_t mutex; // 1: protects read_count
int read_count = 0;
void reader(void) {
sem_wait(&mutex);
if (++read_count == 1) sem_wait(&rw_mutex); // first reader locks writers out
sem_post(&mutex);
/* read */
sem_wait(&mutex);
if (--read_count == 0) sem_post(&rw_mutex); // last reader lets writers in
sem_post(&mutex);
}
void writer(void) {
sem_wait(&rw_mutex);
/* write */
sem_post(&rw_mutex);
}This version can starve writers if readers keep arriving. Writer-preference or fair versions exist; in practice use pthread_rwlock_t.
Sources: Wikipedia: Readers–writers problem
Five philosophers sit round a table with one fork between each pair. Each needs both neighbouring forks to eat.
flowchart LR
P0((P0)) --- F0[fork 0] --- P1((P1)) --- F1[fork 1] --- P2((P2)) --- F2[fork 2] --- P3((P3)) --- F3[fork 3] --- P4((P4)) --- F4[fork 4] --- P0
If every philosopher picks up the left fork first, all five can hold one fork and wait forever for the other: deadlock.
| Fix | Why it works |
|---|---|
| Order the forks: always pick the lower-numbered fork first | Breaks circular wait (one philosopher picks right first) |
| Allow at most 4 to sit at once (a semaphore of 4) | At least one can always get both forks |
| Pick up both forks only if both are free (inside a monitor) | No one holds one fork while waiting |
Sources: Wikipedia: Dining philosophers problem
-
counter++andx = x + 1are not atomic. - Always wait on a condition variable inside a
whileloop, not anif. - In producer-consumer, wait on the counting semaphore before the mutex.
-
volatilein C does not make code thread-safe; use atomics or locks. - Hold locks for as short a time as possible; never do slow I/O while holding a lock if you can avoid it.
- What is a race condition? A bug where the outcome depends on the relative timing of threads accessing shared data, at least one of them writing.
- Mutex vs semaphore? A mutex is a lock with an owner, for mutual exclusion. A semaphore is a counter that any thread can signal, for counting resources or signalling events.
- Spinlock vs mutex: when would you use a spinlock? For very short critical sections on a multicore machine, or in kernel code that cannot sleep (interrupt context).
-
Why must
cond_waitbe in a loop? Wakeups can be spurious, and another thread may have consumed the condition before this one re-acquires the lock. -
Write producer-consumer with semaphores. Use
empty= N,full= 0,mutex= 1, as above. - How do you avoid deadlock in dining philosophers? Impose a global order on the forks, or limit the number of diners to N − 1.
- What does CAS do and how is a lock built from it? It atomically swaps a value only if it equals an expected value; a lock loops on CAS(lock, 0, 1).
- A critical section needs mutual exclusion, progress and bounded waiting.
- Locks are built on atomic instructions; spinlocks busy-wait, mutexes sleep.
- Semaphores count resources; condition variables wait for a condition under a mutex. Know the three classic problems.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look