Skip to content

Operating Systems 05 synchronization

Mugundan edited this page Nov 27, 2026 · 1 revision

Synchronization

Relevant source files

The following references were used as context for generating this wiki page:

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.

Purpose and Scope

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.

The Bathroom Key Analogy

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

The Race Condition

// 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
Loading

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

What a Correct Solution Needs

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.

Hardware Atomics

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 increment

All locks are built on these.

Spinlocks and Mutexes

// 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

Semaphores

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"]
Loading
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 versus Binary Semaphore

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)

Condition Variables and Monitors

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)

Classic Problem 1: Producer-Consumer (Bounded Buffer)

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"]
Loading
// 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

Classic Problem 2: Readers-Writers

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

Classic Problem 3: Dining Philosophers

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
Loading

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

Common Traps

  • counter++ and x = x + 1 are not atomic.
  • Always wait on a condition variable inside a while loop, not an if.
  • In producer-consumer, wait on the counting semaphore before the mutex.
  • volatile in 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.

Interview Questions

  1. 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.
  2. 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.
  3. 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).
  4. Why must cond_wait be in a loop? Wakeups can be spurious, and another thread may have consumed the condition before this one re-acquires the lock.
  5. Write producer-consumer with semaphores. Use empty = N, full = 0, mutex = 1, as above.
  6. How do you avoid deadlock in dining philosophers? Impose a global order on the forks, or limit the number of diners to N − 1.
  7. 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).

Key Points

  • 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.

Start here

Computer Organization & Architecture

Hexagon ISA

Operating Systems

C++ for LLVM Development

LLVM IR

SelectionDAG

Backend Assignments

Target Bring-up

Calling Conventions

Frame Lowering

MC Layer

Register Allocation

Scheduling

Clone this wiki locally