Chapter 6: Synchronization
Introduction
Learning Outcomes
Explain race conditions, the critical section, and the three requirements a solution must meet: mutual exclusion, progress, bounded waiting.
Evaluate the lock variable, strict alternation, and Peterson's solution; explain how reordering on modern CPUs breaks them and how memory barriers help.
Build locks and counters with test_and_set, compare_and_swap, XCHG, and atomic variables.
Compare spinlocks, mutexes, semaphores, monitors, and condition variables; apply the Mesa-style while rule.
Solve the bounded-buffer, readers–writers, and dining-philosophers problems; recognize the risks of starvation and deadlock.
Use the POSIX and Java APIs; analyze priority inversion (Mars Pathfinder) and the basics of lock-free data structures.
Introduction
Why Synchronization?
- Synchronization: coordinating how concurrent processes or threads access shared data so that it stays consistent.
- A process can be interrupted at any point in its instruction stream, leaving an update half done.
- On a multicore system no interrupt is needed: two cores can write the same memory truly simultaneously.
- Symptoms:
- inconsistent data, lost updates, a corrupted linked list;
- a non-reentrant function's shared buffer getting overwritten;
- threads waiting on each other forever (deadlock);
- a thread that never gets its turn (starvation).
Introduction
Race Condition: fork() and pid
The kernel keeps the next free pid in next_available_pid: 2615. P0 and P1 call fork() at the same time.
P0's kernel code reads the value (2615) but is interrupted before it can increment and store it.
P1 also reads 2615, gives it to its child, and writes 2616.
P0 resumes and gives its child 2615 as well. The outcome depends on the order of execution: a race condition.
The same race arises in user programs when count++ interleaves at the register level.
Introduction
Race Condition: Printer Spooler Directory
Files to print go into slots in order. out is the next file to print, in the first free slot.
A reads in (7) into its local next_free; right then its time slice expires.
B also reads in: 7 again!
B writes its file name into slot 7 and sets in = 8.
A resumes: since next_free = 7, it writes slot 7, overwriting B's entry; in = 8.
The directory looks consistent, but B's output is gone. The result depends on who runs when: a race condition.
Race condition: two or more processes access shared data and the final result depends on the order of execution.
Introduction
Non-reproducible Execution
/* Process 1 */ /* Process 2 */
repeat repeat
n = n + 1; print(n);
n = 0;Possible orders with n = 5:
n=n+1; print; n=0→ prints 6print; n=0; n=n+1→ prints 5, n=1print; n=n+1; n=0→ prints 5, increment lost
Even one line of C (count++) is three machine instructions:
Initially count = 5. For count++ the producer first loads the value into a register.
The producer increments its register to 6, then is interrupted before storing it.
The consumer runs count--: memory still holds 5.
The consumer decrements its register: 4.
The producer stores: count = 6.
The consumer overwrites it: count = 4. The right answer was 5; another order could give 6.
Critical Section
The Critical-Section Problem
- n processes
{P0, P1, …, Pn-1}; each has a critical section in which it accesses shared data: writing a global, updating a table, writing a file… - Rule: while one process is in its critical section, no other process may be in its critical section.
- Each process requests entry in its entry section and announces its exit in its exit section.
- Race condition: the result depends on execution order. Mutual exclusion: only one access to shared data at a time.
while (true) { /* entry section */ /* critical section */ /* exit section */ /* remainder section */ }
Critical Section
Three Requirements for a Solution
| Tanenbaum's four conditions | Equivalent |
|---|---|
| No two processes may be in their critical sections at once. | Mutual exclusion |
| No assumptions about CPU speed or count. | Nonzero speed; relative speeds unknown |
| No process outside its critical section may block others. | Progress |
| No process should wait forever. | Bounded waiting |
Silberschatz 10e §6.2; Tanenbaum MOS §2.3.2. Exclusion is a safety property; the other two are liveness properties.
Critical Section
Critical-Section Timeline
T1: A enters its critical section.
T2: B tries to enter; the section is taken, so B blocks (or busy-waits).
T3: A leaves; the waiting B enters at once. At no moment are two processes inside.
T4: B leaves. A correct solution must guarantee this under any schedule.
Adapted from Tanenbaum MOS Figure 2-22.
Software Approaches
Disabling Interrupts
- A process disables interrupts before entering its critical section and re-enables them on exit: with no timer interrupt, no context switch can occur.
- Problems:
- A process that forgets to re-enable interrupts (or loops forever) hangs the system.
- I/O and timer interrupts wait meanwhile; a long critical section makes the system unresponsive.
- Useless on multicore: the other cores keep running.
cli/stiare privileged instructions; user programs cannot execute them.
- Inside the kernel, brief local use is common: Linux
local_irq_save(), andspin_lock_irqsave()for data shared with an interrupt handler.
Software Approaches · Step through the code
Lock Variable
int lock = 0; /* shared */ void enter(void) { while (lock != 0) ; /* busy wait */ lock = 1; } void leave(void) { lock = 0; } /* each process: enter(); critical(); leave(); */
Shared lock is 0: the section is free.
P0 reads lock: 0. It exits the loop…
…but is interrupted before writing lock = 1. P1 also reads 0.
P1 sets the lock to 1 and enters its critical section.
P0 resumes; it already tested the lock, so it also writes 1 and enters.
Mutual exclusion is broken: test and set are separate steps. The fix is a single atomic instruction for both (TSL).
The lock itself is a shared variable, and protecting it would need yet another lock. A software lock alone is not enough.
Software Approaches
Strict Alternation
/* P0 */ while (true) { while (turn != 0) ; /* wait */ critical_section(); turn = 1; noncritical(); }
/* P1 */ while (true) { while (turn != 1) ; /* wait */ critical_section(); turn = 0; noncritical(); }
turn = 0: P0 enters, P1 busy-waits (CS critical section, NCS noncritical section).
On exit P0 sets turn = 1; P1 enters. Mutual exclusion holds.
P1 leaves (turn = 0) and starts a long noncritical stretch. P0 enters and leaves once more: turn = 1.
P0 wants in again, but it is P1's turn. The section is free, yet P1, outside its critical section, blocks P0: progress is violated.
Software Approaches
Peterson's Solution
/* shared */ bool flag[2] = { false, false }; int turn; /* P_i (j = 1 - i) */ while (true) { flag[i] = true; /* I want in */ turn = j; /* after you */ while (flag[j] && turn == j) ; /* busy wait */ /* critical section */ flag[i] = false; /* remainder section */ }
G. L. Peterson, 1981. Works for two processes only; for n processes there is the bakery algorithm.
flag[0] = flag[1] = true; but turn cannot be 0 and 1 at once. Whoever wrote turn last waits.flag[j] = false: Pi enters without waiting.turn = i; Pi waits for at most one entry.Software Approaches · Step through the code
Peterson's Solution: Code Trace
bool flag[2] = { false, false }; int turn; void enter(int i) { int j = 1 - i; flag[i] = true; /* I want in */ turn = j; /* after you */ while (flag[j] && turn == j) ; /* busy wait */ } void leave(int i) { flag[i] = false; }
Both processes are in their remainder sections; both flags are false. Memory is assumed sequentially consistent (all operations fit one global order that preserves each thread's program order).
P0 wants in: flag[0] = true.
P1 asks at almost the same moment: flag[1] = true.
P0 is polite: turn = 1 ("after you").
P1 writes turn = 0 too. P1 wrote turn last, so P1 is the one that waits.
P0: flag[1] && turn == 1 is false since turn is 0; it exits the loop and enters its critical section.
P1: flag[0] && turn == 0 is true → busy-waits. Mutual exclusion holds.
P0 leaves: flag[0] = false.
P1's condition is now false (flag[0] is false) → P1 enters. Progress holds.
P0 asks again: flag[0] = true, turn = 1.
P0: flag[1] && turn == 1 is true → waits. Now P0 wrote turn last.
P1 leaves: flag[1] = false.
P0's condition turns false and it enters. Had P1 asked again, it would set turn = 0 and wait: P0 waits for at most one entry.
Memory Model · Step through the code
Why Peterson Fails on a Modern CPU
/* P_i (i = 0 or 1, j = 1 - i) */ flag[i] = true; turn = j; while (flag[j] && turn == j) ; /* critical section */ flag[i] = false;
Initially both flags in memory are false. Each core's stores go first to its own store buffer.
P0 performs both stores; they sit in the buffer, not yet visible in memory.
P1 does the same. Even x86 (TSO) may let a store complete after a later load.
P0 reads flag[1] from memory: false → leaves the loop.
P1 also reads flag[0] as false and enters: both are in the critical section!
The buffers drain later, but the damage is done. Fix: a full memory barrier between the store and the load, or sequentially consistent atomics.
The compiler may also hoist that load. C11 _Atomic with the default memory_order_seq_cst, or Java volatile fields, restore the order.
Memory Model
Memory Models and Reordering
/* x = y = 0 */ /* T1 */ /* T2 */ x = 1; y = 1; r1 = y; r2 = x; /* r1 == 0 && r2 == 0 ? */
Intuitively at least one should see 1. Yet on x86, ARM, and RISC-V, r1 = r2 = 0 can be observed (the store-buffer litmus test).
| Model | Reordering allowed |
|---|---|
| Sequential consistency (SC) | None; all operations fit one global order that preserves each thread's program order (Lamport 1979). |
| x86-64 (TSO) | Only store → later load; stores stay ordered among themselves. |
| ARMv8, RISC-V (weak) | Loads and stores may pass each other when there is no dependency. |
| Compiler | May move, cache, or remove any access if the single-threaded result is unchanged. |
volatile gives threads neither atomicity nor ordering. The right tools: C11 <stdatomic.h>, Java volatile/java.util.concurrent, locks.Memory Model
Memory Barriers
No barrier: on a weak model T2's stores may become visible in another order; T1 sees flag true while x is still 0.
Or T1 itself may read x before flag (load–load reordering).
Memory barrier (fence): no later load or store starts until all earlier ones complete. T2: x first; T1: flag first.
In real code: x86 mfence, ARM dmb, Linux smp_mb(), C11 atomic_thread_fence; release/acquire atomics usually suffice.
The example from Silberschatz 10e §6.4.1. Lock and semaphore implementations already contain these barriers: code protected by a lock needs no extra fence.
Memory Model
Peterson in Java: A Correct Implementation
public class Peterson { static volatile boolean flag0, flag1; static volatile int turn; static int counter = 0; static void lock(int i) { if (i == 0) { flag0 = true; turn = 1; while (flag1 && turn == 1) Thread.onSpinWait(); } else { flag1 = true; turn = 0; while (flag0 && turn == 0) Thread.onSpinWait(); } } static void unlock(int i) { if (i == 0) flag0 = false; else flag1 = false; } /* main: two threads, i = 0 and i = 1, each 100_000 times: lock(i); counter++; unlock(i); join both, print counter */ }
- Three common mistakes:
volatile boolean[] flagmakes only the array reference volatile, not its elements.getId() % Ncan give two threads the samei.- A
printinside the critical section distorts the measurement.
- In Java,
volatilereads and writes are sequentially consistent; with separate volatile fields Peterson works correctly. Thread.onSpinWait()(Java 9+) hints to the CPU that it is spinning (x86pause).
counter = 200000 counter = 200000 counter = 200000
Memory Model
Synchronization Barrier
A parallel computation split into phases (e.g., a grid simulation): each process computes one slice.
A process that finishes calls barrier_wait() and blocks; everyone waits for the slowest (C).
When the Nth process arrives the barrier opens; all move to the next phase together.
var b = new CyclicBarrier(3, () -> System.out.println( "phase " + phase[0]++ + " done")); /* 3 threads, each: for (f = 0; f < 2; f++) { compute(f); b.await(); } */
phase 0 done phase 1 done
pthread_barrier_wait, CyclicBarrier); a memory barrier enforces the order of one core's memory accesses.Hardware Support
Atomic Hardware Instructions
/* runs as ONE atomic instruction */ bool test_and_set(bool *target) { bool old = *target; *target = true; return old; } /* usage: a simple spinlock */ bool lock = false; while (test_and_set(&lock)) ; /* busy wait */ /* critical section */ lock = false;
- The trouble with software solutions: read and write are separate steps. Hardware provides instructions that test and modify a memory word atomically.
- Atomicity holds on multicore too: the cache-coherence protocol gives one core exclusive ownership of the line for the whole instruction (older systems locked the memory bus).
| Architecture | Atomic read-modify-write |
|---|---|
| x86-64 | XCHG, LOCK CMPXCHG, LOCK XADD, LOCK BTS |
| ARMv8 | LDXR/STXR (LL/SC); v8.1 LSE: CAS, LDADD, SWP |
| RISC-V “A” | LR/SC, AMOSWAP, AMOADD |
| Tanenbaum's hypothetical CPU | TSL REGISTER,LOCK |
Hardware Support · Step through the code
Critical Section with TSL
enter_region: TSL REGISTER,LOCK | R = LOCK; LOCK = 1 CMP REGISTER,#0 | was LOCK 0? JNE enter_region | no: try again RET | entered critical section leave_region: MOVE LOCK,#0 | LOCK = 0 RET
Lock is free: LOCK = 0.
CPU 0 runs TSL: old value (0) into the register, 1 into LOCK, in one indivisible step.
CPU 1 also runs TSL: its register gets 1; LOCK is already 1.
CPU 0 saw zero: it is in its critical section. CPU 1 saw nonzero: it busy-waits.
On exit CPU 0 sets LOCK to 0 with an ordinary store.
CPU 1's next TSL reads 0 and acquires the lock. The two CPUs are never inside together.
Tanenbaum MOS Figure 2-25. TSL works on multicore too: unlike disabling interrupts, it also blocks other CPUs from that word.
Hardware Support
The XCHG Instruction
enter_region: MOVE REGISTER,#1 | put 1 in register XCHG REGISTER,LOCK | swap register and LOCK CMP REGISTER,#0 | was LOCK 0? JNE enter_region | no: loop RET | entered critical section leave_region: MOVE LOCK,#0 | LOCK = 0 RET
- Swaps the contents of two operands in one step; the effect is the same as TSL.
- The instruction Intel x86 uses for locking:
XCHGwith a memory operand is implicitlyLOCK-prefixed, hence atomic. - C11 equivalent:
atomic_exchange(&lock, 1).
Hardware Support · Step through the code
A Lock with compare_and_swap
int compare_and_swap(int *v, int exp, int nv) { int old = *v; /* these three lines */ if (old == exp) /* are ONE atomic op */ *v = nv; return old; } int lock = 0; void enter(void) { while (compare_and_swap(&lock, 0, 1) != 0) ; /* busy wait */ } void leave(void) { lock = 0; }
The lock is free.
T0's CAS finds lock at 0, writes 1, and returns 0: it leaves the loop and is in its critical section.
T1's CAS finds 1: not the expected value, so it writes nothing and returns 1.
T1 busy-waits; each attempt returns without changing the memory word.
T0 sets the lock to 0 on exit (in real code, a store with release ordering).
T1's next CAS succeeds. Note: this lock does not guarantee bounded waiting; an unlucky thread may lose every time.
Silberschatz 10e §6.4.2. x86: LOCK CMPXCHG; C11: atomic_compare_exchange_strong; Java: AtomicInteger.compareAndSet.
Hardware Support · Step through the code
Atomic Increment with CAS
void increment(int *v) { int temp; do { temp = *v; /* read */ } while (temp != compare_and_swap(v, temp, temp + 1)); } /* write if unchanged */ /* C11: if the counter is atomic_int, one line: atomic_fetch_add(v, 1); */
Two threads want to increment the same counter; initially v = 5.
T1 reads the value: temp = 5. It may be interrupted here; there is no lock.
T2 also reads 5. With a plain v++ one increment would be lost.
T2's CAS finds v still 5, writes 6, and returns 5: equal to temp → done.
T1's CAS finds v at 6, not the expected 5; it writes nothing and returns 6 → retry.
T1 reads the current value.
This time it succeeds: v = 7. No increment was lost and no one held a lock (a lock-free update).
This "read → compute → CAS → retry on failure" loop is the basic pattern of lock-free data structures.
Hardware Support
Bounded Waiting with CAS
while (true) { waiting[i] = true; key = 1; while (waiting[i] && key == 1) key = compare_and_swap(&lock, 0, 1); waiting[i] = false; /* critical section */ j = (i + 1) % n; while ((j != i) && !waiting[j]) j = (j + 1) % n; if (j == i) lock = 0; /* no one waiting */ else waiting[j] = false; /* hand over turn */ /* remainder section */ }
P1 is in its critical section; P3 and P4 wait with their waiting flags set.
On exit P1 scans j = 2, 3, … in order; the first waiter is P3.
It does not release the lock; it sets waiting[3] = false: P3's loop ends and it enters. The cyclic scan ensures bounded waiting.
Hardware Support · Step through the code
Bounded Waiting with CAS: Code Trace
/* P_i; n = 4 processes */ waiting[i] = true; key = 1; while (waiting[i] && key == 1) key = compare_and_swap(&lock, 0, 1); waiting[i] = false; /* critical section */ j = (i + 1) % n; while ((j != i) && !waiting[j]) j = (j + 1) % n; if (j == i) lock = 0; /* no one waiting */ else waiting[j] = false; /* hand over turn */
The lock is free (lock = 0) and no one is waiting. The four processes will be scanned in ring order.
P2 arrives: waiting[2] = true; CAS finds lock at 0, writes 1, returns 0 → key = 0.
The loop ends; P2 sets waiting[2] = false and enters its critical section.
P0 arrives: CAS returns 1 (lock held) → key = 1, it spins.
P3 arrives and spins too. Waiting: P0 and P3.
On exit P2 starts scanning at the next index, j = 3; waiting[3] is true → the scan stops.
P2 does not release the lock; it sets waiting[3] = false: P3's loop ends and P3 enters. lock is still 1.
P3 leaves: j = (3 + 1) % 4 = 0; waiting[0] is true → the scan stops.
The turn passes to P0. P0 arrived before P3, but ring order chose P3 first; still, P0 waits for at most n − 1 = 3 entries.
P0 leaves: none of j = 1, 2, 3 is waiting; j comes back to 0 = i.
No one waiting → lock = 0. Only now is the lock truly free.
Locks
Atomic Variables
C11 <stdatomic.h>
#include <stdatomic.h> atomic_int counter = 0; /* _Atomic int */ void *work(void *arg) { for (int n = 0; n < 100000; n++) atomic_fetch_add(&counter, 1); return NULL; } /* 2 threads + join → 200000 */
On an _Atomic type, counter++ is atomic too (default seq_cst). It compiles to lock xadd on x86 and ldadd on ARMv8.1.
Java AtomicInteger
static AtomicInteger atom = new AtomicInteger(); /* two threads, each 100_000 times: */ atom.incrementAndGet(); var v = new AtomicInteger(5); v.compareAndSet(5, 6); /* true, v = 6 */ v.compareAndSet(5, 7); /* false, v = 6 */
AtomicInteger = 200000 synchronized = 200000 true 6 false 6
Locks
Spinlocks and Mutexes
Spinlock: the waiter keeps the CPU; when the lock frees it enters with no context switch.
Sleeping mutex: the waiter blocks and the CPU switches to T3; the cost is two context switches.
| Spinlock | Mutex (sleeping) | |
|---|---|---|
| Best for | Multicore, CS shorter than two context switches | Long critical sections, or ones that may block |
| Single core | Pointless: the holder can't run, the waiter burns its slice | Right choice |
| Example | Linux spin_lock, pthread_spin_lock | pthread_mutex_t, Java synchronized |
Most mutex implementations spin briefly, then sleep.
Locks
Implementing a Mutex: yield and futex
mutex_lock: TSL REGISTER,MUTEX | get old, set 1 CMP REGISTER,#0 | was it free? JZE ok | yes: acquired CALL thread_yield | no: give up CPU JMP mutex_lock | then try again ok: RET mutex_unlock: MOVE MUTEX,#0 RET
- Tanenbaum Figure 2-29: unlike
enter_region, it callsthread_yieldinstead of looping, which avoids busy waiting with user-level threads. - Linux futex (fast userspace mutex): no system call when there is no contention; glibc
pthread_mutex, Java locks, and Go are built on it.
No contention: T1 flips the word 0 → 1 with one CAS; the kernel is never entered.
T2 finds the lock taken, sets the value to 2 ("there are waiters"), and sleeps in futex_wait.
On release T1 sees the old value 2, so it sets the word to 0 and calls futex_wake. T2 wakes and conservatively sets the word to 2 again; the old value was 0, so it holds the lock.
Locks · Step through the code
A Scalable Counter: Per-CPU Counting
typedef struct { int global; pthread_mutex_t glock; int local[NCPU]; pthread_mutex_t llock[NCPU]; int S; /* transfer threshold */ } acount_t; void add(acount_t *c, int cpu) { pthread_mutex_lock(&c->llock[cpu]); c->local[cpu]++; if (c->local[cpu] >= c->S) { /* transfer */ pthread_mutex_lock(&c->glock); c->global += c->local[cpu]; pthread_mutex_unlock(&c->glock); c->local[cpu] = 0; } pthread_mutex_unlock(&c->llock[cpu]); } int get(acount_t *c) { /* approximate */ pthread_mutex_lock(&c->glock); int v = c->global; pthread_mutex_unlock(&c->glock); return v; }
Four cores, threshold S = 4. Each core has its own counter and lock; the global counter G is updated only now and then.
Cores 1 and 3 call add at the same time. Their locks differ, so they don't wait for each other.
Three more cores increment. The global lock still hasn't been touched.
The actual value is 8, but G is still 0: the global counter lags behind.
L1 hits the threshold: core 1 takes the global lock, adds 4 to G, and resets its local counter.
L3 also hits the threshold and transfers: G = 8.
get() returns 8; the actual value is 12. In the worst case the gap can reach NCPU × (S − 1) = 4 × 3 = 12.
With a single-lock counter every increment contends for one lock; adding cores makes it slower. Large S: rare trips to the global lock and good scaling, but get() lags further. Linux's percpu_counter uses the same idea.
Locks
Locking Strategies for Concurrent Data Structures
| Structure | Locking | Result |
|---|---|---|
| Linked list | Single mutex | Simple. Call malloc outside the lock; don't forget unlock on every return path. |
| Hand-over-hand locking | A lock per node: grab the next, then release the previous | Traversals proceed in parallel, but the per-node locking cost often eats the gain. |
| Queue | Separate head and tail locks, a dummy node | Enqueue and dequeue can run concurrently. |
| Hash table | A locked list per bucket | Operations on different buckets don't wait for each other: scales very well. |
Initially there is a single dummy node; head and tail both point to it.
enqueue(A), enqueue(B): only tailLock is taken; the tail end advances.
dequeue(): only headLock. The old dummy is freed, A's value is returned, and A becomes the new dummy.
Semaphores
Semaphore
- Dijkstra (1965): an integer accessed only through two atomic operations.
wait(S)= P =down: if the value is 0 the process blocks (sleeps); otherwise it is decremented and the process continues.signal(S)= V =up: increment the value; if anyone is waiting, wake one.
- Think of the value as the number of available resources.
- In the Silberschatz implementation the value can go negative:
−kmeans k processes are waiting. wait/signalare themselves short critical sections: protected by disabling interrupts on one core, or by a spinlock on multicore. Busy waiting does not vanish, but shrinks to a few instructions.
typedef struct { int value; struct process *list; } semaphore;
down on a zero value sleeps in Dijkstra's semaphore and in real systems; the busy-waiting version is only the first conceptual definition.Semaphores · Step through the code
Semaphore Waiting Queue
void wait(semaphore *S) { /* P / down */ S->value--; if (S->value < 0) { add(S->list, this_proc); sleep(); /* block */ } } void signal(semaphore *S) { /* V / up */ S->value++; if (S->value <= 0) { P = remove(S->list); /* FIFO */ wakeup(P); } }
One resource: S starts at 1 (a binary semaphore, like a mutex).
T1 wait: the value becomes 0, not negative → T1 continues.
T2 wait: the value is −1 → T2 joins the queue and sleeps.
T3 sleeps too. −2: two processes are waiting.
T1 signal: value −1, still ≤ 0 → T2 at the head of the queue is woken and enters.
T2 signal: value 0 → T3 is woken.
T3 signal: value 1, no one waiting. The queue is FIFO, so waiting is bounded.
Silberschatz 10e §6.6.2. The definition does not fix the queue order; without FIFO, starvation is possible.
Semaphores
Semaphore Usage Patterns
wait … CS … signal.Common mistakes
signal(m) … CS … wait(m) | Reversed: several processes in the CS |
wait(m) … CS … wait(m) | Waits on itself: blocked forever |
A forgotten wait or signal | Broken exclusion, or deadlock |
| Two semaphores taken in different orders | Deadlock |
Semaphores are powerful but unstructured: correctness depends on every wait/signal pair. That is why monitors were developed.
Semaphores · Step through the code
Barrier with Semaphores: Code Trace
#define N 3 semaphore mutex = 1, turnstile = 0; int count = 0; void barrier(void) { down(&mutex); count = count + 1; if (count == N) up(&turnstile); /* last */ up(&mutex); down(&turnstile); /* pass through */ up(&turnstile); /* let next one in */ }
Three threads compute a phase. The turnstile is closed (0); count counts arrivals.
A is done: it takes the mutex, count = 1.
1 ≠ 3: A releases the mutex and sleeps in down(&turnstile).
B arrives too: count = 2, sleeps at the turnstile.
The slowest, C, arrives: count = 3 = N.
C, the last to arrive, calls up(&turnstile): since someone is waiting the value stays put and A is woken.
C releases the mutex and sleeps at the turnstile: it can pass only if someone lets it through.
A is through; with up(&turnstile) it wakes B behind it.
B passes and wakes C: the turnstile works like a one-person revolving door.
C passes; with no one left waiting, turnstile = 1. All have moved to the next phase; to reuse the barrier the turnstile must be closed again.
Tanenbaum semaphore: if someone is sleeping, up wakes one without incrementing. This barrier is single-use; a reusable one needs two turnstiles.
Classic Problems
The Producer–Consumer (Bounded-Buffer) Problem
- Two processes share a fixed-size buffer of N slots: the producer writes, the consumer reads.
- Bounded buffer: the producer waits when it is full, the consumer when it is empty. Unbounded buffer: only the consumer waits.
The buffer is empty (count = 0): the consumer cannot read and must wait.
The producer adds A, B, C: each insert does in = (in + 1) % N.
The consumer takes A: out = 1, count = 2.
The producer adds D…I; in wraps around (1). count = N = 8: the buffer is full and the producer must wait.
The consumer takes B and C: out = 3, count = 6; the producer can write again.
Classic Problems · Step through the code
A Fatal Race: The Lost Wakeup
#define N 100 int count = 0; void producer(void) { while (TRUE) { item = produce_item(); if (count == N) sleep(); insert_item(item); count = count + 1; if (count == 1) wakeup(consumer); } } void consumer(void) { while (TRUE) { if (count == 0) sleep(); item = remove_item(); count = count - 1; if (count == N - 1) wakeup(producer); consume_item(item); } }
The buffer is empty. The consumer reads count: 0. Just before calling sleep() it is interrupted.
The producer produces an item and puts it in the buffer.
count becomes 1.
count == 1, so the producer assumes the consumer is asleep and sends wakeup(consumer). But the consumer isn't asleep yet: the signal is lost.
The consumer resumes: acting on its stale decision, it calls sleep() and goes to sleep.
The producer fills the buffer; the consumer is asleep, so no one reads.
count == N → the producer sleeps too. Both sleep forever. The problem: testing count and calling sleep are not one indivisible (atomic) step.
Tanenbaum MOS Figure 2-27. sleep() blocks the caller (no busy waiting); wakeup(p) makes a sleeping p ready. A semaphore stores wakeups as a count, so no signal is lost.
Classic Problems
Bounded Buffer with Semaphores
#define N 100 semaphore mutex = 1; /* buffer access */ semaphore empty = N; /* empty slots */ semaphore full = 0; /* full slots */ void producer(void) { while (true) { item = produce_item(); down(&empty); /* wait for a slot */ down(&mutex); /* enter CS */ insert_item(item); up(&mutex); /* leave CS */ up(&full); /* one more full */ } }
void consumer(void) { while (true) { down(&full); /* wait for an item */ down(&mutex); item = remove_item(); up(&mutex); up(&empty); /* one more empty */ consume_item(item); } }
Classic Problems · Step through the code
Bounded Buffer, Step by Step
semaphore mutex = 1, empty = 2, full = 0; void producer(void) { while (true) { item = produce(); wait(&empty); wait(&mutex); insert(item); signal(&mutex); signal(&full); } } void consumer(void) { while (true) { wait(&full); wait(&mutex); item = remove(); signal(&mutex); signal(&empty); consume(item); } }
The buffer is empty: 2 empty slots, 0 full.
The consumer runs first: full = 0 → it sleeps. No busy waiting.
Producer: empty 2→1, mutex 1→0, inserts A.
signal(full) wakes the waiting consumer; the woken process uses up that "1", so full stays 0.
The consumer hasn't run yet; the producer inserts B too: empty = 0, full = 1.
No empty slot for C: the producer sleeps. The buffer does not overflow.
The consumer takes A; signal(empty) wakes the sleeping producer.
The producer puts C in the freed slot. At all times: empty + full + operations in progress = N.
Classic Problems
If the downs Are Swapped
void producer(void) { while (true) { item = produce_item(); down(&mutex); /* ← first */ down(&empty); /* ← then */ insert_item(item); up(&mutex); up(&full); } }
The producer's two down calls are swapped. The buffer is completely full: empty = 0.
The producer takes mutex, then sleeps in down(&empty), still holding the mutex.
The consumer passes down(&full) but sleeps in down(&mutex). It was the one that would call up(&empty).
Each waits for the other: deadlock. Rule: wait on the counting semaphore first, then the mutex; never sleep while holding the mutex.
Classic Problems
The Readers–Writers Problem
semaphore mutex = 1; /* guards rc */ semaphore db = 1; /* guards database */ int rc = 0; /* reader count */ void writer(void) { while (true) { think_up_data(); down(&db); write_data_base(); up(&db); } } void reader(void) { while (true) { down(&mutex); if (++rc == 1) down(&db); /* first reader */ up(&mutex); read_data_base(); down(&mutex); if (--rc == 0) up(&db); /* last reader */ up(&mutex); use_data_read(); } }
Readers don't exclude each other; only the first reader takes db.
A writer arrives and waits in down(&db).
A new reader, R2, enters without touching db: rc = 2.
R3 arrives as R1 leaves: rc drops to 1 and climbs back to 2; it never hits 0.
As long as readers keep coming the writer waits indefinitely: this solution favors readers and is prone to writer starvation.
Classic Problems
Readers–Writers: Variants and APIs
| Variant | Behavior |
|---|---|
| First readers–writers (reader priority) | A writer enters only when there are no readers; writers may starve. |
| Second readers–writers (writer priority) | No new reader may enter while a writer waits; readers may starve. |
| Fair (turnstile) | Everyone passes through the same turnstile first; a waiting writer holds the turnstile. |
pthread_rwlock_t | The glibc default favors readers; writer preference is configurable. |
Java ReentrantRead | new ReentrantReadWrite gives fair (near-FIFO) ordering. |
| Linux seqlock, RCU | Read-mostly kernel structures in which readers take no lock at all. |
/* Downey: starvation-free */ /* writer */ wait(turnstile); wait(roomEmpty); write(); signal(turnstile); signal(roomEmpty); /* reader */ wait(turnstile); signal(turnstile); /* first reader takes roomEmpty, last reader releases it (via rc) */ read();
Classic Problems
Dining Philosophers: The Naive Solution
semaphore fork[5]; /* all 1 */ void philosopher(int i) { while (true) { think(); wait(&fork[i]); /* left */ wait(&fork[(i + 1) % 5]); /* right */ eat(); signal(&fork[(i + 1) % 5]); signal(&fork[i]); } }
- Dijkstra (1965): each philosopher thinks, and when hungry picks up the two neighboring forks and eats.
- A model for sharing limited resources among processes without deadlock or starvation.
Forks are free; everyone is thinking.
All get hungry at once and pick up their left fork…
…the fifth does too. Now everyone waits for the right fork.
No one lets go: deadlock. The solution is wrong even though every fork is guarded by a semaphore.
Classic Problems
Philosophers: Ways Out
A room semaphore initialized to 4: at least one philosopher gets both forks. Circular wait is broken.
Each philosopher picks up the lower-numbered fork first; F4 asks for fork 0 first. General rule: always acquire locks in one global order.
Tanenbaum: a state[] array and a semaphore per philosopher; start eating only if neither neighbor is eating.
Silberschatz: pickup(i)/putdown(i) and a condition variable self[i] per philosopher; the same test() logic.
Classic Problems · Step through the code
Tanenbaum's Solution, Step by Step
void take_forks(int i) { down(&mutex); state[i] = HUNGRY; test(i); up(&mutex); down(&s[i]); /* block if no forks */ } void put_forks(int i) { down(&mutex); state[i] = THINKING; test(LEFT); /* (i+4) % 5 */ test(RIGHT); /* (i+1) % 5 */ up(&mutex); } void test(int i) { if (state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] != EATING) { state[i] = EATING; up(&s[i]); } }
Initially everyone is THINKING (T). The s[i] semaphores are 0.
F1 gets hungry; test(1): neighbors F0 and F2 aren't eating → EATING, up(&s[1]); then down(&s[1]) passes at once.
F2 gets hungry; its left neighbor F1 is eating → the test fails and it sleeps in down(&s[2]).
F3 gets hungry; F2 is hungry but not eating, F4 is thinking → F3 eats. Two philosophers can eat at once.
F1 puts down its forks and tests its neighbors: test(2) fails because F3 on the right is still eating.
When F3 puts its forks down, test(2) succeeds: F2 becomes EATING and up(&s[2]) wakes it.
Tanenbaum MOS Figure 2-47. There is no deadlock, and at most ⌊5/2⌋ = 2 of the five eat at once; but if F1 and F3 keep taking turns, F2 could in theory starve.
Monitors
Monitor
- Hoare (1974) and Brinch Hansen (1975): a language-level abstract data type that bundles data, procedures, and initialization code.
- Processes may call a monitor's procedures but cannot access its internal data directly.
- Only one process may be active inside the monitor at a time; the compiler inserts the entry lock, so the programmer cannot forget it.
- If the monitor is busy, the caller waits in the entry queue. To wait for a condition, processes use condition variables.
- Getting the
downorder wrong with semaphores caused deadlock; monitors shrink this class of bugs.
monitor example integer i; condition c; procedure producer(); … end; procedure consumer(); … end; end monitor;
Monitors
Condition Variables
P is in the monitor but cannot continue because the buffer is empty. Q is in the entry queue.
P calls x.wait(): it releases the monitor and sleeps on x's queue, so Q can enter.
Q makes the condition true and calls x.signal(): one process on x's queue wakes. Who runs next is a semantic choice.
When no one waits on x, x.signal() has no effect and leaves no trace. A semaphore's signal, in contrast, increments the value and is remembered.
| Operation | Meaning |
|---|---|
x.wait() | Suspend the caller and release the monitor. |
x.signal() | Resume one process waiting on x (if any). |
broadcast / notifyAll | Wake every process waiting on x. |
count > 0) is always kept separately in shared data.Monitors
Hoare and Mesa Semantics
Signal-and-wait (Hoare): the awakened P runs immediately and Q waits. P can be sure the condition holds: an if suffices.
Signal-and-continue (Mesa, 1980): Q continues; P merely becomes ready. Someone else may falsify the condition before P runs: it must recheck.
| Semantics | Who runs next? | Used by |
|---|---|---|
| Signal-and-wait (Hoare) | The awakened process | Textbook monitors |
| Signal-and-exit (Brinch Hansen) | The awakened process; signal must be the procedure's last statement | Concurrent Pascal |
| Signal-and-continue (Mesa) | The signaler | Pthreads, Java, C#, Go sync.Cond, the Linux kernel |
Monitors
Why while, Not if?
/* WRONG (under Mesa) */ lock(&m); if (count == 0) cond_wait(&full, &m); x = take(); /* may be empty */ unlock(&m);
/* RIGHT */ lock(&m); while (count == 0) cond_wait(&full, &m); x = take(); /* count > 0 for sure */ unlock(&m);
The buffer is empty: consumer T1 waits on the condition variable.
The producer puts an item and calls signal. T1 wakes, but must first reacquire the lock.
Meanwhile a newcomer, T2, grabs the lock first (barging) and takes the item: count = 0.
T1 finally runs. With if it doesn't retest the condition and reads from an empty buffer: a bug.
With while, T1 retests the condition and waits again. POSIX also allows spurious wakeups: while is required in every case.
Monitors · Step by step
One Condition Variable Is Not Enough
/* WRONG: one condition c */ C: while (count == 0) wait(&c, &m); x = get(); signal(&c); P: while (count == 1) wait(&c, &m); put(x); signal(&c);
/* RIGHT: two conditions */ C: while (count == 0) wait(&full, &m); x = get(); signal(&empty); P: while (count == 1) wait(&empty, &m); put(x); signal(&full);
The buffer (size 1) is empty: both consumers sleep on the same condition variable c.
The producer puts an item and wakes T1 with signal(c).
The producer retries; the buffer is full, so it also sleeps on c. Now T2 and P wait on c.
T1 takes the item and calls signal(c). Which waiter wakes is unspecified: here, T2.
T2 finds the buffer empty and sleeps, as does T1 next round. No one can wake the producer: the program hangs.
Both versions hold lock m and use while. The bug: all threads wait on the same queue, yet a consumer should wake only the producer, and vice versa.
Monitors · Step by step
Whom to Wake? signal and broadcast
int avail = 0; /* free bytes */ void mem_alloc(int n) { lock(&m); while (avail < n) wait(&c, &m); avail -= n; /* ... allocate */ unlock(&m); } void mem_free(int n) { lock(&m); avail += n; broadcast(&c); /* signal won't do */ unlock(&m); }
Memory is exhausted: Ta wants 100 bytes, Tb wants 10; both sleep in their while loops.
Tc frees 50 bytes. signal wakes only one; if that is Ta, it sleeps again and Tb's chance is wasted.
broadcast wakes everyone, and each retests its condition. The cost is needless wakeups.
pthread_cond_broadcast (Java: notifyAll). If waiters can be split by condition, signal is cheaper. Either way, wait inside a while.Monitors
Producer–Consumer with a Monitor
monitor ProducerConsumer
condition full, empty;
integer count;
procedure insert(item: integer);
begin
if count = N then wait(full);
insert_item(item);
count := count + 1;
if count = 1 then signal(empty)
end;
function remove: integer;
begin
if count = 0 then wait(empty);
remove := remove_item;
count := count - 1;
if count = N - 1 then signal(full)
end;
count := 0;
end monitor;- Tanenbaum Figure 2-34 (Pidgin Pascal). The monitor already guarantees mutual exclusion on
count. - If the buffer is full, the producer blocks in
wait(full)and releases the monitor; once a consumer enters and takes an item,signal(full)wakes the producer. - It is
waitthat blocks the producer;signalonly wakes it. - An
ifsuffices here because Tanenbaum assumes Brinch Hansen semantics (signal is the last statement). In Pthreads/Java the same code must usewhile. - No lost wakeup: the test and the
waithappen inside the same monitor, without interruption.
Monitors · Step through the code
Producer–Consumer with a Monitor: Code Trace
monitor ProducerConsumer { N = 2 } condition full, empty; integer count; procedure insert(item: integer); begin if count = N then wait(full); insert_item(item); count := count + 1; if count = 1 then signal(empty) end; function remove: integer; begin if count = 0 then wait(empty); remove := remove_item; count := count - 1; if count = N - 1 then signal(full) end;
The buffer is empty (count = 0), N = 2. Producer P and consumer C enter the monitor in turn.
C calls remove: count = 0 → wait(empty). C sleeps and releases the monitor.
P calls insert(a): the buffer isn't full, so it inserts the item; count = 1.
count = 1 → signal(empty): C wakes. Since signal is the last statement, P leaves at once; there are never two processes in the monitor.
C resumes: takes a, count = 0. 0 ≠ N − 1, so no signal.
P calls insert(b): count = 1 → signal(empty), but no one is waiting: the signal is lost, harmlessly.
P calls insert(c): count = 2. The buffer is full.
P calls insert(d): count = N → wait(full). P sleeps and the monitor is free.
C calls remove: takes b, count = 1 = N − 1 → signal(full) wakes P.
P returns from wait and inserts d: count = 2. No data was lost and no process slept forever.
POSIX and Java
Pthreads: Mutexes and Condition Variables
| Mutex call | Description | Condition call | Description |
|---|---|---|---|
pthread_mutex_init | Creates a mutex | pthread_cond_init | Creates a condition variable |
pthread_mutex_destroy | Destroys it | pthread_cond_destroy | Destroys it |
pthread_mutex_lock | Acquires the lock or blocks | pthread_cond_wait | Atomically unlocks and sleeps; relocks on return |
pthread_mutex_trylock | Acquires or returns EBUSY at once | pthread_cond_signal | Wakes at least one waiter |
pthread_mutex_unlock | Releases it (owner only) | pthread_cond_broadcast | Wakes all waiters |
cond_wait only while holding the mutex, inside a while loop.NORMAL, ERRORCHECK, RECURSIVE; PTHREAD_PRIO_INHERIT for priority inheritance.pthread_rwlock_*, pthread_spin_*, pthread_barrier_*, C11 mtx_t/cnd_t.Static init: PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER. cond_signal affects only current waiters; with none, the signal is lost.
POSIX and Java · Step through the code
Pthreads Producer–Consumer, Step by Step
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condc = PTHREAD_COND_INITIALIZER,
condp = PTHREAD_COND_INITIALIZER;
int buffer = 0; /* 0 = empty */
void *producer(void *p) {
for (int i = 1; i <= MAX; i++) { /* MAX = 2 */
pthread_mutex_lock(&m);
while (buffer != 0) pthread_cond_wait(&condp, &m);
buffer = i;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&m);
} return NULL;
}
void *consumer(void *p) {
for (int i = 1; i <= MAX; i++) {
pthread_mutex_lock(&m);
while (buffer == 0) pthread_cond_wait(&condc, &m);
printf("%d\n", buffer); buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&m);
} return NULL;
}The consumer runs first and takes the mutex.
The buffer is empty: cond_wait atomically releases the mutex and sleeps. There is no lost-wakeup window.
The producer takes the mutex; the buffer is empty, so it skips the loop and writes 1.
signal wakes the consumer, but it cannot return until it reacquires the mutex (Mesa).
The producer may win the race and retake the mutex: the buffer is full → it waits and releases the mutex.
The consumer takes the mutex, retests the while condition (1 ≠ 0), and consumes the item.
The consumer signals condp; the producer wakes, finds the buffer empty, and writes 2.
Second round: the consumer takes 2. The output is the same in any order.
Adapted from Tanenbaum & Bos, Figure 2-32.
POSIX and Java
POSIX Semaphores
#include <semaphore.h> /* unnamed: threads of one process */ sem_t empty, full; sem_init(&empty, 0, N); /* 0: in-process */ sem_init(&full, 0, 0); sem_wait(&empty); /* … put … */ sem_post(&full); sem_destroy(&empty); /* named: between unrelated processes */ sem_t *s = sem_open("/os06", O_CREAT, 0644, 1); sem_wait(s); /* CS */ sem_post(s); sem_close(s); sem_unlink("/os06");
sem_wait | P / down: blocks if 0 |
sem_trywait, sem_timedwait | Try without waiting or with a timeout |
sem_post | V / up; safe in a signal handler |
sem_getvalue | Current value (informational only) |
- If the second argument of
sem_initis 1, the semaphore must be in shared memory. - macOS lacks unnamed semaphores (
sem_initis deprecated); use a named one ordispatch_semaphore. - Java:
java.util.concurrent.Semaphore:acquire(),release(), optional fair mode.
POSIX and Java
Java: synchronized, wait, and notify
public class OneSlot { private int slot = 0; /* 0 = empty */ synchronized void put(int x) throws InterruptedException { while (slot != 0) wait(); /* releases lock */ slot = x; notifyAll(); } synchronized int take() throws InterruptedException { while (slot == 0) wait(); int x = slot; slot = 0; notifyAll(); return x; } /* main: a producer puts 10, 20, 30, 40; main calls take() four times and prints */ }
- Every Java object is a monitor: an intrinsic lock plus a single wait set.
- A
synchronizedmethod or block takes the lock and releases it on exit (even on an exception); the lock is reentrant. wait()releases the lock and sleeps;notify()wakes one,notifyAll()wakes all. The semantics are Mesa:whileis required.- Producer and consumer share one wait set, so
notifyAllis safer.
took 10 took 20 took 30 took 40
POSIX and Java
Java: ReentrantLock and Condition
class Buffer { private final int[] buf = new int[2]; private int head = 0, tail = 0, count = 0; private final ReentrantLock lock = new ReentrantLock(); private final Condition notFull = lock.newCondition(); private final Condition notEmpty = lock.newCondition(); void put(int x) throws InterruptedException { lock.lock(); try { while (count == buf.length) notFull.await(); buf[tail] = x; tail = (tail + 1) % buf.length; count++; notEmpty.signal(); } finally { lock.unlock(); } } /* take(): while (count == 0) notEmpty.await(); … notFull.signal(); */ } /* producer puts 1..5; main calls take() 5 times */
java.util.concurrent.locks: one lock can have several conditions;signalwakes the right group.tryLock(), timed and interruptible locking, and an optional fair mode.- Always call
unlock()in afinallyblock. - Java 21 virtual threads blocking inside
synchronized"pinned" their carrier thread; JDK 24 (JEP 491) fixed this.
1 2 3 4 5 | sum = 15 1 2 3 4 5 | sum = 15 1 2 3 4 5 | sum = 15
Liveness
Priority Inversion
t = 0: low-priority L acquires the lock on shared resource R.
t = 2: high-priority H arrives and preempts L; at t = 3 it requests R and blocks. A short wait is expected: when L leaves, H enters.
But medium-priority M, which has nothing to do with R, preempts L and runs for a long time. H is indirectly waiting for M: priority inversion. If M runs from t = 4 to 10, L releases R only at t = 11: H waits 8 ms, and the longer M runs, the longer H waits, without bound.
Priority inheritance: while H waits for R, L temporarily inherits H's priority, so M cannot cut in. L leaves and H runs at once: in the same example H waits only 2 ms.
Priority inversion is the problem, not a solution; the remedies are priority inheritance and the priority ceiling. On a single core with strict preemptive priority scheduling, an H spinning on a spinlock never yields the CPU; lower-priority L never runs and never releases the lock: the system hangs.
Liveness
Mars Pathfinder (1997)
- July 1997: on the surface of Mars, Pathfinder, running the VxWorks real-time OS, kept resetting itself.
- While a low-priority meteorology task held the bus mutex, the high-priority bus management task blocked; a medium-priority communications task got in between.
- When the management task missed its deadline, a watchdog timer concluded the system had hung and forced a full reset.
- JPL engineers reproduced the bug on a ground replica; the mutex's priority inheritance option was turned on by a remotely uploaded patch.
- Today:
PTHREAD_PRIO_INHERIT, Linux PI-futexes, andrt_mutex; PREEMPT_RT, merged into mainline in Linux 6.12, relies on this mechanism.
Liveness
Liveness Problems
Lock-Free Programming
An Introduction to Lock-Free Structures
void push(node_t *n) { node_t *old = atomic_load(&top); do { n->next = old; } while (!atomic_compare_exchange_weak( &top, &old, n)); } /* on failure old = current top */
| Blocking | If the lock holder stalls, everyone stalls |
| Lock-free | The system as a whole always makes progress |
| Wait-free | Every thread finishes in a bounded number of steps |
Stack: top → A → B. A single atomic pointer instead of a lock.
T1 prepares to push X: old = A, X.next = A.
Meanwhile T2 pushes Y: CAS(top, A, Y) succeeds.
T1's CAS fails (top is now Y). C11 compare_exchange writes the current value into old; T1 retries with X.next = Y.
The second CAS succeeds. The ABA problem: if top goes A→B→A during a pop, CAS cannot tell; you need a version counter or safe memory reclamation (hazard pointers, epochs).
Summary
Summary
| Tool | What it provides | When to use |
|---|---|---|
| Peterson, strict alternation | Exclusion using only loads and stores (assuming SC) | Conceptual; not used in real code |
| Memory barrier | Ordering and visibility of loads and stores | Inside lock and atomic implementations |
| TAS, XCHG, CAS | Atomic read-modify-write | The foundation of locks and lock-free structures |
| Atomic variable | Indivisible update of one variable | Counters, flags, reference counts |
| Spinlock | Exclusion without sleeping | Multicore, very short CS, in the kernel |
| Mutex | Exclusion; waiters sleep | General-purpose critical sections |
| Semaphore | Counting, exclusion, and ordering | N identical resources, event notification |
| Monitor + condition variable | Structured exclusion + condition waiting | Complex conditions (Java, pthreads) |
| Reader–writer lock | Many readers, one writer | Read-mostly data |
Every tool provides mutual exclusion; progress and bounded waiting come from correct use and fair queues. Priority inversion and deadlock need separate thought.
Exercises
Exercises
The parent calls thr_join(); the child thread calls thr_exit() when it is done.
/* (a) no state variable */ void thr_exit() { lock(&m); signal(&c); unlock(&m); } void thr_join() { lock(&m); wait(&c, &m); unlock(&m); }
/* (b) no lock, uses if */ void thr_exit() { done = 1; signal(&c); } void thr_join() { if (done == 0) wait(&c); }
- In (a), what happens if the child finishes before the parent enters
thr_join()? - In (b), give an interleaving in which the parent sleeps forever.
- Implement
sem_down/sem_upusing only one mutex and one condition variable. - In an 8-core approximate counter with S = 1024, how far can
get()lag behind the actual value? What if S = 1?
Answers
- With no waiter, the signal is lost; the parent then sleeps and never wakes. You need a
donevariable that records the event, andwhile (done == 0). - The parent sees
done == 0and is interrupted beforewait; the child setsdone = 1and signals into the void; the parent resumes and sleeps. The test and the sleep must be under the same lock. sem_down:lock; while (value <= 0) wait(&c,&m); value--; unlock.sem_up:lock; value++; signal(&c); unlock. In this version the value never goes negative.- 8 × 1023 = 8,184. With S = 1 every increment goes to the global counter: the result is exact, but as slow as a single-lock counter.
Summary
Review Questions (1/2)
- State the three requirements for a critical-section solution. Which one does strict alternation violate?
- Why can Peterson's solution fail on x86? How is it fixed?
- Which requirement does a simple
test_and_setspinlock fail to guarantee? - In a CAS-based increment, what happens if two threads read the same value? Why is the final value correct?
Answers
- Mutual exclusion, progress, bounded waiting; strict alternation violates progress.
- The store buffer lets a store complete after a later load, so both read
false; use a full barrier orseq_cstatomics. - Bounded waiting: the same thread may lose every time.
- One succeeds; the other's CAS fails and it rereads; no increment is lost.
Summary
Review Questions (2/2)
- A semaphore starts at 2 and three processes call
waitin a row. What are the value and the queue (Silberschatz implementation)? - In the bounded-buffer solution, what happens if the producer's two
downcalls are swapped? - Why must a condition-variable wait under Mesa semantics be inside a
while? - Define priority inversion. How does priority inheritance solve it?
Answers
- Value −1; the first two pass, the third waits in the queue.
- With the buffer full, the producer sleeps holding the mutex and the consumer sleeps on the mutex: deadlock.
- The awakened thread doesn't run at once; the condition may be falsified meanwhile, and spurious wakeups can occur.
- While a high-priority task waits for a lock held by a low-priority task, medium-priority tasks cut in; with inheritance the lock holder temporarily takes the waiter's priority.
Summary
References
- A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th ed., Wiley, 2018 (Chapter 6: Synchronization Tools, Chapter 7: Synchronization Examples).
- A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th ed. (2014) / 5th ed. (2023), Pearson (§2.3 Interprocess Communication, §2.5 Classical IPC Problems).
- R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP), ostep.org: "Locks", "Condition Variables", "Semaphores", "Common Concurrency Problems".
- A. B. Downey, The Little Book of Semaphores, 2nd ed., Green Tea Press (free): readers–writers and philosophers solutions.
- POSIX.1-2017 (IEEE Std 1003.1):
pthread_mutex_lock,pthread_cond_wait,sem_overview(7); the Linuxfutex(2)man page. - B. Goetz et al., Java Concurrency in Practice, 2006; Java SE 21 API:
java.util.concurrent; JEP 491. - G. L. Peterson, “Myths About the Mutual Exclusion Problem”, IPL, 1981; M. Jones, “What really happened on Mars?”, 1997.