Threads A and B each execute x = x + 1 three times on a shared x (initially 0). Each increment is a load, an add and a store, and the steps of the two threads can interleave freely. What are the smallest and largest possible final values?
When processes or threads share data, unsynchronised updates cause race conditions. The critical-section problem, Peterson's solution, hardware instructions, semaphores, mutexes and monitors — and the bounded-buffer, readers–writers and dining-philosophers problems — are heavily examined.
Concurrent processes and threads interleave arbitrarily: the scheduler may preempt one in the middle of any instruction sequence. When they share data, some interleavings corrupt it. Take a shared counter (value 5) that a producer increments and a consumer decrements. counter++ looks like one step in C, but the CPU executes three machine instructions:
counter++ is really counter-- is really
R1 = counter R2 = counter
R1 = R1 + 1 R2 = R2 - 1
counter = R1 counter = R2| Time | Producer | Consumer | Effect |
|---|---|---|---|
| T0 | R1 = counter | R1 = 5 | |
| T1 | R1 = R1 + 1 | R1 = 6 | |
| T2 | R2 = counter | R2 = 5 | |
| T3 | R2 = R2 − 1 | R2 = 4 | |
| T4 | counter = R1 | counter = 6 | |
| T5 | counter = R2 | counter = 4 — wrong |
A race condition is a situation in which several processes access and manipulate the same data concurrently and the outcome depends on the particular order in which the accesses take place. The cure is to make sure that only one process at a time can manipulate the shared variable — to synchronize them. Step through exactly this bug, and then fix it with a mutex or a semaphore, in the Race-condition stepper tool on this page.
#include <pthread.h>
#include <stdio.h>
#define N 1000000
long counter = 0; /* shared data */
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *worker(void *arg)
{
for (int i = 0; i < N; i++) {
pthread_mutex_lock(&lock); /* entry section */
counter++; /* critical section */
pthread_mutex_unlock(&lock); /* exit section */
}
return NULL;
}
int main(void)
{
pthread_t t1, t2;
pthread_create(&t1, NULL, worker, NULL);
pthread_create(&t2, NULL, worker, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("counter = %ld (expected %d)\n", counter, 2 * N);
return 0;
}x = x + 1 n times (n ≥ 2) on a shared x = 0 with no locking. The final value can be anything from 2 to 2n — not n to 2n. One thread reads 0 and stalls while the other completes n − 1 increments; it then writes 1, and the same trick repeated at the end leaves just 2.Each process has a segment of code, its critical section (CS), in which it accesses shared data. The rule is that while one process executes its CS, no other process may execute its own CS. Every process follows the same skeleton:
do {
entry section ← ask permission to enter
critical section ← touch the shared data
exit section ← announce that we have left
remainder section ← everything else
} while (true);We assume every process runs at a non-zero speed but make no assumption about relative speeds or the number of CPUs. The kernel faces the same problem with its own data (the list of open files, for example). A non-preemptive kernel avoids races on a uniprocessor because a process in kernel mode runs until it leaves the kernel; a preemptive kernel must protect kernel data explicitly but responds faster, which real-time work requires.
| Attempt (two processes) | Idea | What fails |
|---|---|---|
| Strict alternation | Shared turn; Pi enters only when turn == i and hands turn to the other on exit | Progress — if P1 is busy in its remainder section, P0 cannot enter twice in a row even though the CS is empty |
| Flags only | flag[i] = true means “I want in”; wait while the other's flag is true | Progress — if both set their flags together, both wait for ever (a deadlock) |
| Peterson's solution | Flags plus turn: “I want in, but you go first” | Nothing — satisfies all three requirements (if the hardware does not reorder memory operations) |
Gary Peterson's 1981 algorithm solves the two-process case in pure software. The processes share flag[2] (who wants to enter, initially false) and turn (whose turn it is to go first). Process Pi, where the other process is Pj with j = 1 − i, runs:
/* shared */
bool flag[2] = { false, false };
int turn;
/* process Pi (j = 1 - i) */
do {
flag[i] = true; /* I want to enter */
turn = j; /* ...but you may go first */
while (flag[j] && turn == j)
; /* busy wait */
/* critical section */
flag[i] = false; /* exit section */
/* remainder section */
} while (true);Disabling interrupts during the critical section works on a uniprocessor: with no timer interrupt there is no preemption, so the instruction sequence runs undisturbed. It fails on multiprocessors — disabling interrupts on every CPU is slow, and the other CPUs keep running anyway — and it is far too dangerous to allow in user programs. Kernels use it only for a handful of instructions at a time.
Modern processors instead provide instructions that read and modify a word atomically — as one uninterruptible unit, even with several CPUs.
/* executed atomically by the hardware */
bool test_and_set(bool *target) {
bool rv = *target;
*target = true;
return rv; /* returns the OLD value */
}
bool lock = false; /* shared */
do {
while (test_and_set(&lock))
; /* spin while the old value was true */
/* critical section */
lock = false;
/* remainder section */
} while (true);/* executed atomically by the hardware */
int compare_and_swap(int *value, int expected, int new_value) {
int temp = *value;
if (*value == expected)
*value = new_value;
return temp; /* always returns the original value */
}
int lock = 0; /* shared: 0 = free, 1 = held */
do {
while (compare_and_swap(&lock, 0, 1) != 0)
; /* spin */
/* critical section */
lock = 0;
/* remainder section */
} while (true);Both simple locks give mutual exclusion and progress but not bounded waiting: an unlucky process may lose the race every time. Galvin's bounded-waiting version adds a waiting[n] array — on exit, a process scans it cyclically and hands the lock straight to the next waiting process, so nobody waits more than n − 1 turns. On x86 the instructions are XCHG and LOCK CMPXCHG; C11 and Java expose them as atomic variables (atomic_int, AtomicInteger.incrementAndGet()).
A lock that waits by looping is a spinlock, and the looping is busy waiting: the waiter burns CPU cycles achieving nothing. On a uniprocessor that is pure waste, because the lock holder cannot run while we spin. On a multiprocessor, spinning is actually efficient when locks are held very briefly — for less time than two context switches — because the waiter avoids being put to sleep and woken up again. Kernels therefore use spinlocks for short critical sections on multicore machines.
A mutex lock (from mutual exclusion) is the simplest tool: call acquire() before the critical section and release() after it; a Boolean available records whether the lock is free. Edsger Dijkstra introduced the more general semaphore around 1965. A semaphore S is an integer variable that, apart from initialisation, is accessed only through two atomic operations: wait(), originally P (Dutch proberen, “to test”), and signal(), originally V (verhogen, “to increment”). The classic busy-waiting definitions are:
wait(S) { /* P operation */
while (S <= 0)
; /* busy wait */
S--;
}
signal(S) { /* V operation */
S++;
}To avoid busy waiting, real implementations give each semaphore a queue of blocked processes. wait() decrements the value and, if it becomes negative, puts the caller to sleep with block(); signal() increments the value and, if processes are still waiting, wakes one with wakeup(P). In this version the value may go negative, and |S| equals the number of processes waiting. POSIX offers the same thing as sem_init(&s, 0, 1), sem_wait(&s) (P) and sem_post(&s) (V).
typedef struct {
int value;
struct process *list; /* processes blocked on this semaphore */
} semaphore;
void wait(semaphore *S) {
S->value--;
if (S->value < 0) {
/* add this process to S->list */
block();
}
}
void signal(semaphore *S) {
S->value++;
if (S->value <= 0) {
/* remove a process P from S->list */
wakeup(P);
}
}Ordering with semaphores. To make statement S1 in P1 execute before S2 in P2, share synch = 0. P1 runs S1; signal(synch); and P2 runs wait(synch); S2; — P2 cannot get past wait until P1 has signalled.
signal(mutex) … wait(mutex)) breaks mutual exclusion; writing wait(mutex) twice deadlocks the process; two processes taking two semaphores in opposite orders — P0: wait(S); wait(Q); P1: wait(Q); wait(S); — can deadlock; a waiting queue served in LIFO order can cause starvation; and a high-priority task blocked by a low-priority holder suffers priority inversion (see the RTOS topic).A monitor (Brinch Hansen 1973, Hoare 1974) is a programming-language construct that bundles shared variables with the procedures that operate on them. The compiler guarantees that only one process at a time can be active inside the monitor, so mutual exclusion comes free and cannot be forgotten. Java's synchronized methods with wait()/notify() form a monitor; so do C#'s lock blocks with Monitor.Wait/Pulse.
monitor ResourceAllocator {
boolean busy = false;
condition free;
procedure acquire() {
if (busy) free.wait(); // sleep and release the monitor
busy = true;
}
procedure release() {
busy = false;
free.signal(); // wake one waiter, if there is one
}
}To wait for a condition inside a monitor, a process uses a condition variable x. x.wait() suspends the caller — releasing the monitor — until another process calls x.signal(), which resumes exactly one suspended process. If no process is suspended on x, x.signal() has no effect. Contrast this with a semaphore, whose signal() always increments the value and is therefore remembered.
After P signals Q, the two cannot both be active in the monitor. Under signal-and-wait (Hoare semantics) P waits until Q leaves. Under signal-and-continue (Mesa semantics, used by Java and Pthreads) Q waits until P leaves — by which time the condition may have changed again, so waiters re-check it in a while loop. Pthreads provides condition variables through pthread_cond_wait(&cond, &mutex), which atomically releases the mutex and sleeps, and pthread_cond_signal(&cond).
Bounded buffer (producer–consumer). A producer places items into a buffer of n slots and a consumer removes them. Three semaphores suffice: mutex = 1 (mutual exclusion on the buffer), empty = n (number of empty slots) and full = 0 (number of filled slots).
semaphore mutex = 1, empty = n, full = 0;
/* producer */
do {
/* produce next_produced */
wait(empty); /* wait for a free slot */
wait(mutex);
/* add next_produced to the buffer */
signal(mutex);
signal(full); /* one more filled slot */
} while (true);
/* consumer */
do {
wait(full); /* wait for a filled slot */
wait(mutex);
/* remove an item into next_consumed */
signal(mutex);
signal(empty); /* one more free slot */
/* consume next_consumed */
} while (true);wait(mutex) before wait(empty) while the buffer is full, it sleeps holding mutex. The consumer can then never enter to empty a slot, and both are deadlocked. Always wait on the counting semaphore first and on mutex second.Readers–writers (Courtois, Heymans and Parnas, 1971). A shared database may be read by many processes at once, but a writer needs exclusive access. In the first readers–writers problem no reader is kept waiting unless a writer already holds the object — readers have priority, so writers may starve. The second problem gives waiting writers priority, so readers may starve. The first solution shares rw_mutex = 1, mutex = 1 (protecting read_count) and read_count = 0:
semaphore rw_mutex = 1, mutex = 1;
int read_count = 0;
/* writer */
do {
wait(rw_mutex);
/* writing is performed */
signal(rw_mutex);
} while (true);
/* reader */
do {
wait(mutex);
read_count++;
if (read_count == 1) /* first reader locks out writers */
wait(rw_mutex);
signal(mutex);
/* reading is performed */
wait(mutex);
read_count--;
if (read_count == 0) /* last reader lets writers in */
signal(rw_mutex);
signal(mutex);
} while (true);If a writer is inside and n readers arrive, one reader queues on rw_mutex and the other n − 1 queue on mutex. Many systems offer reader–writer locks directly (Pthreads pthread_rwlock_t); they pay off when reads vastly outnumber writes.
Dining philosophers (Dijkstra, 1965): five philosophers sit round a table with a bowl of rice and five single chopsticks, one between each pair. Each alternately thinks and eats, and needs both the left and the right chopstick to eat. It models allocating several resources among several processes without deadlock or starvation. The naive solution uses one semaphore per chopstick, all initialised to 1:
semaphore chopstick[5] = {1, 1, 1, 1, 1};
/* philosopher i */
do {
wait(chopstick[i]); /* left */
wait(chopstick[(i + 1) % 5]); /* right */
/* eat */
signal(chopstick[i]);
signal(chopstick[(i + 1) % 5]);
/* think */
} while (true);This guarantees that no two neighbours eat together, but if all five become hungry at once and each grabs the left chopstick, every chopstick semaphore is 0 and everyone waits for ever — deadlock, with all four Coffman conditions holding and a circular wait around the table.
room = 4): at least one of them can then get both chopsticks.Sleeping barber (also Dijkstra): a shop has one barber, one barber's chair and n waiting chairs. With no customers the barber sleeps; an arriving customer wakes him, takes a waiting chair if one is free, or leaves if all are taken. The semaphore solution uses customers = 0 (customers waiting), barbers = 0 (barber ready), mutex = 1 and an integer waiting. The barber loops on wait(customers); wait(mutex); waiting--; signal(barbers); signal(mutex); cut_hair();, while a customer does wait(mutex); and then, if waiting < n, waiting++; signal(customers); signal(mutex); wait(barbers); get_haircut(); — otherwise just signal(mutex) and leaves. It models a server with a bounded request queue.
Try the problem first, then reveal the working one step at a time.
Threads A and B each execute x = x + 1 three times on a shared x (initially 0). Each increment is a load, an add and a store, and the steps of the two threads can interleave freely. What are the smallest and largest possible final values?
(a) A counting semaphore is initialised to 7, after which 20 P and 15 V operations complete. What is its value? (b) A blocking semaphore is initialised to 3 and five processes call wait(S) with no signal. What is S, and how many processes are blocked?
Processes P1, P2 and P3 contain statements S1, S2 and S3. Use semaphores so that, whatever the scheduling, S2 runs first, then S1, then S3.
A bounded buffer has n = 3 slots (mutex = 1, empty = 3, full = 0, blocking semaphores). The producer adds three items, then tries a fourth; next the consumer removes one item. Give the semaphore values at each stage.
(a) A semaphore initialised to 15 undergoes 11 P and 6 V operations, all of which complete. What is its final value? (b) A blocking semaphore initialised to 2 receives 6 wait() calls and no signal(). What is its value and how many processes are blocked?
In the bounded-buffer producer, wait(empty) and wait(mutex) are swapped. Describe a sequence of events that deadlocks the system.
Show with a concrete scenario that strict alternation (while (turn != i); CS; turn = j;) satisfies mutual exclusion but violates progress.
Using semaphores, make process P1 print A, P2 print B and P3 print C so that the output is always exactly “BCA”.
Five dining philosophers share a counting semaphore room initialised to 4; each does wait(room) before picking up chopsticks and signal(room) after putting them down. Explain why deadlock is now impossible.
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.