1. Threads and shared memory
A multi-threaded program is a set of executions, runs of the program, one per way of interleaving the threads' instructions. This section fixes what a thread, a shared memory and an interleaving are, and states the four assumptions under which the rest of the session reasons.
A thread is a sequence of instructions that the processor executes one after another. Each thread has its own program counter, the position of the instruction it executes next, and its own local variables, which live in a region of memory called the thread's stack (a different thing from the stack data structure of block 2). A program may have several threads, started one from another; the first is started when the program is. An instruction is one step that the processor executes as a whole. The instructions this block needs are three: a read of one memory location into a register, a small storage cell inside the processor that belongs to the running thread; a write of one register into one memory location; and an operation on registers, such as an addition. A line of source code is usually several instructions.
The shared memory is a set of locations, each holding one value, that every thread of the program can read and write by its address, the number that names the location. A field of an object and an element of an array are locations. A local variable of a Java or OCaml method is not, since no other thread can reach it, though an object it refers to may be shared by another thread that also holds a reference to it; in C and in Rust a thread may be given the address of another thread's local variable, which the first Rust program of section 5 attempts and the compiler rejects.
The scheduler is the part of the operating system and of the language's runtime that decides which thread runs on which processor. It may stop a thread between any two of its instructions, run other threads, and resume the stopped thread later, from the instruction where it was stopped. The program does not control when this happens. The scheduler has four parts: a queue of the threads ready to run; a policy that chooses which of them runs next; a timer interrupt that stops the running thread when its turn is up; and a context switch that saves the stopped thread's registers and program counter and loads those of the next thread.
Definition. An execution of a multi-threaded program is an interleaving of its threads' instructions: one sequence of the instructions that the threads execute, each thread's instructions in the order the thread issues them. The execution of a run that ends contains every instruction of every thread. The execution of a run in which a thread waits forever, as in the deadlock of section 6, contains only the instructions executed, and the execution of a run that never ends is an infinite sequence. Which interleaving a run follows is decided by the scheduler, not by the program.
An interleaving of two threads is a sequence of m + n positions, m of them filled by the first thread's instructions in their order and n by the second thread's in theirs; the interleavings differ only in which positions the second thread gets, so there are as many of them as there are ways to choose n positions among m + n. Two threads of three instructions each, the increment's three steps, have twenty interleavings. Two threads that each execute a loop of a million three-step increments, the program of section 2, have more than any test could run. The count is (m + n)! / (m! n!), the binomial coefficient “m + n choose n”; for the counter's two loops of 3·106 steps each it exceeds 101 800 000. A correctness argument therefore does not look at runs; it covers every interleaving at once, which is what the rest of this block does.
An interleaving as a row of six positions, each marked with the thread whose instruction it holds, and beside it as a braid: thread A in blue, thread B in orange, time running down, and at each crossing the strand in front is the thread whose instruction runs.
- The two threads, each with its three instructions in the order the thread issues them.
- One interleaving: A runs its three instructions, then B runs its three; the braid crosses three times with A in front, then three times with B in front.
- Another interleaving, A B A B B A: both threads read n before either writes it, and one update is lost. The braid shows the same order, crossing by crossing.
- An interleaving is fixed by the three positions of B among the six: 6 choose 3, that is, 20 interleavings.
Two threads as two lanes, time running to the right, and one shared memory between them; each step lights the part of the picture that one definition of this section names.
- The threads: each lane is one thread's instructions, in the order the thread executes them.
- An instruction: one box, one step that the processor executes as a whole, here A's read of n.
- A line of source code is several instructions:
n++is a read, an addition and a write, the three boxes lit on B's lane. - The shared memory, which both threads read and write; here the one location n.
- The scheduler: it stops A after A's first write, B runs meanwhile, and A resumes later from its next instruction. Read left to right, the boxes of both lanes form one sequence, the interleaving of this run.
The session reasons under four assumptions. They are a model for reasoning, not a description of the hardware: the fourth says when a language guarantees that the model holds.
- Several threads. The program has two or more threads, each a sequence of instructions as defined above.
- One shared memory. All threads read and write the same locations.
- A scheduler that may stop a thread between any two instructions. So an execution is an interleaving of the threads' instructions, and any interleaving may occur.
- Sequential consistency. There is one memory, and every read returns the value of the latest write to the same location before it in the interleaving. Together with assumption 3, an interleaving that keeps each thread's order, this is what Lamport (1979) calls sequential consistency.1 The language guarantees it for every program none of whose interleavings has a data race; the data race is defined in section 2. Why a language gives the guarantee only under that condition, and what holds instead for a program with a data race, is the subject of the last part of block 2.
The fourth assumption is stated as a guarantee of the language because it is one. On a modern machine each processor buffers its writes and reorders its memory accesses, and compilers reorder instructions; the picture of one memory that every instruction reads and writes in turn is not literally what the hardware does. Each language of this session states in its memory model that a program without data races behaves as if that picture were what the hardware does. The memory model is the part of a language's definition that says what a thread may see of another thread's writes. Java, OCaml 5 and Go state the guarantee for every program without data races; C, C++ and Rust state it provided the program's atomic accesses use the sequentially consistent ordering, which is C++'s default and which a Rust program names on each atomic operation. The programs of this session use that ordering. This block relies on the guarantee; block 2 explains it.
2. Race conditions
Two threads each add one to a shared integer a million times. The program is the smallest one in which the interleaving decides the result, and it gives the session its two central words: the data race and the atomicity violation.
In Java, new Thread(work) creates a thread that will run the code work, a Runnable, when it is started; t1.start() starts it; t1.join() makes the calling thread wait until t1 has finished. The main thread below starts two threads and waits for both before printing.
static int n = 0; // shared by the two threads
public static void main(String[] args) throws InterruptedException {
final int N = 1_000_000;
Runnable work = () -> { for (int i = 0; i < N; i++) n++; };
Thread t1 = new Thread(work), t2 = new Thread(work);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("expected " + 2 * N);
System.out.println("got " + n);
}
What does the program print as the value of n, with N increments per thread?
- Always 2N.
- At most 2N, and which number depends on the run.
- Possibly more than 2N.
- Always less than 2N.
Answer: B. The reasons are below, after the recorded run and the three steps of the increment.
expected 2000000
got 1017204
One sample. Ten further runs of the same program printed ten different numbers, all between 1,009,914 and 1,790,018, and none printed 2,000,000.
The statement n++ is one line of Java and several instructions of the machine. The Java compiler turns it into four instructions of the virtual machine, getstatic, iconst_1, iadd and putstatic, of which the first reads n and the last writes it; whatever machine code the runtime makes of them, the read and the write of n are two accesses, and the scheduler may run another thread between them. For the argument, the three steps that matter are these:
int v = n; // read
v = v + 1; // add
n = v; // write
The interleaving that loses an update is the one in which both threads read before either writes. The table shows it for one increment of each thread, starting from n equal to 5; "register" is the thread's own copy of the value.
| Step | Thread A | Thread B | n |
|---|---|---|---|
| 1 | read n, gets 5 | 5 | |
| 2 | read n, gets 5 | 5 | |
| 3 | add, register holds 6 | 5 | |
| 4 | write 6 | 6 | |
| 5 | add, register holds 6 | 6 | |
| 6 | write 6 | 6 |
Two increments were executed and n grew by one. This is a lost update: a write whose effect is overwritten by a write based on an older read. The recorded run lost close to a million of them.
Counted for one increment of each thread: the six steps r1 a1 w1 r2 a2 w2, read, add and write of each thread, can be put in 720 orders. Program order within each thread, r before a before w, leaves 20 of them, the interleavings of section 1. In 18 of the 20 each thread reads before the other writes, and an update is lost; only the 2 that run one increment entirely before the other count correctly.
The orders of one increment of each thread, written with r, a and w for the read, the addition and the write, and 1 and 2 for the thread.
- All 720 orders of the six steps, too many to read at this size; the 20 in ink keep r before a before w in each thread.
- The other 700 are dropped, and the 20 interleavings remain, from the one that runs thread 1 first to the one that runs thread 2 first.
- Struck out: the 18 in which each thread reads before the other writes, and an update is lost. Shaded: the 2 that run one increment after the other and count correctly.
Why each option is right or wrong, for any N of at least two. The arguments reason in the model of section 1, with one memory and every read returning the latest write. This program has data races, so Java does not guarantee the model for it; the arguments give what the model gives, and the recorded runs matched it.
- Option A is excluded: the interleaving of the table exists, so a run can print less than 2N; the recorded run did.
- Option B is right: first,
nnever exceeds the number of writes made so far. This holds before the first write, whennis 0. Suppose it holds up to the k-th write. That write stores a value that was read fromnat some earlier moment, plus one; at that moment at most k − 1 writes had happened, so the value read was at most k − 1, and the value written is at most k. So after the k-th write the claim still holds, and after all 2N writesnis at most 2N. Second, which number is printed depends on the run, because the scheduler chooses the interleaving: every interleaving in which no two increments overlap, that is, in which no read ofnfalls between another increment's read and its write, gives exactly 2N, and the one in the table loses one. - Option C is excluded: by the argument just given, more than 2N is impossible.
- Option D is excluded: an interleaving in which no two increments overlap gives 2N, and it occurs: twenty runs made while preparing this session, with a thousand increments per thread, printed the exact total three times: with so few increments, one thread sometimes finishes its loop before the other thread starts its own. A run that prints the right number proves nothing about the program.
The values the program can print, on a line from 0 to 2N, for N increments per thread.
- The line of the printed values.
- At most 2N: every write stores one more than a value read, so no run prints more than 2N.
- Exactly 2N is reached, by every interleaving in which no two increments overlap.
- At least 2, for every N of at least two: the interleaving of the table below prints 2, and every printed value lies between 2 and 2N.
The harder question is the smallest value the program can print in the model of section 1, sequential consistency, and the answer is 2, for every N of at least two: the interleaving of the table below prints 2, and the argument that follows excludes 1. The value 1 is excluded: the printed value is the one stored by the last write, which is one more than the value its thread read just before it. No write stores 0, since every write stores one more than a value read. The thread that makes the last write has at least two increments, so it wrote n once before its last read; that read therefore returns the value of some write, at least 1, and the last write stores at least 2.
| Step | Thread A | Thread B | n |
|---|---|---|---|
| 1 | reads 0, is stopped | 0 | |
| 2 | N − 1 complete increments | N − 1 | |
| 3 | writes 1 | 1 | |
| 4 | reads 1, is stopped | 1 | |
| 5 | its remaining N − 1 increments | N | |
| 6 | writes 2 | 2 |
Question 1 of the entry test is this program with three threads and 100,000 increments each, and its answer, any value from 2 to 300,000, follows the same argument.
OCaml 5 calls a unit of parallel execution a domain, several domains running at the same time on different cores; Domain.spawn work starts one running work, and Domain.join waits for it. The same program with two domains loses updates in the same way.
let n = ref 0
let work () =
for _ = 1 to 1_000_000 do
n := !n + 1
done
let () =
let a = Domain.spawn work and b = Domain.spawn work in
Domain.join a;
Domain.join b;
Printf.printf "expected %d\ngot %d\n" 2_000_000 !n
$ ./counter_racy
expected 2000000
got 1056147
One sample; ten further runs all lost updates.
Two words name what went wrong, and they name two different things. Both are needed, because later sections show them apart: a transfer that is an atomicity violation with no data race (section 6), and a flag read by one thread and written by another that is a data race with no multi-step operation at all (section 5). The definition of the data race names three devices of the program: the lock, defined in sections 3 and 4; a thread's start and join, described at the opening of this section; and the atomic, defined in section 3. Here it is enough to know that each of them orders one thread's instructions before another's.
Definition. A data race is two accesses to one memory location from two threads, at least one of them a write, with nothing of the program ordering one before the other. Four things of the program order them, and a data race has none: a lock released by the one thread and taken by the other between the two accesses; a start or join by which the one thread starts the other or waits for its end; an atomic written by the one thread and read by the other; a chain of such orders through other threads. Such two accesses can be adjacent in some interleaving, and that is the harm: one thread may read an old value, or its write may overwrite a result based on a value the other thread read earlier.
n by A and a read of n by B with nothing of the program between them on either lane: no lock, join or atomic orders one before the other, so the two accesses are a data race.To avoid the race, the two threads must coordinate: the program must put something between the two accesses that orders one before the other. The order that the program can impose is called synchronization. In this session synchronization comes from three sources, each of which block 1 meets. First, a lock's release is ordered before the acquire that follows it (sections 3 and 4). Second, the call of start by the thread that creates a new thread is ordered before the new thread's first instruction, and the new thread's last instruction is ordered before the return of the join that waits for it. Third, a write to an atomic variable (section 3) or a volatile variable (section 5) is ordered before the read that sees it. In Java every access to a volatile field provides such an order, and so do the methods get, set, getAndSet and compareAndSet of the atomic classes. The atomic classes also offer weaker access modes, such as getPlain, that provide no such order. In OCaml 5 every operation of the Atomic module provides such an order, and every one of them is sequentially consistent. In C, C++ and Rust an atomic access provides it only when its named ordering requires it, and the sequentially consistent ordering of section 1 does. In each case, the second thread, after its own ordering operation, sees whatever the first thread wrote before its ordering operation. The orders also chain: what is ordered before an operation of the second thread is ordered before what the second thread then orders before a third. The Java Language Specification calls this order happens-before. C++, Rust and OCaml define a data race with it: two accesses to one location, at least one a write and at least one not atomic, with neither ordered before the other by it. The specifications of Java and Go state their definitions in their own terms, and they classify the programs of this session the same way.2 The last part of block 2 shows why the fourth assumption's condition is about this order.
Two threads, each with a critical section between lock and unlock, the dotted block; each step draws the arrow of one mechanism of synchronization, from the instruction ordered first to the instruction ordered after.
- The two threads' instructions, with nothing yet ordering an instruction of one thread before an instruction of the other.
- A lock: A's unlock is ordered before B's lock that follows it, and with it everything A did before.
- A thread's start and join: A's start of B is ordered before B's first instruction, and B's last instruction before A's join of B.
- An atomic: A's atomic write of x is ordered before B's atomic read that sees it.
- The three together. Each orders one thread's instructions before the other's: what the first thread wrote before, the second sees after.
The word atomic has two senses. An instruction is atomic when the processor executes it as one step, so that no instruction of another thread falls inside it. The instructions of the model of section 1 are atomic by definition; an instruction of a real processor is atomic only when its definition says so: on x86, inc applied to a memory location is one instruction that reads the location and writes it, and another processor's write can fall between the two unless the instruction carries the lock prefix. An operation of several steps is logically atomic when it appears to take effect at one instant between its start and its end, so that every other thread sees all of it or none of it. A lock makes an operation logically atomic by exclusion (section 4); block 2 states this standard in full, as linearizability, and asks whether atomic instructions alone can give it.
Definition. An atomicity violation is an operation of several steps that the program meant as a unit and did not protect as a unit, so that another thread's step can fall between two of its steps.
The counter is both. The two threads' reads and writes of n are data races: nothing orders a read by one thread against a write by the other. And the increment is an atomicity violation: its three steps were meant as one and another thread's step can fall between them. Section 6 shows a transfer that is an atomicity violation and not a data race, because each of its accesses is under a lock; the two words come apart there. A transfer of 50 from an account x to an account y, both at 100, shows it in small: thread A subtracts 50 from x under x's lock, releases that lock, and only then adds 50 to y under y's lock; between the two steps thread B takes both locks, which are free, and reads 50 and 100, a sum of 150 where the invariant x + y = 200 requires 200, though every access of both threads is under a lock.
Thread A's increment, its three steps under a bracket that makes them one unit, and one step of thread B.
- A's read, addition and write are meant as one unit; B's write of n comes between A's read and A's addition.
- The atomicity violation: a step of another thread falls inside the unit.
- The data race: A's read of n and B's write of n, which nothing of the program orders one before the other. The counter has both.
The rest of the block follows from the two faults. Section 3 builds a lock from one atomic instruction, test-and-set. Section 4 states what the language's lock guarantees, what it requires of the program, and where a program that meets the requirement can still stop. Section 5 asks who checks the requirement: nobody by default, a static checker or a detector at run time, or Rust's compiler, for data races only. Section 6 takes two locks: a transfer that is not one unit and has no data race, then deadlock, and the order of the locks that removes it. The block ends on the question for block 2: whether a logically atomic operation can be built from atomic instructions, without exclusion.
3. Atomic instructions
A lock makes the increment's three steps one unit and orders the accesses: it fixes both faults of section 2 at once. A lock is itself shared state, though, and something must protect it. This section builds a lock from one instruction of the processor that reads and writes as one step, which shows what a lock is made of and gives the first example of synchronization.
The naive way to take a lock is to read a flag and, if it is false, write true: two steps on a shared location, with the counter's own fault between them, one level down. In the interleaving below, B reads the flag between A's read and A's write; both threads read false, both write true, and both are in the critical section at once. The lock protects the critical section, and nothing protects the lock.
false, both write true, and both threads are in the critical section. Taking the lock has the counter's own fault, one level down.A lock can be built from plain reads and writes alone, for two threads, by Peterson's algorithm (1981), under the one-memory model of section 1 and in Java only with volatile fields.3 It needs a fixed number of threads, and the locks of real languages use an atomic instruction instead. The naive lock fails; a lock does not need a special instruction in principle.
Definition. Test-and-set is an instruction that reads the old value of one memory location and writes a new value to it as one indivisible step: no instruction of any other thread falls between the read and the write.
Definition. A spin lock is a lock made of one flag, a boolean location, and a loop. To acquire it, a thread executes test-and-set on the flag, writing true, until the old value it returns is false; it then holds the lock. To release it, the thread writes false. A thread that finds the flag true repeats the instruction, which is called spinning.
Test-and-set gives two guarantees. The first is indivisibility: it reads the old value and writes the new one as one step, so no thread sees the location between the two. The second is synchronization: the write of false that releases the flag is ordered before the test-and-set that reads it, and with it everything the releasing thread did before; so what one thread did before releasing is ordered before what the next thread does after acquiring. The first guarantee makes the lock below exclusive; the second makes the plain variable inside it, one that is neither atomic nor volatile, race-free.
The two guarantees of test-and-set, the flag's value over time in the top row: indivisibility in the first two steps, synchronization in the third.
- A's call reads the flag and writes
trueas one indivisible step and returnsfalse: A holds the lock, and no instruction of B falls between the read and the write. - While A holds the flag, B's call reads
true, writestrueand returnstrue, and B spins, calling again until the flag isfalse. - A releases the lock by writing
false; B's next call reads thisfalseand returnsfalse, and B holds the lock. The write is ordered before that call, and with it everything A did before.
Java provides the instruction as AtomicBoolean.getAndSet(true), a method with the instruction's two guarantees, which the runtime carries out with the processor's own atomic instruction where the processor has one; it returns the old value and writes true in one step, and its read and write are synchronization, like those of a volatile field (section 5). OCaml 5 provides it as Atomic.exchange flag true, and its atomic operations are synchronization for the plain accesses before and after them.
With atomic accesses defined, the definition of a data race in section 2 takes one more clause: at least one of the two accesses is a plain access, that is, not atomic, so two accesses that are both atomic are never a data race, as block 2, section 2, states.
SpinLock.java, the lines shown on the slidestatic final AtomicBoolean held = new AtomicBoolean(false);
static void lock() { while (held.getAndSet(true)) { } } // loop until it was false
static void unlock() { held.set(false); }
Runnable work = () -> {
for (int i = 0; i < N; i++) { lock(); n++; unlock(); }
};
$ java SpinLock
expected 2000000
got 2000000
One sample. The field n is the plain int of section 2; only the two lines around n++ changed.
let flag = Atomic.make false
let lock () = while Atomic.exchange flag true do Domain.cpu_relax () done
let unlock () = Atomic.set flag false
let n = ref 0 (* read and written only between lock () and unlock () *)
let work () =
for _ = 1 to 1_000_000 do
lock ();
n := !n + 1;
unlock ()
done
$ ./spin_lock
expected 2000000
got 2000000
One sample; ten further runs printed the same. Domain.cpu_relax () only tells the processor that the loop is spinning and changes nothing in the logic.
The lock is the instruction with a loop around it, and the counter under it is exact, for two reasons that are the two guarantees. By indivisibility, between a getAndSet that returned false and the set(false) that follows it in the same thread, no other thread's getAndSet returns false: the flag is true throughout, and each test-and-set that runs meanwhile reads true and writes true. So at most one thread at a time is between its lock() and its unlock(), and the three steps of n++ are never interleaved with another thread's. By synchronization, the write of n by the thread that releases the flag is ordered before the read of n by the thread whose test-and-set next returns false; that order is exactly what the definition of a data race requires, so the accesses to n are not a data race, and the fourth assumption applies to the program: each read of n returns the latest write.
Two relatives of the instruction, in one line each. Fetch-and-add reads a location, adds a value to it, writes the sum and returns the old value, as one indivisible step. A ticket lock is made of two counters: an arriving thread takes a number from the first by fetch-and-add, then waits until the second counter, the number now being served, equals its number; a thread that releases the lock adds one to the second counter. So the threads enter in the order of their numbers, and no thread is passed by a later one; a thread still enters only when every earlier holder has released. Both return in block 2, where the instruction is used without the lock around it.
4. Locks
Every language of this session provides a lock. This section states what a lock guarantees, the contract, and what it requires of the program in return, the obligation.
Definition. A lock is an object with two operations, acquire and release, such that between an acquire that returned and the release that follows it in the same thread, no acquire by any other thread returns. A thread that has acquired a lock and not yet released it holds the lock; at most one thread holds a given lock at any moment. An acquire that cannot return yet keeps its thread waiting inside the call, and whether the waiting thread spins or sleeps is the implementation's choice; the locks of Java and OCaml put a thread to sleep when the wait is not short.
Definition. The critical section of a lock is the sequence of instructions a thread executes while holding it. Mutual exclusion is the property that at most one thread at a time is in a critical section of the same lock. One thread at a time inside: the interleaving is forbidden there.
In Java every object carries a lock, which Java calls the object's monitor (section 7 explains the word), and synchronized (lock) { … } acquires it at the opening brace and releases it at the closing one, also when the block ends by an exception. In OCaml 5 a lock is a value of type Mutex.t, and Mutex.protect m f acquires m, runs f and releases m, also when f raises.
static final Object lock = new Object();
static int n = 0; // guarded by lock
public static void main(String[] args) throws InterruptedException {
final int N = 1_000_000;
Runnable work = () -> {
for (int i = 0; i < N; i++) {
synchronized (lock) { // critical section: begin
n++;
} // critical section: end
}
};
Thread t1 = new Thread(work), t2 = new Thread(work);
t1.start(); t2.start();
t1.join(); t2.join();
System.out.println("expected " + 2 * N);
System.out.println("got " + n);
}
$ java CounterLocked
expected 2000000
got 2000000
One sample.
counter_locked.ml, the lines shown on the slidelet n = ref 0 (* read and written only while m is held *)
let m = Mutex.create ()
let work () =
for _ = 1 to 1_000_000 do
Mutex.protect m (fun () -> n := !n + 1) (* the critical section *)
done
$ ./counter_locked
expected 2000000
got 2000000
One sample; ten further runs printed the same.
The language's lock gives the same two guarantees as the spin lock of section 3, and the argument that the counter is exact is the same: mutual exclusion keeps the three steps of one increment together, and the release of the lock is ordered before the next acquire, so the writes to n made inside a critical section are seen by the thread that enters it next. In words, the picture: on each thread's lane the critical section is a marked stretch, and while one thread is inside its stretch the other thread stands at the start of its own and waits.
The difference from the spin lock is in how the other thread waits. A thread whose acquire cannot return is suspended by the runtime and the operating system until the release, and uses no processor time, where a spinning thread keeps a processor busy for nothing; waking it costs a switch of threads, which is why real locks spin briefly before they suspend. The lock is a construct of the language in Java, synchronized on the lock every object carries, and a module of the standard library in OCaml 5, Mutex; in both, the lock is released even when an exception leaves the critical section, where the hand-written unlock() of section 3 would be skipped.
The session presents three ways of dealing with the interleavings of a program: mutual exclusion, which forbids the interleaving with a lock and is the subject of this block; the atomic instruction with retry, which lets the interleaving happen, detects it and redoes the operation; and independence of the order, which arranges the work so that the result is the same in every interleaving. The last two are block 2. Each way is described by four things. Its contract is what the way guarantees when it is used correctly. Its obligation is what the program must establish for the contract to hold. Its progress risk is the way in which a correct program can still fail to go forward. Last, someone checks the obligation, or nobody does. The four terms are the rows of one table and the three ways its columns. For mutual exclusion, this section gives the contract, the first two parts of the obligation and the progress risk; section 5 gives who checks; section 6 gives the third part of the obligation and the deadlock; section 7 gives the fourth part. Block 2 fills the other two columns, and its last part sets the whole table side by side. Section 8 is the first column, filled. For mutual exclusion:
The contract. Operations are logically atomic by exclusion. Under the lock, operations happen one after another, and each appears to the other threads to happen at one instant inside its critical section. This is the coarse way to be logically atomic: no two operations overlap at all; the operations of block 2 overlap in time and must still each appear to take effect at one instant between their start and their end. Block 2 gives this property its name, linearizability, and its definition; the instant holds here by construction, provided the obligation is met, and what remains is that each operation, run alone, does what its specification says.
The obligation. It has four parts; two are stated here, the third comes in section 6 and the fourth in section 7. First, every access to the state the lock protects, every read and every write, is made while holding the lock. Second, the lock is held for the whole of an operation, over every piece of state that the operation's invariant mentions. An invariant is a statement about the shared state that is true whenever no thread is inside a critical section; an operation may make it false inside its section and must make it true again before releasing the lock. For the counter the invariant is that n equals the number of completed increments.
Increments under one lock, each a band on its thread's lane from acquire to release, and the instant at which it appears to happen as a dot.
- The contract: A's increment, then B's, each inside its band, each appearing to the other thread to happen at one instant.
- A breach of the obligation: B reads n outside any band, and nothing orders that read against the writes inside the bands.
- A second breach: A's next increment releases the lock before its last step, so its write of n falls outside its band.
The second part of the obligation has a breach of its own, the lock released before the last step: an increment whose critical section ends after its addition writes n outside the lock, and another thread's increment can then fall between its read and its write.
The progress risk. It has two sources. The first is a stopped holder: a thread that holds a lock and is stopped stops every thread that needs the lock. A cycle of waiting can stop it, and that is deadlock, section 6; the scheduler can stop it by not running it, and the result can be a missed deadline, as in the appendix on priority inversion; or it can stop for good. The second is starvation: a lock that keeps changing hands may never reach one particular thread; an order among the waiters removes it, and block 2's wait-freedom rules it out.
A suspended waiter looks better than a spinning one, and on the cost of waiting it is. On the progress risk it changes neither source.
| Spinning: the spin lock | Suspended: the language's lock | |
|---|---|---|
| A waiter costs | a busy processor, for as long as it waits | no processor time; waking it up costs a switch of threads |
| A stopped holder | the waiters spin as long as it is stopped; on one processor a spinner takes the time the holder needs to reach its release, and under strict priorities a higher-priority spinner keeps a lower-priority holder from ever running | the waiters leave the processor to the holder, and still wait as long as it is stopped, for ever if it is stopped by a cycle or for good |
| A lock changing hands | no order among the waiters: starvation is possible | a woken waiter competes with the threads arriving at that moment, and can lose again and again: starvation is possible |
Suspension saves processor time; it removes neither source of the risk. Only an order among the waiters removes starvation: a ticket lock, section 3, spins in turn, and a fair lock, such as Java's new ReentrantLock(true), suspends in turn and costs throughput.
Who checks the obligation is the subject of section 5. One consequence of the obligation can be stated now, and question 3 of the entry test asks it: a lock protects only against the threads that take it. A new lock created for each call of the increment, synchronized (new Object()) { n++; }, is held by one thread and never taken by any other, so it forbids nothing, and the program is section 2's; the lock that works is one lock shared by every thread that touches n. The obligation is then the programmer's discipline: the lock enforces none of it. Two other changes of the same question leave the count wrong as well. A volatile field orders each write before the read that sees it, but n++ on it is still a read, an addition and a write, and another thread's increment can fall between the read and the write. An atomic integer read with get and then written with set, n.set(n.get() + 1), makes each of the two calls atomic but not the pair, so another thread's set can fall between them and an update is lost, as in section 2. The same question's fourth change, a local count per thread that the main thread adds up after join, makes the count exact, by the third way of the session, independence of the order, which block 2 presents.
5. Race detection and prevention
The obligation of the lock is a rule about every access in the program. By default nothing verifies it; in Java a static checker verifies it at compile time when the rule is written as an annotation; in OCaml 5, Go, C and C++ a tool detects its violations in the runs that are made; in Rust the compiler verifies it, for data races only.
The program of this section and of section 6 is one program with two accounts. An account is an object with a name, an id (A has id 1, B has id 2), and a balance, a plain int field; each account's own lock is the one Java gives to every object, so synchronized (from) takes the lock of the account from. Both balances start at 100. A transfer takes an amount from one account and adds it to the other, and every transfer of the program moves an amount of 1; two threads, t1 and t2, transfer in opposite directions, a million times each. The program has four modes, chosen by a command-line argument, java Accounts a to d; this section shows mode d, which runs the transfer of mode c, the correct form of section 6 with both locks taken in a fixed order (section 6 says why), and adds a third thread that reads both balances and takes no lock.
// (c) both locks, in the order of the ids
static void transferC(Account from, Account to, int x) {
Account first = from.id < to.id ? from : to;
Account second = from.id < to.id ? to : from;
synchronized (first) {
synchronized (second) { from.balance -= x; to.balance += x; }
}
}
// (d) a reader that takes no lock
static int[] readUnlocked() {
return new int[] { A.balance, B.balance };
}
The reader takes no lock. Does the program compile, and what did the compiler establish about the reader's two reads?
- It does not compile: a balance is read outside its lock.
- It compiles, and the runtime reports the unlocked read when it happens.
- It compiles and runs, and the two reads are data races that nothing reports.
- It compiles, and the reads are correct because reading an
intis one instruction.
Answer: C. The compiler established nothing: a Java program records nowhere which lock protects which field.
transfers: 1000000 A to B, 1000000 B to A
readings with no lock during the transfers: 138670249, sums other than 200: 20954124
first wrong reading 114: A = -5811, B = 6012, sum = 201 (should be 200)
at the end: A = 100, B = 100, sum = 200
One sample. Ten further runs each saw between about eleven and twenty-three million sums other than 200, and the first wrong sum was 201 each time.
Why A and B are wrong is the table below: nothing in Java checks or reports an access outside its lock. Why D is wrong: reading an int is indeed one instruction, but that is not what the definition of a data race requires. Each of the reader's two reads is a data race by the definition of section 2: the transfers write the same location, and nothing of the program orders a read against those writes, since the reader holds no lock. The guarantee of the fourth assumption therefore does not apply to this program. Every wrong sum the run reported is of the kind an interleaving explains, the reader's first read falling before a transfer and its second after it. Java guarantees less: each racy read of an int returns some value that some write stored in it, neither half of a value nor a value no write stored (the Java specification, sections 17.7 and 17.4.8). Java does not guarantee that the two values belong to one interleaving; the last part of block 2 states what Java does guarantee. Nothing worse than the sums shown above appeared on this program, and nothing in the language reported the reads. The negative balance is no error of its own: thread t1 ran ahead of t2 for a while, and the transfers keep the sum.
The same program in OCaml 5 behaves the same way, and the standard compiler reports nothing either. In its listing, w is a record of what the calling domain holds and waits for, kept for the watchdog that detects the deadlock of section 6; lock w first takes the lock of first and notes it there.
(* (c) both locks, in the order of the ids *)
let transfer_ordered w src dst k =
let first, second = if src.id < dst.id then src, dst else dst, src in
lock w first; lock w second;
src.balance <- src.balance - k; dst.balance <- dst.balance + k;
unlock w second; unlock w first
(* (d) a reader that takes no lock *)
let read_unlocked () = (a.balance, b.balance)
$ ./accounts unlocked
2000000 transfers, A = 100, B = 100, sum 200
the reader: 109518919 readings, 2611258 with a sum other than 200
first wrong reading: A = 66, B = 133, sum 199
One sample.
The lab has a rules sheet, ten rules for threads in Java, each with a program that breaks it, a program that keeps it, and a line from a run of each. The rule this program breaks is the first: a lock protects data only if every access takes it. One access outside the rule is enough; the data is then shared with no protection at all, however careful the other accesses are. A write outside the lock is the same fault, and question 4 of the entry test shows it: a balance of 100, a deposit of 10 under a lock, read then write, and a reset to zero by a thread that takes no lock, can end at 0, at 10 or at 110, the last when the reset falls between the deposit's read and its write.
For one word, a variable that fits in one location such as an int or a boolean, that one thread writes and another reads, Java offers a repair short of a lock: a volatile field, whose every write is synchronization for the read that sees it. That makes a flag or a result visible across threads, and the plain flag of the rules sheet, rule 9, is the data race with no multi-step operation that section 2 announced.
static boolean stopPlain; static volatile boolean stopVolatile;
Thread t = new Thread(() -> { while (!stopPlain) { } }); t.setDaemon(true); t.start();
Thread.sleep(200); stopPlain = true; t.join(DEADLINE);
Thread u = new Thread(() -> { while (!stopVolatile) { } }); u.setDaemon(true); u.start();
Thread.sleep(200); stopVolatile = true; u.join(DEADLINE);
$ java Rules visibility
visibility broken the loop never saw the write: stuck at the deadline
visibility fixed the loop ended
One sample, the run recorded on the rules sheet.
The loop on the plain field may never end: no rule of Java requires the plain read of stopPlain to see the main thread's write, since nothing of the program orders the write before the read, so the compiler may read the field once and keep it in a register, and the loop then tests the same value for ever. Declared volatile, the field's write is ordered before the read that sees it, and the loop ends.
The repair holds only as long as no thread reads the word, computes from it and writes it back as one operation: n++ on a volatile field is the same three steps as before, and rule 3 of the rules sheet records the run in which it lost updates.
Who checks the obligation, by language:
| Language | Who checks that every access is under the lock |
|---|---|
| Java | Nobody by default. The program above compiles and runs with no warning, and a comment beside the field, // guarded by lock, records the rule. Written as the annotation @GuardedBy("lock"), the rule is read by Error Prone, a static checker, which reports every access made without the lock, at compile time. |
| OCaml 5; Go; C and C++ | Nobody by default; a detector at run time when the program is built and run with Go's -race flag or with ThreadSanitizer, a race detector that the C and C++ compilers clang and gcc include and that a compiler flag turns on. The detector reports two unordered accesses that the run made, even when the run's timing kept them apart and the answer was right, as far as its record of each location's recent accesses reaches; a path the run did not take is not checked. OCaml 5.2 and later can be built with ThreadSanitizer too; the standard compiler is not. |
| Rust | The compiler, before any run, for data races only. |
The Rust compiler rejects the counter of section 2. The program below says, in Rust's words, what the Java program said: a variable count that may change (let mut), two threads started with s.spawn, each running a function without a name (|| …) that adds one to count a million times, and a print of count at the end. The two threads are started inside thread::scope, which guarantees that both have ended before the scope returns; without it the compiler would also object that the threads might outlive the variable, and the one complaint left is about the sharing.
use std::thread;
fn main() {
let mut count = 0;
thread::scope(|s| {
s.spawn(|| for _ in 0..1_000_000 { count += 1 });
s.spawn(|| for _ in 0..1_000_000 { count += 1 });
});
println!("{}", count);
}
$ rustc --edition 2024 -O r1a_scoped_mut.rs
error[E0499]: cannot borrow `count` as mutable more than once at a time
--> r1a_scoped_mut.rs:7:17
|
6 | s.spawn(|| for _ in 0..1_000_000 { count += 1 });
| ------------------------------------------------
| | | |
| | | first borrow occurs due to use of `count` in closure
| | first mutable borrow occurs here
| argument requires that `count` is borrowed for `'1`
7 | s.spawn(|| for _ in 0..1_000_000 { count += 1 });
| ^^ ----- second borrow occurs due to use of `count` in closure
| |
| second mutable borrow occurs here
error: aborting due to 1 previous error
The compiler's output, recorded; there is no run. Two lines of the output that point into the standard library are left out.
The rule behind the compiler's rejection is ownership, and its intuition is enough for this session: every value has one owner at a time. A value may be shared by several threads, or changed by one thread, but not both at once; a lock or an atomic between the threads and the value lifts the restriction, as the next program shows. In the compiler's words, a borrow is a reference to a variable held by someone other than its owner, and a mutable borrow is one through which the holder may change the variable. Each of the two threads' functions borrows count mutably, since each changes it; two mutable borrows alive at the same time are two threads that can both change one variable, and the compiler rejects the second. Session 12 gives the rule.
The same counter compiles when the integer is put inside a lock, and the way Rust does it is the second thing to see. In the program, Mutex::new(0) is a lock that contains the integer 0, Arc::new wraps it so that several threads may share it, Arc::clone gives each thread its own handle, and c.lock() acquires the lock and returns a guard, a value through which the integer is reached and whose disappearance at the end of the statement releases the lock.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let count = Arc::new(Mutex::new(0));
let mut handles = Vec::new();
for _ in 0..2 {
let c = Arc::clone(&count);
handles.push(thread::spawn(move || {
for _ in 0..1_000_000 {
*c.lock().unwrap() += 1;
}
}));
}
for h in handles {
h.join().unwrap();
}
println!("{}", *count.lock().unwrap());
}
$ ./r1b_arc_mutex
2000000
One sample; three runs printed the same.
In Rust the lock owns the data: a Mutex<T> holds the T, and while the lock is shared between threads the only way to the T is the guard that lock() returns, which releases the lock when it goes out of scope. There is no way for a thread to reach the integer without holding its lock, so the first part of the obligation of section 4 cannot be broken. In Java, the lock and n of CounterLocked.java, section 4, are tied only by a comment, // guarded by lock: the compiler accepts n++ outside synchronized (lock). A Java class whose fields are private and whose every method is synchronized keeps other classes away from its fields, but inside the class the compiler still checks nothing. In Rust, as in the monitors of Brinch Hansen and Hoare (section 7), the data is reachable only under its lock; Rust states the rule in the types of a library, std::sync::Mutex, rather than in a construct of the language, and the compiler checks it. Rust checks the first part of the obligation, every access under its lock; the others remain the programmer's. The same compiler accepts a program in which each thread writes one slot of a shared array with no lock and no atomic, because the array can be split into disjoint mutable borrows, one slot per thread, and the compiler checks that they do not overlap and that the sum is read only after the threads have ended; that program is block 2's third way, and the compiler checks its obligation by the same rule.
What the Rust compiler does not check is as important as what it does. It does not check the order in which locks are taken: the deadlock of section 6 compiles in safe Rust. It does not check atomicity: the transfer in two halves of section 6 compiles in safe Rust and is wrong in the same way. A compiler can rule out a data race; an atomicity violation falls to the programmer.
6. Deadlock
Two accounts, each with a lock. A transfer between them shows that two atomic steps are not one atomic step; taking both locks shows deadlock, defined below; a fixed order of the locks removes it. Each account is a counter, a number that is increased and decreased, so that the session reasons about one number here and about a list, the stack, in block 2.
The two accounts A and B of section 5 start with 100 each, and each transfer moves 1 from one to the other. The invariant of the pair is that the sum of the balances is 200: a transfer moves money and creates none. Two threads transfer in opposite directions, and a third thread reads both balances under both locks and checks the sum.
Accounts.java, mode a, the lines shown on the slide// (a) each step under its lock, the transfer as a whole under none
static void transferA(Account from, Account to, int x) {
synchronized (from) { from.balance -= x; }
synchronized (to) { to.balance += x; }
}
// the reader: both balances, both locks
static int[] read() {
synchronized (A) { synchronized (B) { return new int[] { A.balance, B.balance }; } }
}
The withdrawal and the deposit are each under a lock. Is the transfer atomic, that is, does every other thread see either both of its steps or neither?
- Yes: each of its two steps is atomic, so the sequence of the two is.
- No: between the two steps, a thread that holds both locks can read the balances and find a sum of 199.
- No, and the reads of the balances are data races.
- Yes, provided the reader takes both locks.
Answer: B. Two atomic steps are not one atomic step.
reading 1: A = 99, B = 100, sum = 199 (should be 200)
after the transfers: A = 100, B = 100, sum = 200
One sample. The very first reading fell between a withdrawal from A and the deposit into B.
There is no data race in this program: every access to a balance is under that account's lock, which is why C is wrong. The reader does take both locks, and still sees 199, which is why D is wrong. The fault is the atomicity of the transfer. Its invariant spans two objects, and the operation released the lock of the first before taking the lock of the second; in the gap the money is nowhere, and any thread that looks sees it. This is the atomicity violation of section 2 without the data race: the two words have come apart. The second part of the obligation of section 4, restated for this case: hold every lock the invariant needs for the whole of the operation. Question 5 of the entry test has the same shape with one account: a check of the balance and a withdrawal, each atomic, let two threads both read 100 and both withdraw 100.
In OCaml 5 the same transfer, transfer_split, with the same reader, gave a first wrong reading of A = 234 and B = −35, sum 199, and wrong readings in every one of ten further runs.
The repair is to hold both locks for the whole transfer. The first attempt takes the source's lock first, then the destination's. The lines after the transfer are the deadlock detector that Java ships, ThreadMXBean.findDeadlockedThreads, which the main thread calls until it finds threads waiting for each other's locks in a cycle; it then prints which lock each of them holds and waits for.
// (b) both locks, the source's first
static void transferB(Account from, Account to, int x) {
synchronized (from) {
synchronized (to) { from.balance -= x; to.balance += x; }
}
}
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long[] ids;
while ((ids = bean.findDeadlockedThreads()) == null) Thread.sleep(50);
$ java Accounts b
deadlock: 2 threads blocked for ever
t1 holds account A, waits for account B, held by t2
t2 holds account B, waits for account A, held by t1
main ends; the two threads stay blocked until the JVM exits
One sample; the two threads deadlocked on the first run.
Definition. A deadlock is a state in which every thread of a set waits for a lock held by another thread of the set, so that none of them can ever proceed.
Nothing was corrupted: mutual exclusion holds, and every balance is right. Nothing will ever happen again: no transfer completes. To say which of these two statements is the failure, two kinds of property are needed, defined by Lamport (1977) and made exact by Alpern and Schneider (1985).4
Definition. A safety property says that something bad never happens; a violation of it is a finite run, one that reaches the bad state. A liveness property says that something good eventually happens; no finite run can show a violation, since the good thing may still come.
The deadlock violates both kinds, and the lecture says each time which of the two it means. That the two threads hold one lock each and wait for the other's is a state, and the detector finds it, which is why "never deadlocked" is a safety property. That no transfer will ever complete is the liveness property it ruins, and no detector can see "ever". The lock order below removes the state, and with it the failure of progress.
Coffman, Elphick and Shoshani (1971) list four conditions that are all necessary for a deadlock: mutual exclusion, each resource held by one thread at a time; hold and wait, a thread holding a resource while it waits for another; no preemption, that is, a held resource cannot be taken away from its holder; and circular wait, a cycle of threads each waiting for a resource the next holds.5 A lock provides the first by design, a nested critical section the second, and a lock cannot be taken from its holder. The condition this session removes is the fourth, by taking the locks in one order everywhere; the second can be removed by acquiring all the locks at once, and the third by a tryLock that gives back what it holds when it cannot get the rest.
The resource graph of the deadlock: threads as circles, locks as squares, a solid edge for holding a lock and a dashed arrow for waiting for one; each of the four conditions lit on the part of the graph that makes it true, and last the lock order, which breaks the cycle.
- The state the detector found: t1 holds A and waits for B, and t2 holds B and waits for A.
- Mutual exclusion: each lock has one holder.
- Hold and wait: t2 holds B while it waits for A.
- No preemption: A cannot be taken away from t1.
- Circular wait: the edges of holding and the arrows of waiting form a cycle.
- The lock order: both threads take A first, so t2 waits for A while holding nothing, t1 can take B, which is free, and no cycle can form.
// (c) the locks always taken in the order of the ids
static void transferC(Account from, Account to, int x) {
Account first = from.id < to.id ? from : to;
Account second = from.id < to.id ? to : from;
synchronized (first) {
synchronized (second) { from.balance -= x; to.balance += x; }
}
}
$ java Accounts c
transfers: 1000000 A to B, 1000000 B to A
readings during the transfers: 530369, sums other than 200: 0
at the end: A = 100, B = 100, sum = 200
One sample. The OCaml 5 version, transfer_ordered, read the sum 200 in every reading and ended in every one of ten further runs.
A global order of the locks: every thread that takes several locks takes them in the same order, here the order of the accounts' ids. Then no cycle can form. A thread waits only for a lock later in the order than every lock it holds, so along any chain of waiting threads the locks waited for come later and later; a chain whose locks only go up cannot return to its start. On three locks a, b and c in that order, a cycle would need a thread that holds c and waits for a, and under the order no thread waits for a lock earlier than one it holds. Question 7 of the entry test is three transfers around three accounts, each thread taking its source first: a cycle of three, which two threads alone cannot form, and which the one order removes. The order is the third part of the lock's obligation, after every access under the lock and every lock the invariant needs, and no compiler checks it: the deadlock compiles in Java, OCaml, Go and C, and in safe Rust. Tools find a violation only in a run that makes it. ThreadSanitizer reports two locks that a run of a C or C++ program took in opposite orders, even when that run did not deadlock; Java's findDeadlockedThreads, used above, finds a deadlock after it has occurred.
A lock makes a thread wait, spinning or suspended, for its turn. A consumer that finds a buffer empty must wait until the buffer holds an item, which no lock gives: waiting until a condition on the shared state holds is the subject of section 7, which the lecture leaves to reading and the lab's warm-up builds on. Progress lost with one lock and no cycle, Mars Pathfinder, is the appendix on priority inversion.
7. Condition synchronization
Not presented in the lecture: the appendix of the slides of block 1. The lab's warm-up builds on it, the bounded buffer and the barrier, where a group of threads waits until all of them have arrived, and it is read before them. A lock lets a thread wait for another thread to leave a critical section. A producer, a thread that makes items, and a consumer, a thread that uses them, share a buffer, a store of fixed size between them; a producer that finds the buffer full must wait for something else than a critical section, a change of the state, and the device for that is the monitor's condition variable, defined below. This section takes the oldest program of the field apart to show what is behind acquire and release, and ends on the one rule of waiting: a condition is checked again after every wake-up.
Definition. A semaphore (Dijkstra, 1965) is a counter with two operations, both indivisible: P, which waits until the counter is above zero and then decreases it by one, and V, which increases it by one.6 In the Part 2 introduction and in Java's library they are called acquire and release, the names of the lock's operations, because a semaphore whose counter is only ever 0 or 1 is a lock: P acquires it, V releases it.
Dijkstra's bounded buffer, from Cooperating sequential processes, is a producer and a consumer around a queue with room for N portions, and three semaphores: number of empty positions, starting at N; number of queuing portions, starting at 0; and buffer manipulation, starting at 1. The producer does P on the empty positions, P on buffer manipulation, adds its portion to the queue, V on buffer manipulation, V on the queuing portions. The consumer does P on the queuing portions, P on buffer manipulation, takes a portion from the queue, V on buffer manipulation, V on the empty positions. Taken apart, the program has two different things in it. The semaphore that starts at 1 is a lock around the queue: at most one process at a time is between its P and its V, which is section 4's mutual exclusion. The two semaphores that count are waiting devices: a P on a counter at zero makes the producer wait for a free place, or the consumer wait for a portion, until the other process's V raises the counter. So an implementation of acquire and release keeps a counter that a thread examines and changes without interference, and a queue of the threads waiting for it; the same two parts serve for exclusion, with a counter that is 0 or 1, and for waiting, with a counter that counts.
Definition. A monitor (Brinch Hansen, 1973; Hoare, 1974) is a module that packages some shared state, one lock that every operation on the state holds, and condition variables.7 A condition variable has two operations for a thread that holds the lock: wait, which releases the lock, sleeps until it is woken, and acquires the lock again before returning; and signal, called notify in Java, which wakes one thread waiting on it. A variant of signal wakes every waiting thread; Java calls it notifyAll.
The condition variable is a waiting device, not an exclusion device: a take sleeps until a put has signalled. The order of memory, that the take sees what the put wrote, comes from the lock that wait releases and takes again, as in section 4. In Java every object has a lock and one wait set, and Java calls the pair the object's monitor: a method declared synchronized holds the object's lock for its whole body, and wait() and notifyAll(), which may be called only by a thread holding the lock, are the object's one condition variable. In OCaml 5 a monitor is a record with a Mutex.t and as many values of type Condition.t as there are things to wait for, and Condition.wait c m releases m, sleeps and takes m again before it returns.
The monitor as three rooms: the entry set, where threads wait to acquire the lock; the owner, the one thread that holds it and works on the shared state; the wait set, where threads sleep in wait. The consumer C and the producer P share a buffer that starts empty.
- No thread holds the lock, and the buffer's count is 0.
- C has acquired the lock and is the owner; P, in the entry set, waits to acquire it.
- C finds the buffer empty and calls
wait: C moves to the wait set and releases the lock. - P acquires the lock and puts an item, which makes the count 1.
- P calls
notifyAll, which moves C from the wait set back to the entry set; P still holds the lock, so C must acquire it again beforewaitreturns. - P releases the lock; C acquires it, and its call of
waitreturns with the lock held.
The buffer below is a ring of K slots with a count of the items in it: put stores an item at the position tail and take removes the oldest, at head, both positions moving round the ring. A thread that finds the ring full, or empty, releases the lock and waits, and is woken by the next take, or put.
static final class WhileBuffer implements Buf {
final Integer[] slots = new Integer[K];
int head = 0, tail = 0, count = 0; // guarded by this
public synchronized void put(int x) throws InterruptedException {
while (count == K) wait(); // full: release the lock and sleep
slots[tail] = x; tail = (tail + 1) % K; count++;
notifyAll(); // wake every waiting thread
}
public synchronized Integer take() throws InterruptedException {
while (count == 0) wait(); // empty: release the lock and sleep
Integer x = slots[head]; slots[head] = null; head = (head + 1) % K; count--;
notifyAll();
return x;
}
}
$ java Buffer while
put: 200000 items, sum 10000100000
taken: sum 10000100000
One sample. The buffer has two slots; two producers put 100,000 items each and two consumers take 100,000 each, and the sum taken equals the sum put.
The invariant is that count items are in the ring, from head on; put and take keep it, and wait is called only while it holds, since the lock is released there.
The same buffer with if (count == 0) wait(); in place of the while, and likewise for put. With two producers and two consumers, what changes?
- Nothing: a consumer is woken only when an item has been put, so the condition holds when it wakes.
- A consumer woken by a put finds the buffer empty again, because the other consumer took the item first, and takes from an empty buffer.
- Both consumers wait for ever: a deadlock.
- A consumer takes the same item twice.
Answer: B. The recorded run below shows it on the sixth take.
c1 took from an empty buffer: got null, at its take 6 of 100000
c2 took from an empty buffer: got null, at its take 11 of 100000
put: 200000 items, sum 10000100000
taken: sum 25476
One sample; ten further runs all took from an empty buffer. Each consumer stops at its first null, so the sum taken counts only what came before.
The interleaving that does it, with one producer P and two consumers C1 and C2, the buffer empty:
| Step | Who | What | count |
|---|---|---|---|
| 1 | C1 | take: count is 0, waits, releasing the lock | 0 |
| 2 | C2 | take: count is 0, waits, releasing the lock | 0 |
| 3 | P | put: stores an item, count becomes 1, notifyAll wakes C1 and C2 | 1 |
| 4 | C1 | acquires the lock first, does not look again, takes the item | 0 |
| 5 | C2 | acquires the lock, does not look again, takes from an empty slot | −1 |
Why the other cards are wrong: A assumes that what was true at the signal is still true when the woken thread runs, and step 4 shows that it need not be. C does not happen, since every put wakes every waiting thread. D does not happen either, since a take removes the item it returns. With one producer and one consumer the if cannot fail this way. The only thread that could run between the signal and the consumer's wake-up is the producer, and a put only adds items: it cannot take the item the consumer was woken for. It can still fail, by a wake-up with no cause, defined below, which cannot be predicted. With two consumers the failure is the interleaving above, which can be predicted, and that is why the program has two of each. Question 10 of the entry test is this program as a queue, and its answer is the same take from an empty queue.
The reason is in the monitor itself, and the two kinds of monitor differ exactly here. Hoare's monitors (1974) hand the lock over to the woken thread at once, at the signal: the signalling thread stops, the woken thread runs next, and finds the condition as the signal left it, so it needs no second look. Mesa's monitors (Lampson and Redell, 1980) do not: the signalling thread keeps the lock and goes on, and the woken thread gets the lock back later, when it is free; between the wake-up and the return of wait another thread may take the lock and make the condition false again, so the condition is checked again, in a while.8 Java's and OCaml's condition waits are Mesa's: a woken thread takes the lock again later and checks its condition again. Java adds a second reason for the loop: wait may return with no notify at all, a spurious wake-up, which the language allows; OCaml's Condition.wait allows it too.
while, which also handles a wake-up with no signal at all.The sentence to keep: a condition is checked again after every wake-up, because another thread may have taken the slot first. Its companion is the choice of notifyAll over notify. A Java object has one wait set, so producers and consumers wait on the same condition variable, and notify may wake a thread of the wrong kind. notifyAll costs a few useless wake-ups instead: each woken thread tests its condition again, by the rule above, and goes back to waiting. A design with one condition variable per kind of waiter, as the OCaml program below has, may wake one thread, with the argument written down.
The same monitor in OCaml 5, with two condition variables, not_full and not_empty, and the wait in a while:
let put b x =
Mutex.protect b.m (fun () ->
while b.count = Array.length b.slots do Condition.wait b.not_full b.m done;
b.slots.((b.head + b.count) mod Array.length b.slots) <- Some x;
b.count <- b.count + 1;
Condition.broadcast b.not_empty)
let take b =
Mutex.protect b.m (fun () ->
while b.count = 0 do Condition.wait b.not_empty b.m done;
let x = Option.get b.slots.(b.head) in (* raises if the slot is empty *)
b.slots.(b.head) <- None;
b.head <- (b.head + 1) mod Array.length b.slots;
b.count <- b.count - 1;
Condition.broadcast b.not_full;
x)
$ ./buffer while; $ ./buffer if
4 slots, 2 producers and 2 consumers, 100000 items each
sum put 20000100000
sum taken 20000100000
consumer 1 took from an empty slot, after 8 items
(exit code 1)
One sample of each. The if version, with if in place of each while, failed in all of ten further runs.
8. Summary
Mutual exclusion in one table: what the lock guarantees, what it requires of the program, where a correct program can still stop, and who checks. Then the question block 2 answers.
| Mutual exclusion | Forbid the interleaving |
|---|---|
| The guarantee | Operations are logically atomic by exclusion: under the lock they happen one after another, and each appears to the other threads to happen at one instant inside its critical section. |
| The obligation | Every access to the protected state, read or write, under the lock; every lock the operation's invariant needs, held for the whole operation; one global order of the locks. Section 7 adds a fourth part for a thread that waits: every wait in a loop that checks its condition again. |
| The progress risk | A stopped holder stops every thread that needs its lock: deadlock when the holders wait in a cycle, a missed deadline when the holder is not scheduled. And starvation, when the lock keeps changing hands but one thread is passed over for ever. |
| Who checks | Nobody by default, in Java, OCaml 5, Go, C and C++; in Java a static checker, Error Prone, at compile time, for the fields annotated @GuardedBy; a detector at run time when the run is made with Go's -race or ThreadSanitizer, for the accesses that run made; the compiler, in Rust, for data races only, never for the lock order or for atomicity. |
The progress risk opens into four failures, each with its remedy. Deadlock: every thread of a set waits for a lock held by another thread of the set (section 6), removed by one global order of the locks. A missed deadline: the holder is ready to run and the scheduler does not run it, so a thread that needs its lock waits past its deadline (the appendix on priority inversion), removed by priority inheritance. Starvation: the lock keeps changing hands and one thread is passed over for ever (section 4), removed by an order among the waiters, a ticket lock or a fair lock. A lost wake-up: a notification reaches no thread that waits for it, because it came before the thread waited or woke a thread of the wrong kind, and the thread then sleeps for ever (section 7), removed by testing the condition and waiting under one lock, and by notifyAll or one condition variable per kind of waiter. The first two are a stopped holder; block 2's progress conditions remove that family at the root, since a thread stopped in mid-operation there holds nothing.
The counter has been exact twice, under the spin lock of section 3 and under the language's lock of section 4, both by exclusion: one thread at a time between the acquire and the release. The spin lock was built from one instruction that is itself atomic, test-and-set, and the question that block 2 opens on is whether the lock around it was needed at all. Block 2 first states what an operation must guarantee to the threads that call it at once, with a stack under one lock as the reference. Its first program without a lock is the counter written as a loop around compare-and-set, an atomic instruction: the loop reads n and retries until the instruction succeeds.
The question. Can a logically atomic operation be built from atomic instructions, without exclusion?
Block 2 answers in three steps: the standard of logical atomicity in full, linearizability and the progress conditions; compare-and-set with retry, the second way; and, in its last part, the condition of the fourth assumption of section 1, and what holds instead for a program with a data race.
Appendix. Priority inversion
Not presented in the lecture: the appendix of the slides of block 1, reached from the slide of the global order of the locks. Progress lost with one lock and no cycle.
One failure of progress happened without any cycle, on another planet, and it is the contrast to keep beside the deadlock of section 6.9 A spacecraft's software is a set of tasks, threads each with a priority, a number by which the scheduler chooses, among the tasks ready to run, the one with the highest. In July 1997, days after Mars Pathfinder landed, its computer began to reset itself, each reset stopping the day's work. The cause was a priority inversion. A high-priority task waited for a lock held by a low-priority task. Medium-priority tasks were ready to run, and the scheduler preferred them to the low-priority task, which therefore could not run and so could not release the lock. The lock was a mutual-exclusion semaphore, a lock in the sense of section 4 (section 7 defines the semaphore), inside a service of the operating system that both tasks used to pass data to each other. The lock did its job: one task at a time held it. What failed was progress: the high-priority task did not finish before a deadline that had to be met, the next cycle of the spacecraft's internal bus, and the system reset itself. It was not a deadlock: one lock, no cycle of tasks waiting for each other. It was an unbounded priority inversion: the task holding the lock was ready to run, and the scheduler kept choosing the medium-priority tasks. The remedy was priority inheritance: a task holding a lock runs at the priority of the highest task waiting for it. JPL turned it on for these semaphores by a patch sent from Earth. The problem was described by Lampson and Redell in 1980 for monitors; Sha, Rajkumar and Lehoczky gave the inheritance protocols and their analysis in 1990.10
Pathfinder as three rows, one per priority, time running to the right: a tinted block is a task running while it holds the lock, a dashed line a task blocked.
- The low task runs and takes the lock.
- The high task preempts it and blocks on the lock that the low task holds.
- The medium task runs, preferred by the scheduler to the low task, which is ready but not running and so cannot release the lock.
- The deadline passes while the high task is still blocked, and the system resets itself.
The link to two locks: inheritance alone does not prevent deadlock on two locks taken in opposite order; a fixed order does, on any machine, and on one processor so does the priority ceiling protocol of Sha, Rajkumar and Lehoczky (1990), a rule by which each lock has a ceiling, the highest priority of the tasks that use it, and a task may take a lock only if its priority is above the ceilings of all locks held by other tasks. The lesson Pathfinder adds to the deadlock of section 6 is that the progress risk of exclusion is wider than the cycle: a stopped holder stops everyone who needs its lock, whether it is stopped by a cycle, by the scheduler, or for good. The other source of the risk is starvation: a lock that keeps changing hands, no holder stopped, and one thread that waits for it for ever while others keep acquiring and releasing it; the ticket lock of section 3 is one answer to it.
The sources cited in this block, in the order of their first citation.
- L. Lamport, How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs, IEEE Transactions on Computers C-28(9), September 1979, 690–691. The definition of sequential consistency. Adve and Hill, Weak Ordering: A New Definition, ISCA 1990, 2–14, state the guarantee in its conditional form: sequential consistency for programs without data races.
- The Java Language Specification, chapter 17, section 17.4.5, happens-before order; C++, multi-threaded executions and data races; The Go Memory Model; The Rustonomicon, data races and race conditions; The OCaml Manual, Memory model: the hard bits. C++, Rust and OCaml define a data race as two conflicting accesses, at least one not atomic, that the program's synchronization does not order; Java and Go state their definitions in their own terms.
- G. L. Peterson, Myths About the Mutual Exclusion Problem, Information Processing Letters 12(3), June 1981, 115–116. The lock for two threads built from plain reads and writes alone.
- L. Lamport, Proving the Correctness of Multiprocess Programs, IEEE Transactions on Software Engineering SE-3(2), March 1977, 125–143, introduces the terms safety and liveness; B. Alpern and F. B. Schneider, Defining Liveness, Information Processing Letters 21(4), 1985, 181–185, give the definitions by finite and infinite runs used here.
- E. G. Coffman, M. J. Elphick and A. Shoshani, System Deadlocks, ACM Computing Surveys 3(2), June 1971, 67–78. The four necessary conditions; the paper's names are mutual exclusion, wait for, no preemption, circular wait.
- E. W. Dijkstra, Cooperating sequential processes, EWD 123, 1965, section 4.3, the bounded buffer; printed in F. Genuys (ed.), Programming Languages, Academic Press, 1968.
- P. Brinch Hansen, Operating System Principles, Prentice-Hall, 1973; C. A. R. Hoare, Monitors: An Operating System Structuring Concept, Communications of the ACM 17(10), October 1974, 549–557. The monitor, in the two standard references.
- B. W. Lampson and D. D. Redell, Experience with Processes and Monitors in Mesa, Communications of the ACM 23(2), February 1980, 105–117. The signal-and-continue monitor whose waiter rechecks its condition in a loop, and the first description of priority inversion (section 4).
- G. E. Reeves, What really happened on Mars?, e-mail of 15 December 1997 by the Mars Pathfinder flight software cognizant engineer, JPL; archived on M. Jones's page What really happened on Mars? (Internet Archive copy). The account of the reset, its cause and its fix; the reading "the lock did its job" is the course's.
- L. Sha, R. Rajkumar and J. P. Lehoczky, Priority Inheritance Protocols: An Approach to Real-Time Synchronization, IEEE Transactions on Computers 39(9), September 1990, 1175–1185. Priority inversion (section II, example 1), the inheritance protocol (section III), and the deadlock-freedom theorem of the ceiling protocol for one processor (section IV, theorem 10).
The programs of this block were run while the session was prepared, on 12 and 13 October 2026, and their full sources and the record of every run are kept with the course's material, in Java and in OCaml 5; the Rust programs and the compiler's output are from the same runs.
