Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Synchronization

When multiple threads or processes access shared resources concurrently, synchronization mechanisms ensure correct behavior. Without synchronization, race conditions lead to corrupted data, lost updates, and unpredictable behavior.

Why Synchronization Matters

// Classic race condition
int counter = 0;

// Thread 1              // Thread 2
counter++;                counter++;
// Could be: load, load, inc, store, inc, store → counter = 1 (not 2!)

The counter++ operation is not atomic. It involves:

  1. Read counter from memory
  2. Increment in register
  3. Write back to memory

If two threads interleave these steps, the result is wrong.

The Critical Section Problem

A critical section is code that accesses shared resources and must not be executed by more than one thread at a time. The solution must satisfy:

  1. Mutual Exclusion: At most one thread in the critical section
  2. Progress: If no thread is in CS, a waiting thread must be allowed to enter
  3. Bounded Waiting: A thread must not wait forever (no starvation)

Chapter Contents

Synchronization Mechanism Comparison

MechanismTypeUse CaseComplexity
MutexBinary lockProtect critical sectionLow
SemaphoreCountingResource pool, signalingMedium
SpinlockBusy-wait lockShort CS, no context switchLow
MonitorHigh-levelObject-oriented syncMedium
Condition VariableSignalingWait for conditionMedium
Read-Write LockMultiple readersRead-heavy workloadsMedium
BarrierSynchronizationWait for all threadsMedium
Lock-free (CAS)Non-blockingHigh-performanceHigh

Interview Quick Facts

  1. Mutex vs Semaphore: Mutex = mutual exclusion (binary, owner-based). Semaphore = signaling/counting (no owner concept).
  2. Spinlock vs Mutex: Spinlock busy-waits (no context switch, good for short CS). Mutex sleeps (context switch, good for long CS).
  3. Monitor = mutex + condition variables + encapsulated data
  4. Deadlock requires all 4 conditions: mutual exclusion, hold-and-wait, no preemption, circular wait

Diagram: Synchronization Hierarchy

graph TD
    A[Shared Resource Access]
    A --> B[Blocking]
    A --> C[Non-Blocking]
    
    B --> D[Mutex]
    B --> E[Semaphore]
    B --> F[Monitor]
    B --> G[Read-Write Lock]
    B --> H[Barrier]
    
    C --> I[Lock-Free CAS]
    C --> J[Wait-Free]
    
    D --> K[Spinlock Variant]
    E --> L[Counting Semaphore]
    E --> M[Binary Semaphore]

Cross-References

  • Deadlocks — what happens when synchronization goes wrong
  • I/O — device synchronization
  • Filesystems — concurrent file access
  • Containers — namespace isolation

Cross References