Skip to content
Chethan Yadav_
Operating Systems

OS/Lesson 5 of 9/6 min read

Process Synchronization

Race conditions, the critical section problem, Peterson's solution, mutexes, semaphores, monitors, spinlocks, and the classic synchronization problems.


On this page

Race Condition

A race condition happens when the result of concurrent code depends on the timing of thread execution.

count++ looks atomic but compiles to three steps:

load  r1, count
add   r1, 1
store r1, count

If two threads interleave these steps, one increment is lost:

T1: load (5)       T2: load (5)
T1: add  (6)       T2: add  (6)
T1: store 6        T2: store 6     -> count = 6, expected 7

Critical Section

The critical section is the part of code that accesses shared data. The critical section problem is designing a protocol so that threads can use it safely.

do {
    entry section
        critical section
    exit section
        remainder section
} while (true);

A correct solution must satisfy:

  1. Mutual exclusion: at most one process in the critical section.
  2. Progress: if none is inside, the choice of who enters next cannot be postponed forever, and only processes that want to enter take part in deciding.
  3. Bounded waiting: there is a limit on how many times others can enter before a waiting process gets its turn (no starvation).

Peterson's Solution

A classic software solution for two processes using two shared variables:

bool flag[2];  // flag[i] = process i wants to enter
int turn;      // whose turn it is
 
// Process i (j = 1 - i)
flag[i] = true;
turn = j;                       // politely give way
while (flag[j] && turn == j) ;  // busy wait
/* critical section */
flag[i] = false;

It satisfies all three requirements. On modern CPUs it may fail without memory barriers because the compiler and CPU can reorder instructions, so real systems use hardware support.

Atomic Operation

Hardware provides atomic operations that execute as one indivisible step:

  • Test-and-Set: set a flag to true and return its old value.
  • Compare-and-Swap (CAS): if (*addr == expected) *addr = new; atomically, returns success. Basis of lock-free data structures.
while (test_and_set(&lock)) ;  // spin until we got it
/* critical section */
lock = false;

Mutex

A mutex (mutual exclusion lock) has two operations: acquire() (lock) and release() (unlock). Only the thread that locked it should unlock it (ownership).

pthread_mutex_lock(&m);
count++;
pthread_mutex_unlock(&m);

If the mutex is held, the caller blocks (sleeps) until it is released.

Spinlock

A spinlock is a lock where the waiting thread loops (busy waits) instead of sleeping.

  • Good when the lock is held for a very short time on a multicore machine: no context switch cost.
  • Bad on a single core or for long critical sections: wastes CPU.
  • Used heavily inside OS kernels.

Semaphore

A semaphore is an integer variable accessed only via two atomic operations (Dijkstra):

wait(S)   / P(S) / down:  while (S <= 0) wait; S--;
signal(S) / V(S) / up:    S++;

Real implementations block the process in a queue instead of busy waiting.

Binary Semaphore

Value 0 or 1. Acts like a lock, but has no ownership: any thread can signal it.

Counting Semaphore

Value can range over any non-negative integer. Used to control access to a pool of N identical resources (database connections, parking spots). Initialize to N.

Mutex vs Semaphore

MutexSemaphore
Locking mechanismSignaling mechanism
Has owner; only owner unlocksNo owner; any thread can signal
Values: locked / unlockedInteger value
Protects a critical sectionCoordinates or counts resources

Semaphore misuse (swapping wait and signal, forgetting one) leads to deadlock or broken mutual exclusion.

Monitor

A monitor is a high-level language construct: an object whose methods run with mutual exclusion automatically. Only one thread can be active inside it at a time. Java synchronized methods and C# lock are monitor-style.

Condition Variable

Inside a monitor, a condition variable lets a thread wait until some state becomes true.

  • wait(c): release the monitor lock and sleep on c.
  • signal(c) / notify: wake one waiting thread.
  • broadcast / notifyAll: wake all.

Always re-check the condition in a while loop after waking (spurious wakeups, other threads may have changed state).

Producer-Consumer Problem

Also called the bounded buffer problem. Producers add items to a buffer of size N, consumers remove them. Producers must wait if full, consumers if empty.

semaphore mutex = 1;   // protects the buffer
semaphore empty = N;   // free slots
semaphore full  = 0;   // filled slots
 
producer:                     consumer:
  wait(empty);                  wait(full);
  wait(mutex);                  wait(mutex);
  add item;                     remove item;
  signal(mutex);                signal(mutex);
  signal(full);                 signal(empty);

Order matters: calling wait(mutex) before wait(empty) can deadlock when the buffer is full.

Readers-Writers Problem

Many readers may read shared data together, but a writer needs exclusive access.

semaphore rw_mutex = 1;  // writers / first reader
semaphore mutex = 1;     // protects read_count
int read_count = 0;
 
writer:                 reader:
  wait(rw_mutex);         wait(mutex);
  write;                  read_count++;
  signal(rw_mutex);       if (read_count == 1) wait(rw_mutex);
                          signal(mutex);
                          read;
                          wait(mutex);
                          read_count--;
                          if (read_count == 0) signal(rw_mutex);
                          signal(mutex);

This "readers preference" version can starve writers. Writer-preference variants exist. Databases solve the same problem with shared and exclusive locks (see concurrency control).

Dining Philosophers Problem

Five philosophers sit around a table with five forks; each needs both neighboring forks to eat. If all pick up their left fork at once, everyone waits forever: a deadlock.

Solutions:

  • Allow at most 4 philosophers to sit at once.
  • Pick up both forks only if both are available (inside a critical section).
  • Asymmetry: odd philosophers pick left first, even pick right first. This breaks circular wait.

Priority inversion

A low-priority task holds a lock needed by a high-priority task, while a medium-priority task preempts the low one. The high-priority task is effectively blocked by the medium one. Fix: priority inheritance (the lock holder temporarily inherits the waiting task's priority). Famous on the Mars Pathfinder rover.

Quick revision

  • Critical section solution needs mutual exclusion, progress, bounded waiting.
  • Mutex = lock with owner; semaphore = counter for signaling.
  • Spinlocks only for very short critical sections on multicore.
  • Producer-consumer: mutex, empty = N, full = 0.