Operating Systems · Lecture Notes
Chapter 6: Synchronization
Threads that share an address space, or processes that use a common region of memory, can read and write the same data without knowing about one another. The scheduler can preempt a thread after any instruction; on a multicore machine two threads really do run at the same time. Two pieces of code that are each correct on their own can therefore give a wrong result when run together. Synchronization is the discipline of regulating access to shared data so as to prevent these errors. These notes begin with the problem itself: the race condition and the critical section. They then examine software solutions built from nothing but reads and writes, the memory model of modern processors, and the atomic instructions that the hardware provides. On this foundation spinlocks, mutexes, semaphores, and monitors are built. The classic problems put these tools to the test. The last sections cover the POSIX and Java interfaces, priority inversion, and the basics of lock-free data structures.
Learning outcomes
- Problem
- Define the race condition and the critical section; explain the three conditions a solution must satisfy (mutual exclusion, progress, bounded waiting).
- Software and the memory model
- Evaluate the lock variable, strict alternation, and Peterson's solution against these three conditions; explain the effect of reordering on modern processors and the role of memory barriers.
- Hardware support
- Build locks and counters with
test_and_set,compare_and_swap, XCHG, and atomic variables; trace an interleaving step by step. - Tools
- Compare spinlocks, mutexes, semaphores, monitors, and condition variables; apply the Mesa-style
whilerule. - Classic problems
- Solve the bounded-buffer, readers–writers, and dining-philosophers problems; recognize the risks of starvation and deadlock.
- Real systems
- Use the POSIX and Java interfaces; interpret priority inversion (Mars Pathfinder) and the basics of lock-free structures.
6.1Race conditions
When processes and threads run alone, their behavior is easy to predict: the same input gives the same result. When they share data, this ease is lost. The result now depends not only on the code but also on the order in which the instructions of the two flows are interleaved. This section shows where the problem comes from through three examples: a counter in the kernel, a printer queue, and a single-line count++.
6.1.1Why synchronization?
Synchronization is the coordination of how concurrently running processes or threads access shared data, so that the data remains consistent.
A process can be interrupted after any of its instructions. The timer interrupt arrives, the scheduler picks another process, and the interrupted process leaves the update it was making half done. If another process reads the half-finished update in the meantime, it sees an inconsistent value. On multicore systems not even an interrupt is needed: two cores can truly write the same memory word at the same time. Figure 6.1 shows this situation. Two threads carry out the "read, modify, write" steps on the same count variable; a context switch in the middle leaves the update half done.
The symptoms of synchronization errors are varied:
- Inconsistent data and lost updates. One of two increments is lost; a node of a linked list is torn out of the list.
- An overwritten shared buffer. When a non-reentrant function, one that uses a common static buffer, is called from two threads, one overwrites the other's result.
- Deadlock. Two threads wait forever for each other to release something.
- Starvation. A thread never gets its turn; the others always get ahead of it.
What these errors have in common is that they appear occasionally. The program runs correctly a hundred times and gives a wrong result on the hundred-and-first. Stepping through it with a debugger changes the timing, so the error often disappears. Synchronization errors are therefore prevented not by testing but by getting the code right from the start.
6.1.2A race in the kernel: fork() and the pid
Races are not seen only in user programs; the kernel itself is full of shared data. In Silberschatz's example the kernel keeps the next free process identifier in a variable called next_available_pid. Its value is 2615. Processes P0 and P1 call fork() at almost the same moment. On each call the kernel code does three things: it reads the value, gives it to the child, and increments it and writes it back.
- P0 reads. P0's kernel code reads
next_available_pid: 2615. It is interrupted before it can increment and write. - P1 reads and writes. P1 also reads 2615, gives 2615 to its child, and writes 2616 to the variable.
- P0 continues. P0 resumes where it left off. With the old value it holds, it gives its child 2615 as well, and it also writes 2616.
fork(). Both processes read the value 2615; both children get the identifier 2615 and one of the two increments is lost (adapted from Silberschatz Figure 6.2).As a result two different processes have been given the same identifier and the counter has grown by one instead of two (Figure 6.2). Had the operations run in another order, for example if P0 had finished its three steps without being interrupted, the children would have received the identifiers 2615 and 2616. That the result depends on the order of the operations is the very essence of the basic concept of this chapter.
6.1.3The printer spooler directory
Tanenbaum explains the same problem with a printer queue. The names of files to be printed are written in turn into numbered slots of a spooler directory. The printer process scans the directory and prints the files. There are two shared variables: out points to the next slot to be printed and in to the first free slot. Initially slots 4, 5, and 6 are full; out = 4 and in = 7.
Processes A and B each want to print a file. Each reads in into a local variable next_free, writes its file name into that slot, and increments in. Figure 6.3 shows the following interleaving:
- A reads
inand setsnext_free = 7. Right then its time slice ends. - B also reads
in: 7 again. - B writes the name
b.txtinto slot 7 and setsin = 8. - A resumes where it left off. Because its local variable is still 7, it writes
a.txtinto slot 7, overwrites B's entry, and setsin = 8.
in and the next_free of both is 7. (b) First B writes b.txt into slot 7, then A writes a.txt into the same slot. The directory looks consistent, but B's file is never printed.Seen from outside, the directory is consistent: in = 8 and all the slots are full. The printer process notices no inconsistency. But B's output is lost, and B's user waits at the printer in vain.
A race condition arises when two or more processes access shared data and the final result depends on the order in which the accesses are executed.
6.1.4One line, three instructions: count++
A race condition does not need long code. A single count++ line in C compiles to three instructions at the machine level:
reg = count: load the value from memory into a register,reg = reg + 1: increment the register,count = reg: write the register back to memory.
count-- also consists of the same three steps; only the middle operation is a subtraction. Each thread has its own register set. When a thread is preempted, its registers are saved into its PCB; the intermediate value in the register is not reflected in memory.
Initially count = 5. A producer executes count++ and a consumer executes count--. The correct result is 5. What is the result in the following interleaving?
| Time | Who | Instruction | reg₁ | reg₂ | count |
|---|---|---|---|---|---|
| T₀ | producer | reg₁ = count | 5 | – | 5 |
| T₁ | producer | reg₁ = reg₁ + 1 | 6 | – | 5 |
| T₂ | consumer | reg₂ = count | 6 | 5 | 5 |
| T₃ | consumer | reg₂ = reg₂ − 1 | 6 | 4 | 5 |
| T₄ | producer | count = reg₁ | 6 | 4 | 6 |
| T₅ | consumer | count = reg₂ | 6 | 4 | 4 |
- T₀–T₁. The producer loads the value into its register and increments it. The register holds 6, but memory still holds 5. It is interrupted at exactly this moment.
- T₂–T₃. The consumer reads 5 from memory and decrements it to 4 in its own register.
- T₄. The producer runs again and writes 6 to memory.
- T₅. The consumer writes the 4 in its own register to memory and overwrites the producer's 6. The result is 4; the correct value was 5.
Had T₄ and T₅ been swapped, the producer would have written last and the result would have been 6. The six instructions of the two threads can be interleaved in 20 different ways while each thread's own order is preserved. When all 20 interleavings are tried one by one, only three results appear: 4, 5, and 6. The correct result, 5, is obtained only if the three instructions of one thread complete before the other thread's read.
The interleaving mentioned here is the arrangement of the instructions of concurrent flows into a single sequence, with the order inside each flow preserved. On a single core the scheduler determines this sequence. On multiple cores, the order in which the instructions on different cores reach memory determines it. For two flows of m and n instructions the number of possible interleavings is C(m + n, m); for two flows of three instructions each it is C(6, 3) = 20. This number grows very quickly as the flows get longer, and trying them all by hand becomes impossible.
Another face of the race is that the same program produces a different result on every run. The two processes below use a shared counter called n: the first process keeps incrementing n, and the second occasionally prints n and resets it to zero. The aim is to report how many events were counted in a given period.
/* Process 1 */ /* Process 2 */
repeat repeat
n = n + 1; print(n);
n = 0;With n = 5, the steps of the two processes can be interleaved in three different ways:
n = n + 1; print(n); n = 0→ 6 is printed and the counter becomes 0. This is the correct behavior.print(n); n = 0; n = n + 1→ 5 is printed and the counter becomes 1. This is also correct: the increment is left for the next report.print(n); n = n + 1; n = 0→ 5 is printed and the counter becomes 0. The increment appears in no report: it has been lost.
Such an execution is called a non-reproducible execution. The faulty result appears only under a particular timing, and rerunning with the same input usually does not repeat it.
The same race is easy to see on a real machine. In the following Java program two threads each increment an unprotected counter 100,000 times. The correct result is 200,000.
public class Race {
static int counter = 0; /* unprotected */
public static void main(String[] a) throws InterruptedException {
Runnable task = () -> { for (int n = 0; n < 100_000; n++) counter++; };
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start(); t1.join(); t2.join();
System.out.println("counter = " + counter);
}
}When the program was run three times on the same machine with JDK 21, it gave these outputs:
counter = 170429
counter = 150258
counter = 135129These numbers change on every run; on another machine, under another load, very different values may come out. The only thing that does not change is that the result is almost never 200,000. Each lost increment is the result of an interleaving like the one in Table 6.1.
Believing that a one-line C expression is indivisible. Expressions such as count++, x += 2, or a[i] = a[i] + 1 are a single line in the source code but a read–modify–write sequence on the machine, and can be interrupted between any two of its steps. Another misconception is "a very short operation, nothing will get in between." The probability of a race may be low; but in code that runs millions of times per second, a low-probability event happens often.
6.2The critical-section problem
Race conditions have a common structure: in a certain part of its code each process touches shared data. To solve the problem it is not necessary to protect the whole program; it is enough to prevent these parts from running at the same time. This section defines that part and what is expected of a solution.
6.2.1Entry, critical, exit, and remainder sections
Let the system have n processes: {P0, P1, …, Pn−1}. Each has a section of code in which it accesses shared data: writing a global variable, updating a table, writing a file.
A critical section is a piece of code in which a process accesses shared data and in which only one process should be at a time. Mutual exclusion is the condition that while one process is in its critical section, no other process is in its own critical section.
Before entering its critical section, a process asks for permission; the code that makes this request is called the entry section. When leaving the critical section it announces this to the others; this is the exit section. The rest of the code is the remainder section. A typical process repeats these four parts in a loop (Figure 6.4):
while (true) {
/* entry section */
/* critical section */
/* exit section */
/* remainder section */
}The critical-section problem is to design an entry and exit protocol that lets the processes cooperate. The contents of the critical section and the remainder section do not concern the protocol. What matters is that the entry and exit sections work correctly whatever the timing.
6.2.2The three requirements of a solution
Mutual exclusion alone is not enough. A protocol that lets no one into the critical section also "provides" exclusion but is useless. Silberschatz therefore asks three requirements of a solution.
- Mutual exclusion. While Pi is in its critical section, no other process can execute in its own critical section.
- Progress. If the critical section is empty and some processes want to enter, only the processes that are not in their remainder sections take part in deciding who enters next. This decision cannot be postponed indefinitely.
- Bounded waiting. After a process has made its request to enter, there is an upper bound on how many times the other processes can enter the critical section before its request is granted.
The first requirement is a safety property: "nothing bad ever happens." The second and third are liveness properties: "something good eventually happens." The progress requirement ensures that the system as a whole does not get stuck, and bounded waiting ensures that every individual process eventually gets a turn. If bounded waiting holds, no process falls into starvation.
None of the three requirements makes an assumption about the speed of the processes. It is assumed only that each process proceeds at a speed greater than zero; the relative speeds of the processes are unknown. Tanenbaum writes the same requirements as four items. Table 6.2 shows how these items match the three requirements.
| Tanenbaum's four conditions | Counterpart |
|---|---|
| No two processes may be in their critical sections at the same time. | Mutual exclusion |
| No assumptions about CPU speed or count. | Each process proceeds at a speed greater than zero; relative speeds are unknown. |
| No process outside its critical section may block others. | Progress |
| No process should wait forever. | Bounded waiting |
Confusing progress with bounded waiting. Progress means that, when the critical section is empty, one of those wanting to enter can do so in finite time. Bounded waiting is the limit on how many times way is given to others for a particular process. A lock can satisfy progress and still violate bounded waiting: each time someone enters, but the same unlucky process is always left outside.
6.2.3A critical-section timeline
The behavior of a good solution is clearly visible in Tanenbaum's timeline (Figure 6.5):
- T1. A enters its critical section.
- T2. B also wants to enter. Because the section is occupied, B blocks or busy-waits.
- T3. A leaves and the waiting B enters at once.
- T4. B leaves.
In the timeline, at no moment are two processes in the critical section together. A good solution must guarantee this behavior not only under this timing but under all possible timings. A single interleaving that violates one of the three requirements is enough to invalidate a solution.
6.3Software approaches
The first attempts at a solution use no special hardware support; they are built only from ordinary read and write instructions. Most of these attempts fail, but seeing why they fail is the best way to understand the three requirements. The section begins with an approach specific to operating systems, disabling interrupts, and ends with Peterson's algorithm.
6.3.1Disabling interrupts
On a single-core machine a process loses the processor only because of an interrupt. If a process disables interrupts before entering its critical section and re-enables them when it leaves, no timer interrupt arrives and no context switch takes place. On x86 this is done with the cli (clear interrupt flag) and sti (set interrupt flag) instructions. The idea is simple but unsuitable for user programs:
- A process that forgets to re-enable interrupts, or that enters an infinite loop in its critical section, locks up the whole system. The operating system can never take back control.
- While interrupts are disabled, I/O completion and timer interrupts wait. A long critical section leaves the system unresponsive.
- It does not work on a multicore machine.
clidisables interrupts only on the core that executes it; the other cores continue to access the shared data (Figure 6.6). cliandstiare privileged instructions. A program in user mode cannot execute them; if it tries, the processor raises a trap.
The method is common inside the kernel, but it is used briefly and locally. In Linux, local_irq_save() disables interrupts on the local core and saves the old state. For data shared with an interrupt handler, spin_lock_irqsave() both disables interrupts and takes a spinlock against the other cores. Both measures are needed together: disabling interrupts protects against the handler on the same core, and the spinlock protects against the other cores.
6.3.2The lock variable
The first software solution that comes to mind is a shared lock variable. If the value of lock is 0, the section is empty; if 1, someone is inside. A process entering waits until the value is 0 and then writes 1; on leaving it writes 0 again.
int lock = 0; /* shared */
void enter(void) {
while (lock != 0)
; /* busy wait */
lock = 1;
}
void leave(void) {
lock = 0;
}
/* each process: enter(); critical(); leave(); */The flaw in the code is that the "test" and "set" steps are separate. A process can be interrupted between the test on line 4 and the assignment on line 6. The following interleaving breaks mutual exclusion:
- Start.
lock = 0; the section is empty. - P0 tests. P0 reads
lock: 0. It leaves the loop. - P0 is interrupted. P0 is interrupted before performing the assignment
lock = 1on line 6. P1 runs and also reads 0. - P1 enters. P1 sets the lock to 1 and enters the critical section.
- P0 enters. P0 resumes where it left off. Since it has already done the test, it does not read the value again; it also writes 1 and enters.
lock as 0. (b) Both processes are in the critical section.When the entire state space is explored with a program, the same result comes out: a state in which two processes are in the critical section at the same time is reachable. The problem is circular at heart. The lock itself is a shared variable, and testing and changing it safely would need yet another lock. So a lock variable built from ordinary reads and writes is not enough by itself. The solution is to combine the test and the assignment into a single indivisible instruction; the hardware provides this instruction. That one can go further with reads and writes alone is shown by strict alternation and Peterson's algorithm.
6.3.3Strict alternation
The second attempt uses a turn variable instead of a lock. The shared variable turn shows whose turn it is to enter the critical section. P0 enters only when turn == 0, P1 only when turn == 1. The process that leaves gives the turn to the other.
/* P0 */
while (true) {
while (turn != 0) ; /* wait */
critical_section();
turn = 1;
noncritical();
}/* P1 */
while (true) {
while (turn != 1) ; /* wait */
critical_section();
turn = 0;
noncritical();
}This solution provides mutual exclusion: turn cannot be both 0 and 1 at the same time, and only the process that leaves the critical section changes it. Bounded waiting is also provided: the turn passes to the other process at every exit, so a process waits for at most one entry. The problem is in the progress requirement. The following scenario shows this clearly (Figure 6.8):
- With
turn = 0, P0 enters; P1 busy-waits. - On leaving, P0 sets
turn = 1; P1 enters. - On leaving, P1 sets
turn = 0and starts a long noncritical job. P0 enters and leaves once more and setsturn = 1. - P0 wants to enter again but it is P1's turn. The section is empty and P1 is not interested in the critical section; yet P0 cannot enter.
Strict alternation makes the processes run in forced turns. Of two processes with different speeds, the faster has to wait for the slower to finish its remainder section. A process that gets stuck in its remainder section, or never returns, keeps the other out forever. Also, the waiting process wastes processor time in the while (turn != i) ; loop.
Busy waiting is waiting by continuously testing a condition in a loop. The waiting process does not block; it keeps using the processor. A lock that busy-waits is called a spinlock.
6.3.4Peterson's algorithm
In 1981 G. L. Peterson gave a short solution that works correctly for two processes using only reads and writes. The algorithm combines the lock-variable idea with the strict-alternation idea. Each process has a flag: flag[i] = true means "Pi wants to enter." The shared turn variable decides who enters first when both want to.
/* 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 */
}The entry section is two lines. The process first announces its intention (flag[i] = true), then politely gives the turn to the other (turn = j, that is, "after you"). Then it waits as long as the other process wants to enter and it is the other's turn. On exit it merely lowers its own flag.
How the algorithm satisfies the three requirements can be shown in a few sentences:
- Mutual exclusion. If both processes are in the critical section,
flag[0]andflag[1]must both betrue. In that case each can leave the loop only whenturnis in its favor. Butturncannot be both 0 and 1 at once. The process that wroteturnlast has left the turn to the other and it is its job to wait. - Progress. If Pj does not want to enter,
flag[j] = false, and Pi's loop condition is immediately false: Pi enters without waiting. A process in its remainder section does not block the other. - Bounded waiting. If Pj leaves while Pi is waiting and immediately wants to enter again, it must write
turn = iin its entry section. This assignment clears Pi's way. Pi waits for at most one entry.
Peterson's algorithm is for two processes only. For n processes there is Lamport's bakery algorithm: each process takes a ticket number and the process with the smallest number enters. These algorithms have two important costs. The first is busy waiting; the waiting process burns processor time. The second is more important: the correctness proof assumes that all processors see the memory operations in a single common order. This assumption is called sequential consistency, and modern hardware does not provide it on its own.
Thinking that the order of the two assignments in the entry section does not matter. If turn = j is written first and flag[i] = true second, the algorithm breaks. P0 writes turn = 1 and is interrupted. P1 writes turn = 0 and flag[1] = true; since flag[0] is still false, it enters. P0 continues and writes flag[0] = true; since turn is 0, the condition is false and P0 enters too. When the entire state space is explored, it is verified that this order lets both processes into the critical section together; with the correct order, no such state is ever reachable.
6.3.5Code trace: Peterson
The behavior of the algorithm is best shown by tracing an interleaving step by step. The following code separates the entry and exit sections into the functions enter(i) and leave(i). Memory is assumed to be sequentially consistent: all memory operations can be explained by a single common order that preserves each thread's program order.
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;
}Table 6.3 traces a scenario in which two processes want to enter almost at the same time. Each row gives the shared variables and the states of the processes after a step. "Entering" means being in the entry section, "spinning" means being in the waiting loop, and CS means being in the critical section.
| Step | Event | flag[0] | flag[1] | turn | P0 | P1 |
|---|---|---|---|---|---|---|
| 1 | initial | false | false | ? | remainder | remainder |
| 2 | P0: flag[0] = true | true | false | ? | entering | remainder |
| 3 | P1: flag[1] = true | true | true | ? | entering | entering |
| 4 | P0: turn = 1 | true | true | 1 | entering | entering |
| 5 | P1: turn = 0 | true | true | 0 | entering | entering |
| 6 | P0 tests: turn == 1 is false | true | true | 0 | CS | entering |
| 7 | P1 tests: condition true | true | true | 0 | CS | spinning |
| 8 | P0: flag[0] = false | false | true | 0 | remainder | spinning |
| 9 | P1 tests: flag[0] is false | false | true | 0 | remainder | CS |
| 10 | P0: flag[0] = true, turn = 1 | true | true | 1 | entering | CS |
| 11 | P0 tests: condition true | true | true | 1 | spinning | CS |
| 12 | P1: flag[1] = false | true | false | 1 | spinning | remainder |
| 13 | P0 tests: flag[1] is false | true | false | 1 | CS | remainder |
Steps 4 and 5 are the key point of the trace. Both processes give the turn to the other; but turn is a single variable and the value of the last writer stays. Because P1 wrote last, turn = 0 and it falls to P1 to wait. In step 6 P0's condition flag[1] && turn == 1 is true && false; P0 enters. In step 7 P1's condition flag[0] && turn == 0 is true and P1 spins. Mutual exclusion is preserved.
In step 8 P0 leaves and lowers its flag. P1's condition turns false and P1 enters (step 9): progress is satisfied. In step 10 P0 wants to enter again; this time P0 is the last to write turn and it falls to P0 to wait. When P1 leaves (step 12), P0 enters. Had P1 wanted to enter again at once, it would have written turn = 0 and waited. So P0 waits for at most one entry: bounded waiting is satisfied too.
turn = 0, P0 is in the critical section, P1 is spinning. (b) Step 11: turn = 1, the roles have changed; P1 is in the critical section, P0 is spinning.This trace is a single interleaving; correctness has to hold for all of them. The small state space of two-process Peterson was explored completely with a program. In sequentially consistent memory neither a violation of exclusion nor a deadlock was found.
6.4The memory model
The proof of Peterson's algorithm assumes that when a process writes to a variable, the write is visible to everyone immediately and in the same order. On a modern multicore processor this assumption is false. Both the processor and the compiler may change the order of memory accesses as long as the result of a single thread does not change. This section explains how this reordering breaks Peterson and how it is prevented.
6.4.1Why does Peterson break on modern processors?
Each core has a store buffer. When a core executes a store instruction, the value first goes into this buffer. The core moves on to the following instructions without waiting for the store to reach memory; the buffer is drained to memory in the background. This arrangement makes stores much faster. If the same core then reads that address, it gets the value from its own buffer. The other cores, however, see the old value until the buffer drains.
/* P_i (i = 0 or 1, j = 1 - i) */
flag[i] = true;
turn = j;
while (flag[j] && turn == j)
;
/* critical section */
flag[i] = false;In Peterson's entry section each process first does two writes (flag[i] and turn) and then one read (flag[j]). With a store buffer, the following execution is possible (Figure 6.10):
- Start. In memory both flags are
false. - P0 writes. P0 writes
flag[0] = trueandturn = 1. Both writes wait in Core 0's buffer; they are not yet visible in memory. - P1 writes. P1 does the same; its writes are in Core 1's buffer.
- P0 reads. P0 reads
flag[1]from memory:false. It leaves the loop and enters the critical section. - P1 reads. P1 also reads
flag[0]from memory asfalseand enters. Both processes are in the critical section. - The buffers drain. Memory finally gets
flag[0] = flag[1] = true. But it is too late.
false. (b) Both processes read the other's flag from memory as false and enter the critical section.No instruction here has run "wrongly." Each core has executed the program in order from its own point of view. The problem is that one core's write reaches the other core after that core's next read. For an outside observer the effect is as if "the write slipped past the following read." The compiler can create the same effect: it can move the read of flag[j] ahead of the writes, or read a value that does not change in the loop once and keep it in a register. For these notes, all executions of Peterson were explored in a model built with store buffers. An execution in which both processes entered together was found in the version without barriers; none was found in the version with full barriers.
6.4.2Memory models and reordering
Which reorderings a processor allows is determined by its memory model. The experiment that shows the difference most briefly is called the store-buffer litmus test:
/* x = y = 0 */
/* T1 */ /* T2 */
x = 1; y = 1;
r1 = y; r2 = x;
/* r1 == 0 && r2 == 0 ? */Initially x = y = 0. T1 and T2 execute the two lines above. Which (r1, r2) results are possible?
- Number of interleavings. Each thread has two instructions. With each one's own order preserved, C(4, 2) = 6 interleavings arise.
- Sequential consistency. All six orders are tried. Since in each thread the write comes before the read, at least one write has completed by the time the first read is made. The results are (0, 1), (1, 0), and (1, 1); (0, 0) comes out in no order.
- A processor with a store buffer. While T1's write
x = 1waits in the buffer, T1 can readyfrom memory as 0. The same holds for T2. So on x86, ARM, and RISC-V,r1 = r2 = 0can also be observed. - With a full barrier. If a full memory barrier is placed between the write and the read in each thread, (0, 0) becomes impossible again. When all executions are explored in the store-buffer model, only the three results of SC remain.
Sequential consistency (SC) means that the memory operations of all threads can be arranged in a single common order. In this order each thread's own program order is preserved and every core sees the same order (Lamport, 1979).
| Model | Reordering allowed |
|---|---|
| Sequential consistency (SC) | None; all cores see a single common order. |
| x86-64 (TSO) | Only "write → later read"; writes are ordered among themselves. |
| ARMv8, RISC-V (weak) | Reads and writes can pass one another if there is no dependency between them. |
| Compiler | May move, keep in a register, or delete any access if equivalent for a single thread. |
x86's model is called total store order (TSO). This model is quite close to SC; it allows a single relaxation, the one arising from the store buffer. This is exactly the relaxation that breaks Peterson. In weak models such as ARM and RISC-V more reordering is possible. For example, two writes may appear to another core in the reverse of the order in which they were written.
Because of these differences, concurrent code is written not against "what the processor does" but against the language's memory model. The volatile keyword in C is not a tool for this job. volatile merely asks the compiler to actually perform every access to that variable. For threads it provides neither atomicity nor ordering. The right tools are C11's <stdatomic.h> header, Java's volatile fields and the java.util.concurrent package, and locks.
6.4.3Memory barriers
In Silberschatz's example two threads communicate through a flag. Thread 2 first writes x = 100 and then flag = true. Thread 1 waits until flag is true and then prints x. The programmer expects 100 to be printed. On a weak memory model, two things spoil this expectation (Figure 6.11):
- Writes are reordered. Thread 2's writes reach the other core in reverse order. Thread 1 sees
flagastruebutxis still 0. - Reads are reordered. Thread 1 itself may read
xbeforeflag. When it leaves the loop, thexit holds is the old value.
x is read before flag. (c) With a barrier on both sides the order is enforced and the output is 100. (d) C11 release/acquire atomics or Java volatile give the same guarantee more cheaply.A memory barrier (or fence) is an instruction that forces all memory accesses before it to complete, and become visible to the other cores, before those after it.
In the example thread 2 puts a barrier between the two writes: the write of x is certainly visible before flag. Thread 1 also puts a barrier after the loop: the read of x is certainly done after the read of flag. Together the two barriers guarantee that the output is 100. In real code the name of the barrier varies with the platform: mfence on x86, dmb on ARM, smp_mb() in the Linux kernel, atomic_thread_fence in C11.
A full barrier is an expensive instruction, because it waits for the store buffer to drain. In most cases a lighter guarantee suffices. The writing side writes flag with release semantics: all earlier accesses are visible before this write. The reading side reads flag with acquire semantics: later accesses are not performed before this read. Implementations of locks and semaphores already include these barriers. So in code protected by a lock there is no need to write barriers separately. Barriers are the tool of those who write locks and atomic variables.
Writing Peterson's algorithm in C with volatile variables and assuming it will work correctly on x86. volatile keeps the compiler from holding the read in a register but does not affect the processor's store buffer. The program seems to work correctly for a long time, and then occasionally two threads enter the critical section together. Adding usleep() to the wait loop is not a cure either; it only changes the timing and makes the bug rarer. The cure is to put a full barrier between the write flag[i] = true and the read flag[j], or to declare the variables as sequentially consistent atomics (_Atomic, default memory_order_seq_cst).
6.4.4Peterson's algorithm written correctly in Java
In the Java memory model, reads and writes of volatile fields are sequentially consistent. The compiler and the JVM add the barriers needed to preserve the order of these accesses themselves. So Peterson's algorithm works correctly in Java with separate volatile fields:
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 */
}In the code the two flags are separate fields, and turn is also volatile. Thread.onSpinWait() (Java 9 and later) gives the processor the hint "I am busy-waiting"; on x86 it becomes the pause instruction. This instruction reduces the loop's power consumption and the harm it does to the hardware thread sharing the same core. The main part of the code in the slides was summarized as a comment; the full runnable version is as follows:
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;
}
public static void main(String[] a) throws InterruptedException {
Thread[] t = new Thread[2];
for (int k = 0; k < 2; k++) {
final int i = k;
t[k] = new Thread(() -> {
for (int n = 0; n < 100_000; n++) { lock(i); counter++; unlock(i); }
});
}
for (Thread x : t) x.start();
for (Thread x : t) x.join();
System.out.println("counter = " + counter);
}
}The program was run three times with JDK 21 and gave this output every time:
counter = 200000
counter = 200000
counter = 200000This time the counter is 200,000 on every run: the critical section is protected. The unprotected version of the same counter gave different and smaller values on every run. That this program works correctly under one particular timing is not a proof; the guarantee of correctness is the sequential consistency that the Java memory model gives for volatile.
When writing Peterson in Java, three pitfalls are common. The first is the declaration volatile boolean[] flag: this makes only the array reference volatile, not the elements. Reads and writes of the elements remain ordinary accesses. The second is generating the process number with getId() % N; two threads may get the same value of i and both use the same flag. The third is putting System.out.println in the critical section. Printing uses its own lock internally and changes the timing so much that the measurement loses its meaning.
6.4.5The synchronization barrier
The word "barrier" names two different concepts in synchronization. A memory barrier enforces the order of a single core's memory accesses. A synchronization barrier makes a group of processes meet at a certain point.
Parallel computations divided into phases need this meeting. In a grid simulation each process computes a slice of the grid. The next phase uses the values of the neighboring slices from this phase. So no process should move on to the next phase before the others have finished this one. A process that has finished the phase calls barrier_wait() and blocks. When the N-th process arrives, the barrier opens and all move on to the next phase together (Figure 6.12).
In POSIX there is pthread_barrier_wait for this job, and in Java CyclicBarrier. In the Java fragment below three threads compute two phases. The second argument given to the barrier is an action; it runs once when the last thread arrives, before the barrier opens.
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();
} */The full program was run with JDK 21, with each thread sleeping a random time between phases:
import java.util.concurrent.CyclicBarrier;
public class Barrier {
public static void main(String[] a) throws Exception {
int[] phase = {0};
var b = new CyclicBarrier(3,
() -> System.out.println(
"phase " + phase[0]++ + " done"));
Thread[] t = new Thread[3];
for (int k = 0; k < 3; k++) {
t[k] = new Thread(() -> {
try { for (int f = 0; f < 2; f++) { Thread.sleep((long) (Math.random() * 20)); b.await(); } }
catch (Exception e) { }
});
t[k].start();
}
for (Thread x : t) x.join();
}
}The output is the same on every run, because the action runs exactly once in each phase and only after all the threads have arrived:
phase 0 done
phase 1 doneThe order in which the threads reach the barrier changes on every run. Because the program's output does not depend on this order, the variability is not visible from outside.
6.5Hardware support
The common problem of software solutions is that reading a value and writing to it are two separate steps. Anything can happen in between. To close this gap the hardware offers instructions that test and change a memory word without interruption. These instructions are the foundation of all locks, semaphores, and lock-free data structures.
6.5.1Atomic hardware instructions
An atomic instruction is a hardware instruction that reads, modifies, and writes a memory word and performs these three steps without interruption. While the instruction runs, no other core can access that word; the effect of the instruction is seen either in full or not at all.
Silberschatz defines the behavior of these instructions with a C-like function. The three lines of the test_and_set function below are in reality a single machine instruction:
/* 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 function returns the old value of the target and in every case writes true to it. If the lock is free (false), the caller gets false and the lock is now true: the lock has been acquired. If the lock is taken, the caller gets true and nothing changes: the loop tries again. The "window between the test and the assignment" of the lock variable has disappeared.
Atomicity holds on multiple cores as well. Old processors used to lock the memory data path for the duration of the instruction. Today the cache-coherence protocol reserves the relevant cache line for a single core for the duration of the instruction; the other cores cannot access that line in the meantime. Table 6.5 gives the counterparts on common architectures.
| Architecture | Atomic read-modify-write |
|---|---|
| x86-64 | XCHG, LOCK CMPXCHG, LOCK XADD, LOCK BTS |
| ARMv8 | LDXR/STXR (LL/SC); with v8.1 LSE, CAS, LDADD, SWP |
| RISC-V "A" extension | LR/SC, AMOSWAP, AMOADD |
| Tanenbaum's virtual processor | TSL REGISTER,LOCK |
The LL/SC pair on ARM and RISC-V reaches the same result by a different route. LDXR (load-linked) reads the value and starts monitoring the address. STXR (store-conditional) writes only if no other write has intervened; if one has, it fails and the code tries again.
6.5.2A critical section with TSL
Tanenbaum explains the same idea with an instruction called TSL (test and set lock). TSL REGISTER,LOCK reads the word LOCK into a register and writes 1 to LOCK; it does both in a single indivisible step. Entering and leaving the critical section are written with a few lines of assembly:
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
RETenter_region tests the old value of LOCK. If the value was 0, the lock was free and now belongs to this core; the function returns. If the value is not 0, the lock is taken and the loop tries again. leave_region sets the lock to 0 with an ordinary write. Table 6.6 traces a scenario in which two processors try to enter at the same time.
| Step | Event | LOCK | R0 | R1 |
|---|---|---|---|---|
| 1 | lock free | 0 | – | – |
| 2 | CPU 0: TSL (old 0 into the register, 1 into LOCK) | 1 | 0 | – |
| 3 | CPU 1: TSL (old 1 into the register) | 1 | 0 | 1 |
| 4 | CPU 0: CMP → 0, in the critical section; CPU 1: JNE → loop | 1 | 0 | 1 |
| 5 | CPU 0: MOVE LOCK,#0, leaves | 0 | 0 | 1 |
| 6 | CPU 1: TSL → sees 0, entering | 1 | 0 | 0 |
The third step is important. CPU 1's TSL also writes 1 to LOCK; but since the value is already 1, nothing changes. The 1 that arrives in CPU 1's register is the information "the lock was taken." At no moment are the two processors inside together. TSL works on multiple cores too: unlike disabling interrupts, it also prevents the other processors from accessing that word (Tanenbaum MOS Figure 2-25).
6.5.3The XCHG instruction
XCHG swaps the contents of two operands in a single step. First 1 is put into the register, then the register is swapped with LOCK. After the swap LOCK is in every case 1 and the register holds the old value of LOCK (Figure 6.13). The effect is the same as TSL.
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
RETXCHG. Afterwards the register holds the old value of LOCK and LOCK holds 1. If the old value was 0, the lock has been acquired.This is the basic instruction used for locking on Intel x86 processors. XCHG with a memory operand is implicitly treated as LOCK-prefixed, that is, it is always atomic. Its counterpart in C11 is the call atomic_exchange(&lock, 1).
6.5.4A lock with compare_and_swap
The most flexible atomic instruction is compare-and-swap (CAS). The instruction takes three operands: an address, an expected value, and a new value. If the value at the address equals the expected one, it writes the new value. In every case it returns the old value at the address.
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; }When used as a lock, the expected value is 0 and the new value is 1. If the lock is free, CAS writes 1 and returns 0: the loop ends. If the lock is taken, CAS writes nothing and returns 1: the loop continues. The trace goes as follows:
- The lock is free.
lock = 0. - T0 wins. T0's CAS finds
lockto be 0, writes 1, and returns 0. T0 leaves the loop and enters the critical section. - T1 loses. T1's CAS finds 1. This is not the expected value; it writes nothing and returns 1.
- T1 waits. T1 busy-waits; each attempt loops without changing the memory word.
- T0 leaves. T0 sets the lock to 0. In real code this write is done with release ordering.
- T1 enters. T1's next CAS succeeds.
On x86 the counterpart of CAS is LOCK CMPXCHG. In C11 atomic_compare_exchange_strong and in Java AtomicInteger.compareAndSet do the same job (Silberschatz 10e §6.4.2).
Thinking that a simple spinlock built with an atomic instruction satisfies all three requirements. Mutual exclusion is satisfied thanks to atomicity. Progress is satisfied too: when the lock is released, one of the attempts certainly succeeds. But which thread's CAS runs first when the lock is released is undetermined. An unlucky thread can lose every race; bounded waiting is not guaranteed.
6.5.5Atomic increment with CAS
Beyond building locks, CAS also makes it possible to update without using a lock. To increment a shared counter, a thread first reads the value. Then with CAS it says, "if the value is still as I read it, write one more." If someone has changed the value in the meantime, CAS fails and the loop tries again with the current value.
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); */Initially v = 5. T1 and T2 call increment(&v) at the same time. The order is as follows: T1 reads, T2 reads, T2 does CAS, T1 does CAS, T1 retries. What are v and the local values at each step?
| Step | Event | v | T1.temp | T2.temp |
|---|---|---|---|---|
| 1 | T1 reads | 5 | 5 | – |
| 2 | T2 reads | 5 | 5 | 5 |
| 3 | T2: CAS(v, 5, 6) → returns 5, succeeds | 6 | 5 | 5 |
| 4 | T1: CAS(v, 5, 6) → returns 6, fails | 6 | 5 | – |
| 5 | T1 reads again | 6 | 6 | – |
| 6 | T1: CAS(v, 6, 7) → returns 6, succeeds | 7 | 6 | – |
- Steps 1–2. Both threads read 5. With a plain
v++an increment would be lost here. - Step 3. T2's CAS finds
vstill 5 and writes 6. The 5 it returns equalstemp; T2's loop ends. - Step 4. T1's CAS finds
vto be 6. The expected value, 5, does not match; CAS does not write and returns 6. Since 6 ≠ 5, the loop repeats. - Steps 5–6. T1 reads the current value (6) and its CAS succeeds this time:
v = 7.
No increment was lost and nobody held a lock. When all interleavings of the two threads are explored with a program, the final value is always 7.
This "read → compute → CAS → retry if it fails" loop is the basic pattern of lock-free data structures. If the counter is declared as atomic_int, C11 does the same increment in one line: atomic_fetch_add(v, 1). On x86 this is executed with a single LOCK XADD instruction without a loop.
6.5.6A CAS lock with bounded waiting
What the simple CAS lock lacked was bounded waiting. Silberschatz fills this gap with a waiting[n] array. Each waiting process raises its own flag. The process that leaves the critical section does not release the lock directly; it first scans the processes in ring order, starting with the one after itself. If it finds the first waiter, it hands the lock over to it.
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 */
}The subtlest point of the code is the hand-over step. When the leaving process finds a waiting Pj, it does not touch lock; it merely sets waiting[j] = false. Since Pj's loop condition is waiting[j] && key == 1, Pj leaves the loop and enters. During this the lock stays at 1, so no one else can slip in. The lock is really released (lock = 0) only when no one is waiting.
j = 2, 3, …; the first waiter is P3. (b) P1 does not release the lock; it sets waiting[3] = false; P3 enters and lock is still 1. With five processes, at most n − 1 = 4 turns have to be waited.The ring scan guarantees bounded waiting. A waiting process waits for at most n − 1 entries, those of the processes that will be scanned before it. Table 6.8 traces a scenario with four processes. The line numbers in this code are as follows: 2 raising the flag, 3–4 the waiting loop, 5 lowering the flag, 7–9 the scan, 10–13 releasing or handing over.
/* 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 */| Step | Event | lock | key | j | waiting | CS |
|---|---|---|---|---|---|---|
| 1 | lock free, no waiters | 0 | – | – | F F F F | – |
| 2 | P2 arrives; CAS returns 0 | 1 | 0 | – | F F T F | – |
| 3 | P2 waiting[2] = false, enters | 1 | 0 | – | F F F F | P2 |
| 4 | P0 arrives; CAS returns 1, spins | 1 | 1 | – | T F F F | P2 |
| 5 | P3 arrives and spins | 1 | 1 | – | T F F T | P2 |
| 6 | P2 leaves; the scan stops at j = 3 | 1 | – | 3 | T F F T | P2 |
| 7 | P2 waiting[3] = false; P3 enters | 1 | – | 3 | T F F F | P3 |
| 8 | P3 leaves; j = (3 + 1) % 4 = 0 | 1 | – | 0 | T F F F | P3 |
| 9 | the turn is handed to P0 | 1 | – | 0 | F F F F | P0 |
| 10 | P0 leaves; j = 1, 2, 3 are empty, j back to 0 | 1 | – | 0 | F F F F | P0 |
| 11 | j == i: no one waiting, lock = 0 | 0 | – | – | F F F F | – |
The ninth step is interesting. P0 had arrived before P3, but the ring order chose P3 first. This lock does not work in arrival order (FIFO); it merely ensures that there is an upper bound on the wait. Because when P2 leaves the scan starts from the one after itself, j = 3, P3 has got ahead. Still, P0 waits for at most n − 1 = 3 entries. The only moment the lock is really free is step 11.
6.6Locks
Atomic instructions are impractical on their own; programmers use them not directly but through tools built on top of them. This section covers the most basic of these tools: atomic variables, spinlocks, and mutexes. It then looks at how data structures that use locks are scaled.
6.6.1Atomic variables
Languages and libraries offer atomic instructions as atomic variables. In C11 every access to a variable of type _Atomic is atomic and, by default, sequentially consistent (seq_cst). With this type even the expression counter++ is atomic; it compiles to lock xadd on x86 and ldadd on ARMv8.1.
#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 */Java's counterpart is the java.util.concurrent.atomic package. AtomicInteger.incrementAndGet() is an atomic increment and compareAndSet(expected, new) is CAS directly:
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 */The fragments in the slides were combined into a single program. The program also increments the same counter with a synchronized method:
import java.util.concurrent.atomic.AtomicInteger;
public class Atom {
static AtomicInteger atom = new AtomicInteger();
static int plain = 0;
static synchronized void increment() { plain++; }
public static void main(String[] a) throws InterruptedException {
Runnable task = () -> { for (int n = 0; n < 100_000; n++) { atom.incrementAndGet(); increment(); } };
Thread t1 = new Thread(task), t2 = new Thread(task);
t1.start(); t2.start(); t1.join(); t2.join();
System.out.println("AtomicInteger = " + atom.get());
System.out.println("synchronized = " + plain);
var v = new AtomicInteger(5);
System.out.println(v.compareAndSet(5, 6) + " " + v.get());
System.out.println(v.compareAndSet(5, 7) + " " + v.get());
}
}When run three times with JDK 21, it gave the same output every time:
AtomicInteger = 200000
synchronized = 200000
true 6
false 6Both methods give the result 200,000. compareAndSet(5, 6) succeeds because the value is 5. compareAndSet(5, 7) fails because the value is now 6, and v stays at 6.
counter++ versus fetch_add. In the top row two reads see the same value and one increment is lost. In the bottom row each increment is a single step; the cache line is locked for the duration of the operation.Believing that atomic variables protect several variables together. An atomic variable makes the update of only one variable indivisible. If a buffer array and the number of items in it have to be kept consistent together, making the counter atomic is not enough. The array may have been updated while the counter has not yet been incremented. For consistency across several variables a lock or monitor is still needed.
6.6.2Spinlocks and mutexes
What a waiting thread does while a lock is taken gives rise to two kinds of locks. A spinlock busy-waits: it does not give up the processor and keeps testing the lock. As soon as the lock is released, it enters without a context switch. A sleeping mutex, on the other hand, blocks the waiter; the kernel gives the processor to another thread. When the lock is released, the waiter is woken.
A mutex (mutual exclusion lock) is a binary lock with an owner, used for mutual exclusion. lock acquires the lock or makes the caller wait until the lock is free; unlock releases the lock and can be called only by the lock's owner.
The choice depends on how long the wait will be. If the critical section is shorter than two context switches, spinning is cheaper than sleeping. If the critical section is long or can block inside (for example a disk read), spinning burns the processor for nothing. On a single-core machine a spinlock is meaningless: the thread holding the lock cannot run, because the spinning thread is using the processor. The waiter burns its whole slice, and the lock can be released only at the next context switch.
| Spinlock | Mutex (sleeping) | |
|---|---|---|
| Suitable | Multicore; critical section shorter than two context switches | Long critical section, or one that can block |
| Single core | Meaningless: the holder cannot run, the waiter burns its slice | Right choice |
| Example | Linux spin_lock, pthread_spin_lock | pthread_mutex_t, Java synchronized |
Most real mutex implementations combine the two methods. They first spin for a short time and, if the lock is not released in that time, sleep.
6.6.3How a mutex is written: yield and futex
Tanenbaum writes a mutex with TSL for user-level threads. The code is very similar to enter_region with TSL. Its only difference is that if the lock is taken it calls thread_yield instead of looping back:
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
RETWith user-level threads, thread switching is not driven by the timer interrupt. A thread that busy-waits never gives up the processor, and the thread holding the lock can never run. thread_yield gives the processor to the other threads in the same process; the owner of the lock can run and release it (Tanenbaum Figure 2-29).
The solution in Linux is the futex (fast userspace mutex). The lock is an integer word in user space. If there is no contention, the lock is acquired and released with a single atomic instruction; the kernel is never entered. The kernel steps in only when a thread really needs to sleep. glibc's pthread_mutex, Java locks, and Go's concurrency tools are built on top of this mechanism. In the common design in Ulrich Drepper's paper "Futexes Are Tricky," the word has three values: 0 free, 1 locked with no waiters, 2 locked with possible waiters.
- No contention. T1 turns the word from 0 to 1 with a single CAS. No system call is made.
- T2 arrives. T2 finds the lock taken, sets the value to 2 ("there are waiters"), and sleeps in the kernel's wait queue with the
futex_waitsystem call. - T1 releases. T1 sets the word to 0. Since the old value was 2, it calls
futex_wake. - T2 wakes. T2 sets the word to 2 again with an atomic exchange (
xchg). Since the old value returned by the exchange is 0, the lock now belongs to T2. T2 cannot know whether there are other waiters; so it cautiously sets the value to 2, not 1.
futex_wake; the woken T2 sets the word to 2 again and takes the lock.The reason for separating the values 1 and 2 is to avoid unnecessary futex_wake calls. If the value is 1, nobody is sleeping and the releasing thread never enters the kernel. The woken thread's setting the value to 2 sometimes leads to an unnecessary futex_wake call; but it ensures that no waiter is forgotten. Thus in the uncontended case acquiring and releasing each consist of a single atomic instruction.
6.6.4The scalable counter
A counter protected by a single lock is correct but does not scale. Every increment competes for the same lock, and the same cache line is moved between cores continually. As the number of cores grows, the total time does not shrink; it grows. The approximate counter of the Arpaci-Dusseaus solves this problem with per-core counting. Each core has its own local counter and its own lock. When a local counter reaches a threshold S, its value is transferred to the global counter.
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;
}add takes only the local lock of the calling core. Because different cores use different locks, they do not wait for each other. The global lock is taken only during a transfer, that is, once every S increments. get returns only the global counter; so the result is approximate.
There are four cores and S = 4. The cores call add in the order below. After each step, what are the local counters (L1–L4), the global counter G, and the true total?
| t | Cores incrementing | L1 | L2 | L3 | L4 | G | true |
|---|---|---|---|---|---|---|---|
| 0 | – | 0 | 0 | 0 | 0 | 0 | 0 |
| 1 | 1, 3 | 1 | 0 | 1 | 0 | 0 | 2 |
| 2 | 1, 2, 3 | 2 | 1 | 2 | 0 | 0 | 5 |
| 3 | 1, 3, 4 | 3 | 1 | 3 | 1 | 0 | 8 |
| 4 | 1, 2 | 4 → 0 | 2 | 3 | 1 | 4 | 10 |
| 5 | 3, 4 | 0 | 2 | 4 → 0 | 2 | 8 | 12 |
- t = 1–3. Eight increments occur, but no local counter reaches 4. The global lock is never touched; G = 0.
- t = 4. L1 reaches the threshold. Core 1 takes the global lock, adds 4 to G, and resets its local counter.
- t = 5. L3 also reaches the threshold and transfers: G = 8.
- Reading.
get()returns 8. The true value is 12; the difference of 4 sits in L2 and L4.
In the worst case every local counter stops at S − 1 and has never been transferred. So get() can lag the true value by at most NCPU × (S − 1); in the example it is 4 × 3 = 12. S sets the trade-off between accuracy and scalability. A large S goes to the global lock rarely and scales well, but the value read lags further behind. With S = 1 every increment goes to the global counter: the result is exact but the counter is as slow as a single-lock counter. The percpu_counter in the Linux kernel is based on the same idea.
6.6.5Lock ordering in concurrent data structures
The easiest way to make a data structure thread-safe is to wrap every operation in a single lock. This is correct but serializes all operations. Splitting the lock can increase parallelism; Table 6.11 summarizes common layouts.
| Structure | Lock layout | Result |
|---|---|---|
| Linked list | Single mutex | Simple. malloc should be done outside the lock; unlock must not be forgotten on any return path. |
| Hand-over-hand locking | A lock per node: take the next one first, then release the previous one | Traversals proceed in parallel; but the cost of the lock on each node often eats up the gain. |
| Queue | Separate locks for head and tail, a dummy node | Enqueue and dequeue can happen at the same time. |
| Hash table | A locked list per bucket | Operations going to different buckets do not wait for one another; scales very well. |
The two-lock queue published by Michael and Scott in 1996 is a fine example of splitting a lock. There is always a dummy node at the head of the queue. Initially both the head and the tail point to this dummy. enqueue takes only tail_lock and advances the tail. dequeue takes only head_lock: it frees the old dummy, returns the value of the first real node, and that node becomes the new dummy (Figure 6.18). Thanks to the dummy node the two operations never modify the same node.
enqueue(A) and enqueue(B) take only tail_lock. (b) dequeue() takes only head_lock; the old dummy is freed, A's value is returned, and A becomes the new dummy.The practical rule is this: write the code correctly with a single lock first. If measurement shows that the lock is really a bottleneck, the lock is split. More locks does not always mean faster. Every lock brings an extra atomic instruction and a risk of deadlock.
6.7Semaphores
A mutex says only "let one in." Many coordination problems ask for more: taking one of N identical resources, or waiting until an event occurs. Dijkstra's semaphore meets both needs with a single tool.
6.7.1The semaphore
A semaphore is an integer that is accessed only through two atomic operations (Dijkstra, 1965):
wait(S), also P ordown: if the value is 0, the calling process blocks (sleeps); otherwise the value is decremented by 1 and the process continues.signal(S), also V orup: the value is incremented by 1; if some process is waiting, one is woken.
The value of a semaphore can be thought of as the number of available resources. If the value is 3, three more processes can pass without waiting. The letters P and V come from Dijkstra's Dutch words; Tanenbaum uses the names down and up, and Silberschatz wait and signal.
wait and signal are themselves short critical sections: they read and change the value. The operating system protects these two operations by disabling interrupts on a single core and with a spinlock on multiple cores. Busy waiting does not disappear completely this way; but it shrinks from the application's long critical section to a few instructions of the semaphore operation. In real systems a process that calls down when the value is 0 sleeps. The busy-waiting version seen in textbooks is only the first, conceptual definition.
6.7.2A semaphore with a wait queue
In Silberschatz's implementation a semaphore consists of a value and a list of waiting processes:
typedef struct {
int value;
struct process *list;
} semaphore;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);
}
}In this implementation wait first decrements the value and then tests it. So the value can be negative. If the value is −k, k processes are waiting in the queue (Figure 6.19). signal increments the value; if the result is still 0 or negative, someone is waiting in the queue and the one at the head is woken.
There is a single resource and the semaphore starts at 1 (a binary semaphore, working like a mutex). T1, T2, and T3 do wait in turn, then signal in the same order.
| Event | S.value | S.list | In the critical section |
|---|---|---|---|
| initial | 1 | empty | – |
T1 wait | 0 | empty | T1 |
T2 wait | −1 | T2 | T1 |
T3 wait | −2 | T2, T3 | T1 |
T1 signal | −1 | T3 | T2 |
T2 signal | 0 | empty | T3 |
T3 signal | 1 | empty | – |
- T1 wait. The value becomes 0. Since it is not negative, T1 continues.
- T2 and T3 wait. The value becomes −1 and then −2; both are added to the queue and sleep.
- T1 signal. The value becomes −1. Since it is still ≤ 0, T2 at the head of the queue is woken and enters the critical section.
- T2 signal. The value becomes 0; T3 is woken.
- T3 signal. The value becomes 1 and nobody is waiting.
The order of the queue is not specified in the definition of a semaphore. If a FIFO queue is used, every waiter eventually gets its turn and the wait is bounded. Another order (for example LIFO or by priority) can lead to starvation. In Tanenbaum's definition the value is never negative: if someone is asleep, up wakes one directly without incrementing the value. The two definitions give the same behavior from outside; only the reading of the internal value differs.
6.7.3Usage patterns
The initial value of a semaphore determines what it is used for:
- Binary semaphore (like a mutex). The initial value is 1. Each process does
wait… critical section …signal. - Counting semaphore. The initial value is N and it represents N identical resources: the connections of a connection pool or the empty slots of a buffer. For example, if at most 5 connections can be opened to a database, the semaphore starts at 5; the sixth request blocks.
- Signaling or ordering. The initial value is 0 and it is used to wait until an event happens. If P2's statement S2 must run after P1's statement S1, P1 does
signal(synch)after S1 and P2 doeswait(synch)before S2 (Figure 6.20).
wait(synch) waits until P1 does signal(synch); so S2 runs after S1.In the ordering pattern it is no problem if the event occurs first. If P1 does signal first, the value becomes 1; when P2 then does wait, it passes without waiting. A semaphore stores the wakeup as a counter, and no signal is lost. This property is the most important difference that separates a semaphore from a condition variable.
The semaphore is a powerful but unstructured tool: correctness depends on writing every wait/signal pair correctly. Table 6.13 lists typical errors. A single forgotten line creates a bug that the compiler never warns about and that is rarely seen in testing.
| Code | Result |
|---|---|
signal(m) … CS … wait(m) | Reversed order: several processes enter the critical section. |
wait(m) … CS … wait(m) | The process waits for itself: it blocks permanently. |
wait or signal is forgotten | Exclusion breaks or deadlock occurs. |
| Two semaphores are taken in different orders | Deadlock. |
6.7.4Code trace: a barrier with semaphores
A synchronization barrier can be built with two semaphores and a counter. mutex protects the counter. turnstile starts at 0, that is, closed. The last thread to arrive opens the turnstile. Each thread that passes through the turnstile lets the one behind it through:
#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 */
}The following trace uses Tanenbaum's semaphore semantics: if someone is asleep, up wakes it without incrementing the value. Three threads A, B, and C arrive at the barrier in turn.
| Step | Event | mutex | turnstile | count | asleep at the turnstile |
|---|---|---|---|---|---|
| 1 | all three computing | 1 | 0 | 0 | – |
| 2 | A arrives, takes the mutex, count = 1 | 0 | 0 | 1 | – |
| 3 | 1 ≠ 3: A releases the mutex, sleeps at the turnstile | 1 | 0 | 1 | A |
| 4 | B arrives, count = 2, sleeps at the turnstile | 1 | 0 | 2 | A, B |
| 5 | C arrives, count = 3 = N | 0 | 0 | 3 | A, B |
| 6 | C up(&turnstile): A wakes | 0 | 0 | 3 | B |
| 7 | C releases the mutex, sleeps at the turnstile | 1 | 0 | 3 | B, C |
| 8 | A passes, wakes B with up | 1 | 0 | 3 | C |
| 9 | B passes, wakes C with up | 1 | 0 | 3 | – |
| 10 | C passes, up: no one waiting | 1 | 1 | 3 | – |
In step six C opens the turnstile but, because someone is waiting, the value does not increase; A is woken. C then sleeps at the turnstile right behind it (step 7), because it can pass through the turnstile only if someone lets it through. The turnstile works like a one-person revolving door: each one who passes lets the next one through. The last one through, C's up, finds no one and the value becomes 1.
count = 3, the turnstile is still 0.All interleavings of the three threads were explored with a program. In every execution the threads passed through the turnstile only after count = 3, and no execution deadlocked. This barrier is single-use: in the end the turnstile stays at 1 and the counter is 3. To reuse it in a loop the turnstile must be closed again. A reusable version needs two turnstiles; Downey's book works this version out in detail.
Thinking that the up(&turnstile) line after passing through the turnstile is unnecessary. The last arriving thread's up wakes only a single sleeper. If each thread that passes does not let the one behind it through, only one gets through the turnstile and the other two sleep forever.
6.8Classic problems
Synchronization tools are tested with a few classic problems that model many situations in real systems. When a new coordination mechanism is proposed, one looks at how cleanly it can solve these problems.
6.8.1The producer–consumer problem
Two processes share a fixed-size buffer (N slots). The producer writes items into the buffer and the consumer reads items from it. If the buffer is full the producer must wait, and if it is empty the consumer must wait. This arrangement is called a bounded buffer. If the buffer were unbounded, only the consumer would wait. The buffer is a circular array: in points to the slot the producer will write, out to the slot the consumer will read, and both advance with (i + 1) % N.
in has wrapped around: count = 8, the buffer is full and the producer must wait. (b) The consumer takes B and C: out = 3, count = 6.In the example the producer first puts A, B, and C into slots 0, 1, and 2; in = 3. The consumer takes A: out = 1, count = 2. The producer puts items D…I into slots 3–7 and 0; in wraps around to 1 and count = 8 = N. When the consumer takes B and C, out = 3 and count = 6, and the producer can write again.
6.8.2A fatal race: the lost wakeup
The first solution that comes to mind uses a shared count counter and the sleep and wakeup calls. sleep() blocks the caller; wakeup(p) makes the sleeping p ready. Tanenbaum's code is as follows:
#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 code looks innocent but contains a fatal race. In the following order both processes sleep forever:
- The buffer is empty. The consumer reads
count: 0. It is interrupted just as it is about to callsleep(). - The producer produces an item and puts it in the buffer;
countbecomes 1. - Because
count == 1, the producer assumes the consumer is asleep and sendswakeup(consumer). Since the consumer has not yet gone to sleep, the signal is lost. - The consumer continues. Following its old decision, it calls
sleep()and sleeps. - The producer fills the buffer; since the consumer is asleep, nobody reads. When
count == Nthe producer sleeps too.
The problem is that the test of count and the call to sleep are not indivisible. A wakeup that arrives in between is lost without a trace, since no one is asleep. A semaphore solves this problem: because it stores the wakeup as a counter, an up that comes first lets the following down pass without waiting (Tanenbaum MOS Figure 2-27).
6.8.3A bounded buffer with semaphores
The correct solution uses three 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);
}
}mutex = 1provides mutual exclusion on buffer access. Had it started at 0, no one could ever get in.empty = Ncounts the empty slots. When the buffer is full, the producer blocks atdown(&empty).full = 0counts the full slots. When the buffer is empty, the consumer blocks atdown(&full).
mutex does exclusion; empty and full do ordering (synchronization). The two jobs are done with separate semaphores.
N = 2 and the buffer is empty. The order is as follows: the consumer (C) tries to take an item; the producer (P) puts A and B; P tries for C; C takes an item; P puts C; C takes one more item. The semaphores have Tanenbaum's semantics: if someone is asleep, up wakes one and the value does not change.
| Event | mutex | empty | full | Buffer | Asleep |
|---|---|---|---|---|---|
| initial | 1 | 2 | 0 | – | – |
C: down(&full), full = 0 → sleeps | 1 | 2 | 0 | – | C |
P: puts A; up(&full) wakes C | 1 | 1 | 0 | A | – |
| P: puts B | 1 | 0 | 1 | A B | – |
P: down(&empty) for C → sleeps | 1 | 0 | 1 | A B | P |
C: takes A; up(&empty) wakes P | 1 | 0 | 1 | B | – |
| P: puts C | 1 | 0 | 2 | B C | – |
| C: takes B | 1 | 1 | 1 | C | – |
- The consumer runs first. Since
full = 0, it sleeps. There is no busy waiting. - A is put.
up(&full)wakes the sleeping consumer. Because the woken process uses this "1,"fullstays at 0. - B is put. The consumer has not run yet;
empty = 0andfull = 1. - No room for C. The producer sleeps; the buffer does not overflow.
- A is taken. The consumer's
up(&empty)wakes the sleeping producer;emptystays at 0. - Final state. C is put and B is taken. The buffer holds C:
mutex = 1,empty = 1,full = 1.
When no operation is in progress, empty + full = N always holds; in the middle of an operation the difference is the item "in transit."
All interleavings of a four-item scenario were explored with a program: the items were always taken in the order A, B, C, D, the buffer never overflowed, and there was no deadlock.
6.8.4If the order of down changes
The correctness of the solution depends on the order of the two down calls. What happens if the order is reversed in the producer?
void producer(void) {
while (true) {
item = produce_item();
down(&mutex); /* ← first */
down(&empty); /* ← then */
insert_item(item);
up(&mutex);
up(&full);
}
}- The buffer is completely full:
empty = 0. - The producer first takes
mutexand then sleeps atdown(&empty). It still holds the mutex. - The consumer passes
down(&full)but sleeps atdown(&mutex). Yet it was the one that would have doneup(&empty). - Everyone waits for the other: deadlock.
down. The producer holds the mutex and waits for empty; the consumer, having passed full, waits for the mutex.A state-space scan done with a program also finds a deadlocked state: mutex = 0, empty = 0, and two items in the buffer. The rule is this: wait first for the counting semaphore and then for the mutex; never sleep while holding the mutex. The order of the up calls, on the other hand, does not matter, because up never blocks.
6.8.5The readers–writers problem
Many processes share a database. Readers only read the data; writers modify it. Readers do not have to exclude one another: ten readers can read at the same time. But while a writer is writing, neither another writer nor a reader should be inside. Tanenbaum's solution uses two semaphores and a counter:
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();
}
}rc is the number of readers inside, and mutex protects it. db protects the database. A writer takes db directly. Of the readers, only the first to enter takes db (++rc == 1) and only the last to leave releases it (--rc == 0). The readers in between come and go without ever touching db.
The solution provides exclusion correctly. When all interleavings of two readers and a writer were explored, no state arose in which the writer and a reader were inside together; the two readers, however, could read together. But the solution has a serious weakness (Figure 6.24):
- R1 enters and takes
db. - A writer arrives and waits at
down(&db). - A new reader R2 enters without touching
db:rc = 2. - While R1 leaves, R3 arrives.
rcdrops to 1 and rises to 2 again; it never reaches 0. - As long as the stream of readers continues in overlapping fashion,
up(&db)is never called and the writer waits indefinitely.
rc never becomes 0 and the writer waits at down(db).This solution is reader-priority and is open to writer starvation. The variants of the problem choose different priorities (Table 6.16). In Downey's starvation-free solution everyone who arrives first passes through a turnstile. A waiting writer holds the turnstile, and no new reader can enter behind it:
/* 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();| Variant | Behavior |
|---|---|
| First readers–writers (reader priority) | A writer enters only when there are no readers; writers may starve. |
| Second readers–writers (writer priority) | If a writer is waiting, no new reader can enter; readers may starve. |
| Fair (turnstile) | Everyone who arrives first passes through the same turnstile; a waiting writer holds the turnstile. |
pthread_rwlock_t | glibc's default is reader priority; writer priority can be configured. |
Java ReentrantReadWriteLock | new ReentrantReadWriteLock(true) gives a fair, near-FIFO order. |
| Linux seqlock, RCU | Read-mostly kernel structures in which readers never take a lock. |
6.8.6The dining philosophers
Dijkstra posed the following problem in 1965. Five philosophers sit at a round table; there are five forks between them. Each philosopher thinks, and when hungry picks up the two forks on the right and the left and eats. The problem is a model of sharing limited resources among processes without deadlock and without starvation. The naive solution protects each fork with a semaphore:
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]);
}
}If all become hungry at the same moment and take their left fork, every philosopher waits for the right fork and no one releases: deadlock (Figure 6.25). Even though each fork is protected by a semaphore, the solution is wrong. When all interleavings of the five philosophers were explored, exactly this state was found: all five have passed the first wait and all fork semaphores are 0.
There are four ways to a solution:
- At most four at the table. A room semaphore starting at 4 lets at most four philosophers try to pick up forks at the same time. When five forks are distributed among four people, at least one reaches two forks and the circular wait is broken.
- Resource ordering (asymmetry). Each philosopher first takes the fork with the smaller number. P4's forks are 4 and 0; P4 asks for 0 first. The general rule: locks are always taken in the same global order.
- Taking both forks together. Tanenbaum's solution uses a state array and one semaphore per philosopher. A philosopher starts eating only if both neighbors are not eating.
- A monitor. Silberschatz's solution uses the procedures
pickup(i)andputdown(i)and one condition variable per philosopher (self[i]); its logic is the same as Tanenbaum's.
Tanenbaum's solution is below. Each philosopher's state can be THINKING, HUNGRY, or EATING. The s[i] semaphores start at 0; LEFT and RIGHT are the numbers of the neighbors.
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]);
}
}take_forks sets the state to HUNGRY and calls test(i). If the neighbors are not eating, test sets the state to EATING and gives the philosopher permission with up(&s[i]); the following down(&s[i]) passes at once. If one of the neighbors is eating, permission is not given and the philosopher sleeps at down(&s[i]). put_forks sets the state to THINKING and tests the two neighbors: if a waiting neighbor can now eat, it wakes it.
Initially everyone thinks (the state array is TTTTT; T is thinking, H hungry, E eating). P1, P2, and P3 become hungry in turn; then P1, followed by P3, finishes eating.
- P1 becomes hungry.
test(1): P0 and P2 are not eating → P1 becomesEATING,up(&s[1]);down(&s[1])passes at once. State: TETTT. - P2 becomes hungry. The left neighbor P1 is eating → the test fails; P2 sleeps at
down(&s[2]). State: TEHTT. - P3 becomes hungry. P2 is hungry but not eating, and P4 is thinking → P3 eats. State: TEHET. Two philosophers can eat at the same time.
- P1 puts down the forks.
test(0)andtest(2)are done.test(2)fails, because P3 on the right is still eating. State: TTHET. - P3 puts down the forks. This time
test(2)succeeds: P2 becomesEATINGandup(&s[2])wakes it. State: TTETT.
All interleavings of the five philosophers were explored with a program. In no execution was there a deadlock, two neighbors never ate together, and at most two philosophers ate at the same time. The number two is not random: each eating philosopher holds two forks, and two philosophers side by side cannot eat at the same time. At a table with n philosophers at most ⌊n/2⌋ can eat at once; for five it is 2, for seven 3.
Thinking that a deadlock-free solution is also starvation-free. In Tanenbaum's solution there is no deadlock. But if P1 and P3 keep taking turns eating, one of the two is always eating and P2's test never succeeds. P2 can in theory stay hungry forever. An additional rule is needed to prevent starvation: a ticket number, or raising priority with waiting time (aging).
6.9Monitors
The correctness of code written with semaphores depends on every wait/signal pair, and even swapping two down calls creates a deadlock. The monitor was developed to reduce this class of errors at the programming-language level.
6.9.1The monitor
A monitor is a language-level abstract data type that keeps the shared data, the procedures that operate on that data, and the initialization code together. Only one process can be active inside the monitor at a time (Hoare, 1974; Brinch Hansen, 1975).
monitor example
integer i;
condition c;
procedure producer(); … end;
procedure consumer(); … end;
end monitor;Processes can call the monitor's procedures but cannot access its internal data directly. Mutual exclusion is provided not by the programmer but by the compiler: the compiler adds the entry lock at the start and end of each procedure. The programmer cannot forget to take or release the lock. If the monitor is occupied, the calling process waits in an entry queue (Figure 6.27).
x and y have queues of their own.6.9.2Condition variables
Exclusion is not enough; a process inside the monitor sometimes has to wait for a condition to hold. For example, the consumer has found the buffer empty. If it waits while holding the monitor, the producer can never get in. Monitors therefore offer condition variables.
A condition variable is a wait queue used to wait for a condition to occur. x.wait() suspends the caller and releases the monitor. x.signal() resumes one process waiting on x (if any). broadcast or notifyAll wakes all the waiters.
- P is in the monitor; it cannot continue because the buffer is empty. Q is in the entry queue.
- P calls
x.wait(): it releases the monitor and sleeps in thexqueue. Q can thus enter. - Q makes the condition true and calls
x.signal(); a process wakes from thexqueue. Who runs immediately is a semantic choice. - When no one is in the
xqueue,x.signal()has no effect and leaves no trace.
x.wait() and sleeps in the x queue; Q goes in. (b) Q calls x.signal() and P wakes.The last step is the basic difference between a condition variable and a semaphore. A semaphore's signal increments the value and the following wait uses that increment; the signal is remembered. A condition variable has no value; it is only a queue. If no one is waiting, the signal is lost. So the awaited condition (for example count > 0) is always kept separately in the shared data and tested before waiting.
6.9.3Hoare and Mesa semantics
When Q wakes P with x.signal(), two processes in the monitor are ready to run. But only one can be active inside. Which one continues is determined by the monitor's semantics:
- Signal-and-wait (Hoare). The woken P runs at once; Q waits in an "urgent" queue. At the moment P wakes it is sure the condition is true: writing the wait with an
ifsuffices. - Signal-and-continue (Mesa, 1980). Q continues; P only becomes "ready" and waits to take the monitor again. Until P runs, another process may spoil the condition. When P wakes it must test the condition again.
signal P runs at once and the condition is true; Q waits in the urgent queue. (b) Mesa semantics: Q continues in the monitor; P is ready and, when it enters, must test whether the condition is still true.| Semantics | Who runs at once? | Used by |
|---|---|---|
| Signal-and-wait (Hoare) | The woken process | Textbook monitors |
| Signal-and-exit (Brinch Hansen) | The woken process; signal must be the last instruction of the procedure | Concurrent Pascal |
| Signal-and-continue (Mesa) | The signaler | Pthreads, Java, C#, Go sync.Cond, the Linux kernel |
Almost all real systems use Mesa semantics. Under Mesa semantics signal is only a "hint": the condition is perhaps true, and the woken thread tests it itself.
6.9.4Why while and not if?
Under Mesa semantics, writing the wait with an if is a bug:
/* 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 way the bug arises is as follows (Figure 6.30):
- The buffer is empty. Consumer C1 waits on the condition variable
full. - The producer puts an item, sets
count = 1, and callssignal. C1 wakes but must first reacquire the lock; it only becomes ready. - Meanwhile a newly arrived consumer C2 grabs the lock first (barging) and takes the item:
count = 0. - C1 finally gets the lock. If written with
if, it reads from the empty buffer without testing the condition again: a bug. - If written with
while, C1 tests the condition again, seescount == 0, and waits again.
if, reads from the empty buffer after C2 has taken the item. (b) With while, C1 tests the condition again and waits again.When all interleavings are explored with a model of a Mesa-style monitor, an execution that reads from an empty buffer is found in the version with if. There is no such execution in the version with while. POSIX also permits spurious wakeups: pthread_cond_wait may return even though no signal has arrived. So the while is mandatory in every case.
6.9.5A single condition variable is not enough
while is necessary but not sufficient. In the Arpaci-Dusseaus' example the buffer has a single slot; there are two consumers (C1, C2) and one producer (P). All use the same condition variable c:
/* 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);- The buffer is empty; C1 and C2 sleep on
c. - P puts an item and wakes C1 with
signal(c). - P tries again; since the buffer is full it too sleeps on
c. Now C2 and P are waiting onc. - C1 takes the item and does
signal(c). Which waiter will wake is not determined; this time C2 wakes. - C2 finds the buffer empty and sleeps again. C1 also sleeps in the next round. No one is left to wake the producer: the program stops.
c.The mistake is that the consumers and the producer wait in the same queue. A consumer should wake only the producer, and the producer only a consumer. The solution is two condition variables:
/* 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);In a scan with the model, in the version with a single condition a state is reachable in which all three threads sleep despite the while. There is no such state in the version with two conditions.
6.9.6signal and broadcast
Sometimes it cannot be known which waiter can make progress. In a memory allocator, threads ask for different amounts of memory:
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 and Tb wants 10; both sleep in the while loop. Tc frees 50 bytes. signal wakes only one. If that is Ta, since 50 < 100 it sleeps again; Tb keeps sleeping although it could have proceeded. broadcast, however, wakes everyone. Each tests its condition again: Tb takes its 10 bytes and avail becomes 40; Ta sees 40 < 100 and sleeps again.
signal wakes only Ta; Ta waits again and Tb's chance is wasted. (b) With broadcast Tb proceeds, and Ta has been woken for nothing.The rule is this: if it is not known which waiter can make progress, use pthread_cond_broadcast (notifyAll in Java). This pattern is called a covering condition. Its price is unnecessary wakeups. If the waiters can be divided into separate conditions, signal is cheaper. In both cases the wait is done inside a while.
6.9.7Producer–consumer with a monitor
The monitor Tanenbaum wrote in Pidgin Pascal solves the bounded buffer with two condition variables:
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;Access to count is already mutually excluded thanks to the monitor. If the buffer is full, the producer blocks with wait(full) and releases the monitor. When the consumer takes an item, count = N − 1 and signal(full) wakes the producer. What blocks the producer is wait; signal only wakes. Here if suffices, because Tanenbaum assumes Brinch Hansen semantics: signal is the last instruction of the procedure and the signaler leaves at once. In Pthreads or Java the same code must be written with while. There is also no lost wakeup: the test and the wait are done inside the same monitor, without interruption.
N = 2 and the buffer is empty. The consumer (C) first calls remove; the producer (P) then puts the items a, b, c, d in turn; C calls remove twice in between.
| Event | count | Buffer | In buffer | full | empty |
|---|---|---|---|---|---|
| initial | 0 | – | – | – | – |
C remove: count = 0 → wait(empty) | 0 | – | – | – | C |
P insert(a) | 1 | a | P | – | C |
count = 1 → signal(empty); P leaves, C continues | 1 | a | C | – | – |
| C takes a; 0 ≠ N − 1, no signal | 0 | – | – | – | – |
P insert(b); signal(empty) goes to waste | 1 | b | – | – | – |
P insert(c); the buffer is full | 2 | b c | – | – | – |
P insert(d): count = N → wait(full) | 2 | b c | – | P | – |
C takes b; count = 1 = N − 1 → signal(full) | 1 | c | P | – | – |
P returns from wait, puts d | 2 | c d | – | – | – |
When b is put, count = 1 and signal(empty) is called; but no one is waiting and the signal is lost. This loss is harmless, because had anyone been waiting it would have been woken anyway. In the end no data is lost and no process sleeps forever.
6.10POSIX and Java
Textbook monitors are a language feature and do not exist in C. In real programs the same structure is built by using a mutex and condition variables together. This section summarizes the tools in POSIX threads (Pthreads) and Java.
6.10.1Pthreads: mutexes and condition variables
| Mutex call | Purpose | Condition call | Purpose |
|---|---|---|---|
pthread_mutex_init | creates a mutex | pthread_cond_init | creates a condition variable |
pthread_mutex_destroy | destroys the mutex | pthread_cond_destroy | destroys the condition variable |
pthread_mutex_lock | acquires the lock or blocks | pthread_cond_wait | atomically releases the mutex and sleeps; reacquires it on return |
pthread_mutex_trylock | acquires, or returns EBUSY at once | pthread_cond_signal | wakes at least one of the waiters |
pthread_mutex_unlock | releases the lock (only its owner) | pthread_cond_broadcast | wakes all the waiters |
The rule: pthread_cond_wait is always called while holding the mutex and inside a while loop. Releasing the mutex and going to sleep atomically closes the window for the lost wakeup. For static initialization there are PTHREAD_MUTEX_INITIALIZER and PTHREAD_COND_INITIALIZER. The mutex types are NORMAL, ERRORCHECK, and RECURSIVE; priority inheritance is turned on with the PTHREAD_PRIO_INHERIT attribute. Additional interfaces include pthread_rwlock_*, pthread_spin_*, pthread_barrier_*, and C11's mtx_t/cnd_t types.
In the producer–consumer program that Tanenbaum and Bos wrote with Pthreads, the buffer is a single integer (0 means empty). The producer puts the values 1 and 2, and the consumer prints them:
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_waitatomically releases the mutex and sleeps. - The producer takes the mutex. Since the buffer is empty, it skips the loop and writes 1.
signalwakes the consumer; but the consumer cannot return without reacquiring the mutex (Mesa). - The producer may have won the race and taken the mutex again. For
i = 2it finds the buffer full, waits oncondp, and releases the mutex. - The consumer takes the mutex, tests the
whilecondition again (1 ≠ 0), prints 1, and empties the buffer. - The consumer signals
condp. The producer wakes, finds the buffer empty, and writes 2. In the second round the consumer prints 2.
All interleavings were explored with a Mesa-style model of the mutex and condition variable. In every execution the output was "1, 2" and none deadlocked. Even if the order changes, the output does not; what changes is only who sleeps when.
6.10.2POSIX 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");POSIX offers two kinds of semaphores. An unnamed semaphore is created as a variable with sem_init. If the second argument is 0, the semaphore is used among the threads of the same process. If it is 1, it is shared among processes; then the semaphore must reside in shared memory. A named semaphore is opened with a name using sem_open, and unrelated processes access it using the same name. sem_wait is the P operation and sem_post the V operation. sem_post can also be called safely from a signal handler. sem_trywait tries without waiting and sem_timedwait with a time limit; sem_getvalue gives the instantaneous value for information only.
macOS does not support unnamed semaphores; there sem_init is deprecated. A named semaphore or dispatch_semaphore is used. Java's counterpart is java.util.concurrent.Semaphore: acquire(), release(), and an optional fair mode.
6.10.3Java: synchronized, wait, and notify
In Java every object is a monitor: it has an intrinsic lock and a single wait set. A synchronized method or block takes this lock and releases it on exit, even if an exception is thrown. The lock is reentrant: its owner can acquire the same lock a second time. wait() releases the lock and sleeps; notify() wakes one of the waiters and notifyAll() all of them. The semantics are Mesa; the wait is done inside a while.
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 */
}The description of main in the slides was turned into a runnable program:
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;
}
public static void main(String[] a) throws InterruptedException {
OneSlot s = new OneSlot();
Thread p = new Thread(() -> {
try { for (int x = 10; x <= 40; x += 10) s.put(x); } catch (InterruptedException e) { }
});
p.start();
for (int k = 0; k < 4; k++) System.out.println("took " + s.take());
p.join();
}
}The program gave the same output on every run with JDK 21:
took 10
took 20
took 30
took 40The producer and the consumer share the same wait set. That is why notifyAll is safer than notify: notify may wake a waiter of the wrong kind, and the deadlock seen with a single condition variable can occur.
6.10.4Java: ReentrantLock and Condition
The java.util.concurrent.locks package offers a more flexible lock. Several Condition objects can be attached to one ReentrantLock. Producers and consumers can then wait in separate queues, and signal wakes the right group. The lock also offers tryLock(), timed and interruptible locking, and an optional fair mode. unlock() must always be called inside finally; otherwise an exception leaves the lock held forever.
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 */notFull and the consumer C2 waits on notEmpty; the lock's owner is C1.The class in the slides was completed with the take() method and run:
import java.util.concurrent.locks.*;
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(); }
}
int take() throws InterruptedException {
lock.lock();
try {
while (count == 0) notEmpty.await();
int x = buf[head]; head = (head + 1) % buf.length; count--;
notFull.signal();
return x;
} finally { lock.unlock(); }
}
public static void main(String[] a) throws InterruptedException {
Buffer b = new Buffer();
Thread p = new Thread(() -> {
try { for (int x = 1; x <= 5; x++) b.put(x); } catch (InterruptedException e) { }
});
p.start();
int sum = 0; StringBuilder sb = new StringBuilder();
for (int k = 0; k < 5; k++) { int x = b.take(); sum += x; sb.append(x).append(' '); }
p.join();
System.out.println(sb + "| sum = " + sum);
}
}All three runs with JDK 21 gave the same output:
1 2 3 4 5 | sum = 15
1 2 3 4 5 | sum = 15
1 2 3 4 5 | sum = 15With a two-slot buffer the producer can be at most two items ahead of the consumer; when the buffer is full it waits on notFull. The items are always taken in the order they were put. When the threads go to sleep varies from run to run; the output does not. A note on virtual threads: in Java 21, when a virtual thread blocked inside synchronized, it "pinned" the platform thread carrying it. For that reason ReentrantLock was recommended in that version. In JDK 24, JEP 491 fixed this problem.
6.11Liveness
Correct synchronization first ensures safety: the data is not corrupted. But the system must also make progress. This section covers the liveness problems that can arise even when exclusion is correct.
6.11.1Priority inversion
Under priority scheduling, a high-priority task runs the moment it is ready. Locks can break this rule in unexpected ways. Consider three tasks: high-priority H, medium-priority M, and low-priority L. H and L use a shared resource R; M has nothing to do with R. There is a single processor and times are in milliseconds.
- t = 0. L takes R's lock. Its critical section will take 4 ms in total.
- t = 2. H arrives and preempts L. At t = 3 it asks for R and blocks. A short wait is expected: when L finishes the remaining 2 ms, H will enter.
- t = 4. M arrives. M has higher priority than L; it preempts L and runs until t = 10. L runs again only at t = 10 and releases R at t = 11.
H has waited 8 ms for R; 6 ms of that is M's running. The highest-priority task waits for a medium-priority task that has nothing to do with it. As M gets longer, H's wait grows without bound.
Priority inversion is a high-priority task waiting for a lock held by a low-priority task. In the meantime, because of the medium-priority tasks that step in, the high-priority task indirectly waits for them too. Priority inheritance is the lock-holding task temporarily taking over the priority of the highest-priority task waiting for that lock.
Priority inversion is not a solution but a problem. With priority inheritance, while H waits for R, L temporarily takes H's priority. Even if M arrives, it cannot preempt L. L runs from t = 3 to t = 5, releases R, and returns to its old priority. H runs at once and waits only 2 ms (Figure 6.34). Another solution is the priority ceiling: the task that acquires the lock is immediately raised to the priority of the highest-priority task that can use that lock.
These two scenarios were rerun, unit by unit, with a small model of a preemptive priority single-processor scheduler. H's wait for the lock came out as 8 without inheritance and 2 units with inheritance. If H waits for the lock with a spinlock, the result on a single core is worse. When scheduling is strict-priority and preemptive, the highest-priority ready process always runs; H, spinning in a loop without blocking, is always ready. H never gives up the processor, the lower-priority L can never run and can never release the lock: the system locks up.
On a single CPU the priorities are H > M > L. L takes the lock at t = 0 and its critical section takes 4 units. H arrives at t = 1 and immediately asks for the same lock; once it gets the lock it runs for 2 units. M arrives at t = 2, runs for 5 units, and uses no lock. How many units does H wait for the lock, and when does it finish?
- No inheritance. L runs from 0 to 1. H blocks at t = 1. L continues from 1 to 2. M arrives at t = 2 and, preempting L, runs from 2 to 7. L finishes its remaining 2 units from 7 to 9 and releases the lock. H runs from 9 to 11. H waits 8 units, from 1 to 9, and finishes at t = 11.
- With inheritance. When H blocks at t = 1, L takes H's priority. Even though M arrives at t = 2, it cannot preempt L. L finishes its remaining 3 units from 1 to 4 and releases the lock. H runs from 4 to 6. H waits 3 units and finishes at t = 6; M runs from 6 to 11.
6.11.2Mars Pathfinder (1997)
The most famous example of priority inversion happened on Mars. In July 1997 the Pathfinder lander on the Martian surface, running under the VxWorks real-time operating system, reset itself again and again. A low-priority meteorological task held a mutex that protected the information bus. The high-priority bus-management task blocked on this mutex. Meanwhile the medium-priority, long-running communications task stepped in (Figure 6.35).
When the bus-management task could not run on time, a watchdog timer concluded "the system has hung" and did a full reset. JPL engineers reproduced the bug on the copy on the ground. The mutex's priority-inheritance option existed in VxWorks but was turned off; it was turned on with a small patch uploaded remotely, and the resets stopped. Today the same mechanism exists as the PTHREAD_PRIO_INHERIT attribute in POSIX and as priority-inheriting futexes and rt_mutex in Linux. The PREEMPT_RT real-time patch, which entered the mainline in Linux 6.12, also relies on this mechanism.
6.11.3Deadlock, livelock, and starvation
Three liveness problems are often confused (Figure 6.36):
- Deadlock: every member of a set of processes waits for a resource held by another member of the set. The processes are blocked and the processor may sit idle. It occurs when four necessary conditions hold at the same time.
- Livelock: the processes are not blocked; they react to one another and keep repeating the same steps, but none makes progress.
- Starvation: the system as a whole makes progress, but one process keeps giving way to others and never gets a turn.
The typical example of livelock is two "polite" threads. Each wants two locks. A thread that cannot get the second lock with trylock releases the one it holds and retries after always the same interval. If the two threads work in exactly the same rhythm, they give way to each other forever. The cure is to back off for a random (usually exponentially growing) time; this is the method used for Ethernet collisions. The cure for starvation is FIFO queues, fair locks, and aging.
6.12Introduction to lock-free structures
Every structure that uses locks has a weakness: if the thread holding the lock is preempted, waits for a page fault, or crashes, everyone stops. Lock-free structures use atomic instructions such as CAS directly instead of locks. Progress guarantees are defined at three levels:
| Kind | Guarantee |
|---|---|
| Blocking | If the thread holding the lock stops, everyone stops. |
| Lock-free | The system as a whole always makes progress; some threads may fail repeatedly. |
| Wait-free | Every thread finishes its own operation in a bounded number of steps. |
The simplest lock-free structure is the Treiber stack. The top of the stack is a single atomic pointer. push prepares the new node, links the node's next field to the current top, and tries to change the top with CAS:
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 */The stack is top → A → B. T1 wants to add X and T2 wants to add Y.
- T1 prepares. It reads
old = Aand setsX.next = A. It is interrupted at this point. - T2 adds.
CAS(top, A, Y)succeeds; the stack becomes top → Y → A → B. - T1's CAS fails.
topis now Y, not A. C11'scompare_exchangefunction writes the current value intooldon failure:old = Y. The loop setsX.next = Yand tries again. - The second CAS succeeds. The stack becomes top → X → Y → A → B.
No one held a lock. Even if T1 had stayed suspended forever after step 1, T2 could have finished its work.
push on the Treiber stack. (a) After T2's insertion, T1's CAS(top, A, X) fails; T1 sets old to Y. (b) The second attempt succeeds.The famous trap of lock-free programming is the ABA problem. CAS looks only at the equality of the value; it cannot know whether the value changed and changed back in between. In pop, let T1 read top = A and A.next = B and be interrupted. Meanwhile T2 pops A and B, frees B, and pushes A again. top is A once more. T1's CAS(top, A, B) succeeds and puts on top the node B, which is no longer on the stack and whose memory has been freed. The cure is to compare a version counter that increases with every change along with the pointer, or to delay freed nodes with safe memory reclamation (hazard pointers, epochs).
6.13Summary
- A race condition is when the result of processes accessing shared data depends on the order of execution. Even a single
count++is a read–modify–write sequence on the machine and can be interrupted in the middle. Such errors appear occasionally and are hard to catch with testing. - A critical section is code that accesses shared data. A solution must satisfy three requirements: mutual exclusion (safety), progress, and bounded waiting (liveness).
- Disabling interrupts does not work on multiple cores and is not open to users. A lock variable breaks exclusion and strict alternation breaks progress. Peterson's algorithm satisfies the three requirements for two processes using only reads and writes, but assumes sequentially consistent memory.
- On modern processors the store buffer and compiler reordering break Peterson. x86 (TSO) allows only the "write → later read" reordering. A memory barrier or sequentially consistent atomics (C11
_Atomic, Javavolatile) restore the right order; C'svolatiledoes not. - The hardware offers atomic instructions:
test_and_set/TSL, XCHG, and CAS. A simple atomic spinlock does not guarantee bounded waiting; awaiting[]array and cyclic hand-over provide it. The CAS loop is the basis of lock-free updates. - A spinlock busy-waits and is suitable on multiple cores for short critical sections. A mutex puts the waiter to sleep. On Linux, mutexes are built with the futex: if there is no contention, the kernel is not entered. A per-core counter scales by giving up a little accuracy.
- A semaphore is a counter used with
wait/signal. With an initial value of 1 it is the exclusion pattern, with N resource counting, with 0 ordering. A semaphore stores the wakeup; the signal is not lost. - The bounded buffer is solved with the semaphores
mutex,empty, andfull; if the order ofdownis reversed, deadlock occurs. The reader-priority readers–writers solution is open to writer starvation. The naive solution of the dining philosophers deadlocks; it is solved with a room semaphore, resource ordering, or a state array. - A monitor provides exclusion at the language level; a condition variable is a wait queue with no value. Real systems use Mesa semantics: the wait is always inside a
while, separate condition variables are used for separate groups, andbroadcastis used if it is not known which waiter will proceed. - In Pthreads
pthread_cond_waitatomically releases the mutex and sleeps. In Java every object is a monitor (synchronized,wait,notifyAll);ReentrantLockoffers severalConditionobjects. - Priority inversion is a high-priority task indirectly waiting for a medium-priority one; it is solved by priority inheritance or the ceiling (Mars Pathfinder). Deadlock, livelock, and starvation are different liveness problems.
- Lock-free structures work with a CAS loop and are not affected by the lock holder stopping; but they need a version counter or safe memory reclamation against the ABA problem.
| Tool | What it provides | When |
|---|---|---|
| Peterson, strict alternation | Exclusion with only reads/writes (assuming SC) | Conceptual; not used in real code |
| Memory barrier | Order and visibility of reads/writes | 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 a single variable | Counters, flags, reference counting |
| Spinlock | Exclusion without sleeping | Multicore, very short critical sections, inside the kernel |
| Mutex | Exclusion, the waiter sleeps | General-purpose critical sections |
| Semaphore | Counting, exclusion, and ordering | N identical resources, event notification |
| Monitor + condition variable | Structured exclusion + waiting on a condition | Complex conditions (Java, Pthreads) |
| Readers–writer lock | Many readers, one writer | Read-mostly data |
6.14Key terms
- synchronization
- race condition
- critical section
- mutual exclusion
- bounded waiting
- busy waiting
- Peterson's algorithm
- memory barrier
- atomic instruction
- spinlock
- mutex
- semaphore
- producer–consumer problem
- readers–writers problem
- dining philosophers problem
- monitor
- condition variable
- priority inversion
- priority inheritance
- deadlock
- livelock
- starvation
6.15Test Yourself
The shared
count = 10. T1 executescount = count + 3and T2 executescount = count − 1; each is three instructions: LOAD, ADD, STORE. What are all the possible final values?Answer
12, 13, and 9. If one finishes before the other reads, the result is 12. If T2's update is lost the result is 13, and if T1's is lost it is 9. All 20 interleavings give one of these three values.
If the line
flag[i] = falsein the exit section of Peterson's algorithm is forgotten, which of the three requirements is violated? What happens to P1 after P0 enters and leaves once and stays in its remainder section?Answer
Progress is violated.
flag[0]staystrueforever. When P1 wants to enter it writesturn = 0; its conditionflag[0] && turn == 0is true and P1 spins. While P0 sits in its remainder section, the only thing that can clear P1's way is P0's wanting to enter again and writingturn = 1. Although the critical section is empty, a process in its remainder section blocks the other.On a semaphore with initial value 3 (Silberschatz implementation, FIFO queue), P1–P5 do
waitin turn, followed by twosignalcalls. What are the value and the queue after the fivewaitcalls and after the twosignalcalls?Answer
After the five
waitcalls the value is 3 − 5 = −2; P1, P2, and P3 have passed, and P4 and P5 are in the queue. The firstsignalmakes the value −1 and wakes P4; the second makes it 0 and wakes P5. In the final state the value is 0 and the queue is empty.In the bounded-buffer solution with semaphores N = 3 and the consumer never runs. If the producer tries to put five items, how many items are put, what are
emptyandfull, and at which item does the producer sleep?Answer
Three items are put. Each time an item is put,
emptydecreases by one andfullincreases by one: at the endempty = 0andfull = 3. For the fourth itemdown(&empty)finds the value 0 and the producer sleeps. The buffer does not overflow.In the barrier code with semaphores, if the line
up(&turnstile)after passing the turnstile is deleted, how many threads pass the barrier when N = 3?Answer
Only one. The last arriving thread's
uplets a single thread through the turnstile. Because the one that passes does not let the one behind it through, the other two sleep at the turnstile forever. When all interleavings were explored, the number that passed in every deadlocked execution was 1.With
v = 0three threads each increment once with the CAS loop (increment). What is the final value? What are the minimum and maximum total numbers of CAS calls?Answer
The final value is always 3. At least 3 CASes are done: if each finishes before the others read, there is no failure at all. At most 3 + 2 + 1 = 6 CASes are done. If all three read the same value, one succeeds and two retry. In the next round again one succeeds and one fails.
On a single CPU H > M > L. L takes the lock at t = 0 and its critical section is 3 units. H arrives at t = 1 and immediately asks for the same lock; once it gets the lock it runs for 1 unit. M arrives at t = 2, runs for 4 units, and uses no lock. How many units does H wait, and when does it finish, without and with priority inheritance?
Answer
Without inheritance the schedule is L(0–1), L(1–2), M(2–6), L(6–7), H(7–8). H waits 6 units, from 1 to 7, and finishes at t = 8. With inheritance L runs with H's priority from 1 to 3 and releases the lock; H runs from 3 to 4. H waits 2 units and finishes at t = 4; M runs from 4 to 8.
On a two-core machine an approximate counter with threshold
S = 5is used. Core 0 callsadd()twelve times and core 1 seven times. What doesget()return at the end? What is the true value? What is the largest the difference can be in the worst case?Answer
Core 0 transfers 5 twice and 2 remain locally; core 1 transfers 5 once and 2 remain locally.
get()= G = 15 and the true value is 19. In the worst case the difference is 2 × (5 − 1) = 8.At a table with six philosophers, at most how many can eat at the same time? Does the naive solution (left fork first, then right) deadlock with six philosophers too?
Answer
⌊6/2⌋ = 3: for example P0, P2, and P4 can eat together. The naive solution deadlocks regardless of the number of philosophers: if all take their left fork, a circular wait forms.
In the store-buffer test T1 executes
x = 1; r1 = y;and T2 executesy = 1; r2 = x;. A full memory barrier is placed only in T1, between the write and the read. On x86 (TSO) canr1 = r2 = 0still be observed?Answer
Yes. T1's barrier only ensures that T1's own write is visible before its read. While T2's write
y = 1waits in the buffer, T2 can readxfrom memory as 0; T1 can also readyfrom memory as 0. When all executions are explored in the store-buffer model, (0, 0) still comes out. The barrier must be placed on both sides.
6.16Further reading
- R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, the chapters "Locks," "Condition Variables," "Semaphores," and "Common Concurrency Problems": explain how locks are built from hardware, the approximate counter, and the pitfalls of condition variables, with short, measured examples.
- A. B. Downey, The Little Book of Semaphores: solves dozens of problems with semaphores, from the barrier with a turnstile to the starvation-free readers–writers; before each solution it leaves room for the reader to try it alone. The book is free.
- A. Silberschatz, P. B. Galvin, and G. Gagne, Operating System Concepts (10th ed.), Chapters 6 and 7: treats the critical-section conditions, hardware support, and the tools in real systems in detail.
- B. Goetz et al., Java Concurrency in Practice: explains the Java memory model, the meaning of
volatile, and the correct use of thejava.util.concurrenttools, with practical examples.
6.17References
- 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.
- B. Goetz et al., Java Concurrency in Practice, Addison-Wesley, 2006; Java SE 21 API:
java.util.concurrent; JEP 491. - U. Drepper, "Futexes Are Tricky," Red Hat technical report, version 1.6, 2011 (first version 2004), akkadia.org/drepper/futex.pdf.
- M. Jones, “What really happened on Mars?”, 1997.
- M. M. Michael, M. L. Scott, "Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms," Proceedings of the 15th ACM Symposium on Principles of Distributed Computing (PODC '96), pp. 267–275, 1996, doi:10.1145/248052.248106.
- G. L. Peterson, "Myths About the Mutual Exclusion Problem," Information Processing Letters, 1981.
- POSIX.1-2017 (IEEE Std 1003.1):
pthread_mutex_lock,pthread_cond_wait,sem_overview(7); the Linuxfutex(2)manual page. - 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., Pearson, 2014 (5th ed. 2023) — §2.3 Interprocess Communication, §2.5 Classical IPC Problems.
Related pages: Chapter 6 slides · © Sercan Külcü. All rights reserved.