← back to Operating Systems

Synchronization

Wikipedia · wpSynchronization · CC BY-SA 4.0

Synchronization primitives enforce order on concurrent access to shared resources. Mutexes give exclusive access. Semaphores generalize to counting. Monitors bundle the lock with the data. The classic problems (producer-consumer, dining philosophers) test whether your primitive is strong enough.

Mutexes

A mutex (mutual exclusion lock) has two operations: lock and unlock. Only one thread can hold the lock. Others block until it is released. Simple, effective, and the foundation of most synchronization.

Semaphores

A semaphore is an integer with two atomic operations: wait (decrement, block if zero) and signal (increment). A binary semaphore acts like a mutex. A counting semaphore controls access to a pool of resources.

Scheme

Producer-Consumer

One thread produces items into a bounded buffer. Another consumes them. Two semaphores coordinate: one counts empty slots, one counts full slots. A mutex protects the buffer itself.

Scheme

Dining Philosophers

Five philosophers sit around a table, each needing two forks to eat. If every philosopher picks up their left fork simultaneously, nobody can pick up their right fork. Deadlock. Solutions: limit diners, impose ordering, or use a waiter.

P0 P1 P2 P3 P4 F0 F1 F2 F3 F4

Monitors

A monitor bundles the shared data, the operations on it, and the synchronization into one construct. Only one thread can be active inside the monitor at a time. Condition variables let threads wait inside the monitor for specific events.

Neighbors
  • 🔢 Discrete Math Ch.4 — graph theory: the happens-before relation for synchronization primitives is a directed acyclic graph
  • 🔗 Abstract Algebra Ch.1 — groups and atomicity: mutex operations are the OS implementation of atomic group actions on shared state
  • ✎ Proofs Ch.7 — equivalence relations: linearizability defines an equivalence between concurrent and sequential executions

Foundations (Wikipedia)