Programming Paradigms Session 7 · Notes

← Session 7, Multi-Threading

Block 1: Mutual exclusion

Lecture notes of block 1, session 7. Every program on this page was run while the session was prepared and its output recorded; what is shown is one sample of a run, never a live one. The session's entry test, eleven questions on the course site, is referred to by its question numbers.

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.

thread Athread B read nadd 1write n read nadd 1write n one interleaving Aread n Aadd 1 Awrite n Bread n Badd 1 Bwrite n another interleaving Aread n Bread n Aadd 1 Badd 1 Bwrite n Awrite n AB read n add 1 write n read n add 1 write n time AB read n read n add 1 add 1 write n write n time 6 positions,choose 3 for B:20 interleavings

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.

  1. The two threads, each with its three instructions in the order the thread issues them.
  2. 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.
  3. 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.
  4. An interleaving is fixed by the three positions of B among the six: 6 choose 3, that is, 20 interleavings.
thread Athread B read nadd 1write nread nadd 1write n read nadd 1write nread nadd 1 shared memoryn A stopped here by the schedulerB runs meanwhile timetime

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.

  1. The threads: each lane is one thread's instructions, in the order the thread executes them.
  2. An instruction: one box, one step that the processor executes as a whole, here A's read of n.
  3. 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.
  4. The shared memory, which both threads read and write; here the one location n.
  5. 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.

  1. Several threads. The program has two or more threads, each a sequence of instructions as defined above.
  2. One shared memory. All threads read and write the same locations.
  3. 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.
  4. 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.

CounterRacy.java, the lines shown on the slide
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?

  1. Always 2N.
  2. At most 2N, and which number depends on the run.
  3. Possibly more than 2N.
  4. Always less than 2N.

Answer: B. The reasons are below, after the recorded run and the three steps of the increment.

$ java CounterRacy
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.

       
StepThread AThread Bn
1read n, gets 55
2read n, gets 55
3add, register holds 65
4write 66
5add, register holds 66
6write 66

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.

r1 a1 w1 r2 w2 a2r1 a1 w1 a2 r2 w2r1 a1 w1 a2 w2 r2r1 a1 w1 w2 r2 a2r1 a1 w1 w2 a2 r2r1 a1 r2 w1 w2 a2r1 a1 r2 w2 w1 a2r1 a1 r2 w2 a2 w1r1 a1 a2 w1 r2 w2r1 a1 a2 w1 w2 r2r1 a1 a2 r2 w1 w2r1 a1 a2 r2 w2 w1r1 a1 a2 w2 w1 r2r1 a1 a2 w2 r2 w1r1 a1 w2 w1 r2 a2r1 a1 w2 w1 a2 r2r1 a1 w2 r2 w1 a2r1 a1 w2 r2 a2 w1r1 a1 w2 a2 w1 r2r1 a1 w2 a2 r2 w1r1 w1 a1 r2 a2 w2r1 w1 a1 r2 w2 a2r1 w1 a1 a2 r2 w2r1 w1 a1 a2 w2 r2 r1 w1 a1 w2 r2 a2r1 w1 a1 w2 a2 r2r1 w1 r2 a1 a2 w2r1 w1 r2 a1 w2 a2r1 w1 r2 a2 a1 w2r1 w1 r2 a2 w2 a1r1 w1 r2 w2 a1 a2r1 w1 r2 w2 a2 a1r1 w1 a2 a1 r2 w2r1 w1 a2 a1 w2 r2r1 w1 a2 r2 a1 w2r1 w1 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 r2 a1 r1 w1w2 a2 r2 a1 w1 r1w2 a2 r2 w1 r1 a1w2 a2 r2 w1 a1 r1 r1 a1 w1 r2 a2 w2 r1 a1 r2 w1 a2 w2 r1 a1 r2 a2 w1 w2 r1 a1 r2 a2 w2 w1 r1 r2 a1 w1 a2 w2 r1 r2 a1 a2 w1 w2 r1 r2 a1 a2 w2 w1 r1 r2 a2 a1 w1 w2 r1 r2 a2 a1 w2 w1 r1 r2 a2 w2 a1 w1 r2 r1 a1 w1 a2 w2 r2 r1 a1 a2 w1 w2 r2 r1 a1 a2 w2 w1 r2 r1 a2 a1 w1 w2 r2 r1 a2 a1 w2 w1 r2 r1 a2 w2 a1 w1 r2 a2 r1 a1 w1 w2 r2 a2 r1 a1 w2 w1 r2 a2 r1 w2 a1 w1 r2 a2 w2 r1 a1 w1

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.

  1. 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.
  2. 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.
  3. 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, n never exceeds the number of writes made so far. This holds before the first write, when n is 0. Suppose it holds up to the k-th write. That write stores a value that was read from n at 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 writes n is 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 of n falls 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.
printed value 02N2N at most 2N exactly 2N at least 2

The values the program can print, on a line from 0 to 2N, for N increments per thread.

  1. The line of the printed values.
  2. At most 2N: every write stores one more than a value read, so no run prints more than 2N.
  3. Exactly 2N is reached, by every interleaving in which no two increments overlap.
  4. 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.

       
StepThread AThread Bn
1reads 0, is stopped0
2N − 1 complete incrementsN − 1
3writes 11
4reads 1, is stopped1
5its remaining N − 1 incrementsN
6writes 22

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.

counter_racy.ml, the lines shown on the slide
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.

thread A thread B read n add 1 write n read n add 1 write n shared memoryn time time data race: nothing orders them
A write of 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.

thread Athread B write nstart Bwrite x (atomic)lock···unlockjoin B read nread x (atomic)lock···unlock timetime releasebefore acquire start beforethe first steplast stepbefore the join atomic writebefore the readthat sees it

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.

  1. The two threads' instructions, with nothing yet ordering an instruction of one thread before an instruction of the other.
  2. A lock: A's unlock is ordered before B's lock that follows it, and with it everything A did before.
  3. 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.
  4. An atomic: A's atomic write of x is ordered before B's atomic read that sees it.
  5. 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 Athread B timetime one unit read nadd 1write n write n write na step falls inside the unit read ndata race

Thread A's increment, its three steps under a bracket that makes them one unit, and one step of thread B.

  1. 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.
  2. The atomicity violation: a step of another thread falls inside the unit.
  3. 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.

flag thread A thread B time time false true read flag reads false read flag reads false write true write true critical section critical section between A's read and write both inside
The naive lock: B reads the flag between A's read and A's write; both read 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.

flag thread Athread B timetime false true read flagwrite true returns false one indivisible step falsetrue write false read flagwrite true returns false ordered before,with everything A did before read flagwrite true returns true spins

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.

  1. A's call reads the flag and writes true as one indivisible step and returns false: A holds the lock, and no instruction of B falls between the read and the write.
  2. While A holds the flag, B's call reads true, writes true and returns true, and B spins, calling again until the flag is false.
  3. A releases the lock by writing false; B's next call reads this false and returns false, 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 slide
static 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.

spin_lock.ml, the lines shown on the slide
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.

CounterLocked.java, the lines shown on the slide
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 slide
let 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.

thread Athread Btimetimeshared memorynheld by Alockread nadd 1write nunlockcritical sectionwaits at the edgelock
The critical section as a band on A's lane, from its acquire to its release; B, which asked for the lock meanwhile, waits at the edge of its own until A releases, and the tag on the memory names the holder.

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.

thread Athread B timetime read nadd 1write n read nadd 1write n appears to happen at one instant read n access outside the lock read nadd 1 write n lock released before the last step

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.

  1. The contract: A's increment, then B's, each inside its band, each appearing to the other thread to happen at one instant.
  2. A breach of the obligation: B reads n outside any band, and nothing orders that read against the writes inside the bands.
  3. 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.

thread Athread Blockread nA stopped by the schedulerlockwaits as long as A is stoppedtimetime
A holds the lock and is stopped by the scheduler inside its critical section; B waits at the edge of its own for as long as A is stopped.
thread Athread Blockread nA stopped by the schedulerlockwaits as long as A is stoppedtimetimethread Atimethread Btimethread Ctimelockunlockheld by Alockunlockheld by Blockunlockheld by Alockunlockheld by Blockstarvation: C is passed over
No holder is stopped and the lock keeps changing hands between A and B; C, which asked for it first, is passed over every time: starvation.

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 lockSuspended: the language's lock
A waiter costsa busy processor, for as long as it waitsno processor time; waking it up costs a switch of threads
A stopped holderthe 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 runningthe 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 handsno order among the waiters: starvation is possiblea 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.

Accounts.java, mode d, the lines shown on the slide
// (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?

  1. It does not compile: a balance is read outside its lock.
  2. It compiles, and the runtime reports the unlocked read when it happens.
  3. It compiles and runs, and the two reads are data races that nothing reports.
  4. It compiles, and the reads are correct because reading an int is one instruction.

Answer: C. The compiler established nothing: a Java program records nowhere which lock protects which field.

$ java Accounts d
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.

accounts.ml, mode unlocked, the lines shown on the slide
(* (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.

Rules.java, rule 9, the lines of the flag
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:

 
LanguageWho checks that every access is under the lock
JavaNobody 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.
RustThe 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.

r1a_scoped_mut.rs
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.

r1b_arc_mutex.rs
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?

  1. Yes: each of its two steps is atomic, so the sequence of the two is.
  2. No: between the two steps, a thread that holds both locks can read the balances and find a sum of 199.
  3. No, and the reads of the balances are data races.
  4. Yes, provided the reader takes both locks.

Answer: B. Two atomic steps are not one atomic step.

$ java Accounts a
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.

transfer reader transfer of k from A to B: one unit under A's lock under B's lock under both locks A.balance −= k B.balance += k read both a step falls inside the unitthe sum is short by k time time
The transfer's two steps, each under its own lock, and the reader's step falling between them under both locks: the money is in neither account, and the reader finds the sum short. An atomicity violation with no data race, since every access is under a lock.

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.

Accounts.java, mode b, the lines shown on the slide
// (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.

holds t1t2AB threadlock holdswaits forwaits for one holderone holder cannot be taken away both take A first: no cycle

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.

  1. The state the detector found: t1 holds A and waits for B, and t2 holds B and waits for A.
  2. Mutual exclusion: each lock has one holder.
  3. Hold and wait: t2 holds B while it waits for A.
  4. No preemption: A cannot be taken away from t1.
  5. Circular wait: the edges of holding and the arrows of waiting form a cycle.
  6. 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.
Accounts.java, mode c, the lines shown on the slide
// (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.

monitor entry setthe ownerwait set slots count = 0 count = 1 acquire wait release notifyAll P C C P C C

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.

  1. No thread holds the lock, and the buffer's count is 0.
  2. C has acquired the lock and is the owner; P, in the entry set, waits to acquire it.
  3. C finds the buffer empty and calls wait: C moves to the wait set and releases the lock.
  4. P acquires the lock and puts an item, which makes the count 1.
  5. 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 before wait returns.
  6. P releases the lock; C acquires it, and its call of wait returns 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.

Buffer.java, the lines shown on the slide
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?

  1. Nothing: a consumer is woken only when an item has been put, so the condition holds when it wakes.
  2. 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.
  3. Both consumers wait for ever: a deadlock.
  4. A consumer takes the same item twice.

Answer: B. The recorded run below shows it on the sixth take.

$ java Buffer if
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:

      
StepWhoWhatcount
1C1take: count is 0, waits, releasing the lock0
2C2take: count is 0, waits, releasing the lock0
3Pput: stores an item, count becomes 1, notifyAll wakes C1 and C21
4C1acquires the lock first, does not look again, takes the item0
5C2acquires 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.

Hoare 1974signalerwaitertimewaitlocksignalstopswakestakelock handed over at once
Hoare's monitor: at the signal the lock passes to the woken thread at once, and it runs next, finding the condition as the signal left it.
Mesa 1980; Java, OCamlsignalerwaitertimewaitlocksignalanother threadcontinuesunlocktaketakes the slot firstwakeslocklock back laterchecks againwhilespurious wake-up: no signal
Mesa's monitor, the one of Java and OCaml: the signaller keeps the lock and goes on, the woken thread gets the lock back later, and another thread may take the slot in between; so the condition is checked again, in a 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:

buffer.ml, the lines shown on the slide
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 exclusionForbid the interleaving
The guaranteeOperations 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 obligationEvery 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 riskA 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 checksNobody 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.

thread A time fetch-and-add 1 one instruction, no lock shared memoryn
The increment of block 1 made atomic by a critical section, and the same increment as one instruction of the processor, fetch-and-add, with no lock around it; block 2 runs it beside the counter written with compare-and-set.

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

high priority task medium priority task low priority task time holds lock blocked on the lock held by low ready, not running deadline deadline missed: the system reset

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.

  1. The low task runs and takes the lock.
  2. The high task preempts it and blocks on the lock that the low task holds.
  3. The medium task runs, preferred by the scheduler to the low task, which is ready but not running and so cannot release the lock.
  4. The deadline passes while the high task is still blocked, and the system resets itself.
high priority task medium priority task low priority task holds lock blocked on the lock held by low holds lock inherits high's priority release ready, not running holds lock deadline time
The same rows with priority inheritance: the low task, holding the lock a higher task waits for, runs at that task's priority, releases, and the high task takes the lock and finishes before the deadline.

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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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).
  9. 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.
  10. 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.


Block 2: Atomics; independence of the order

Lecture notes of block 2, session 7.

The session names three ways to control the interleavings of a multi-threaded program. The first way, mutual exclusion, forbids the harmful interleavings with a lock; block 1 treated it. The second way, the atomic instruction with retry, lets the threads interleave, detects an interleaving in which another thread changed a value that a thread had read, and retries. The third way, independence of the order, arranges the work so that no interleaving can change the result. Block 1 ended on a question: can an operation be atomic without a lock around it? This block answers it in three steps. First it states the two standards that any answer must meet: what a client may require of the values that an operation returns when several threads call it at once, and what a client may require of the operation's progress. Then it gives the answer, the second way: one atomic instruction with a loop around it, on the counter and then on a stack, with the proof that the stack meets the standards. Then it takes the third way, where the work is arranged so that its result does not depend on the order. It ends with the fourth assumption that block 1 made about memory: it is a guarantee, and section 7 says who gives it and what a program gets when it breaks the guarantee's condition.

The programs on this page are the session's running examples; each shows the lines of its slide, together with the declarations and other lines that a run of the program needs. Java is the language of the lab. OCaml 5 is the lecture's second language: each OCaml program follows the Java program that does the same, and the comments in both explain the lines. In OCaml 5 a domain is the unit of parallel execution: each domain runs on an operating-system thread of its own, so several domains run in parallel on several cores, whereas the threads of OCaml's Thread library within one domain take turns. Domain.spawn starts a domain and Domain.join waits for it and returns its result, as start and join do in Java. A core is one of the processor's units that each run one thread at a time.

1. Linearizability and progress

An operation without a lock needs its standard stated before it is built: what it has to achieve. The locked stack of block 1 is the reference: it is correct, and block 1 showed why: every push and pop holds the stack's one lock for its whole body. A client of a data structure is the code that calls its operations, here the threads that push and pop. The question of this section is what exactly the lock gives a client, so that a version without the lock can be held to the same standard.

The locked stack, the reference

Example 7a, Java: LockedStack.java, the lines the slide shows

record Node(int value, Node next) { }   // a record: its fields are final, set once

Node top = null;                     // guarded by this stack's lock

synchronized void push(int x) {      // one thread at a time
  top = new Node(x, top);
}
synchronized Integer pop() {         // null when the stack is empty
  if (top == null) return null;
  Node old = top;
  top = old.next();
  return old.value();
}
$ java LockedStack
one lock: pushed sum 125000500000, popped 62500849627 + remaining 62499650373 = 125000500000

Example 7a, OCaml 5: locked_stack.ml

(* items is read and written only while m is held. *)
type 'a stack = { mutable items : 'a list; m : Mutex.t }

let push s x = Mutex.protect s.m (fun () -> s.items <- x :: s.items)

let pop s =
  Mutex.protect s.m (fun () ->
    match s.items with
    | [] -> None
    | x :: rest -> s.items <- rest; Some x)
$ ./locked_stack
pushes and pops, 4 domains, one lock
  sum pushed          125000500000
  sum popped + left   125000500000

Four threads each push the numbers from 1 to 250,000 and pop after every second push; at the end, what was popped and what remains on the stack add up to what was pushed. This output is one sample, one run on one machine; ten more runs gave equal sums each time. The sums agree, which is what a stack that loses no push and pops nothing twice must give; the check catches a lost or doubled value unless two such mistakes cancel, and one run proves nothing in general. The run does not yet say what a client of this stack may rely on in general; saying it takes the definitions that follow. In what follows, a word is one location of memory that the processor reads or writes in one indivisible step; an int fits in a word, and so does a reference, the address of an object in memory.

Histories and linearizability

A concurrent object is a data structure, here a stack, with operations that several threads may call at the same time. A history of an object is the record of one run as seen from outside: for each operation, the thread that called it, which operation it is with its arguments, the instant at which the thread called it, the instant at which the call returned, and the value returned. Two operations overlap in a history when each is called before the other has returned. The sequential specification of the object says what each operation does when operations run one at a time, one after another: for a stack, a pop returns the value of the most recent push among those not yet popped, and returns null when every push has been popped. A sequential run of the specification is a sequence of operations applied one after another, each returning what the specification says it returns. For the stack, the specification run in this way is the sequential stack.

A history where no two operations overlap is checked against the sequential specification directly: the check applies the operations to the specification in the order of their calls and compares the values the specification returns with the values in the history. A history with overlapping operations has no single order of its operations, and that is the difficulty: two pushes that overlap could have gone onto the stack in either order, and a later pop will show which. Herlihy and Wing gave the standard that resolves this difficulty.1

Linearizability. A history is linearizable when its operations can be given instants that meet two conditions. First, each operation receives one instant between its call and its return, its point of effect (the field's word is linearization point), and no two operations receive the same instant. Second, the operations, taken in the order of these instants, form a sequential run of the specification in which each operation returns the value it returned in the history. The history then counts as explained by the sequential specification, for the stack by the sequential stack. An object is linearizable when every history it can produce is linearizable. Informally: each operation appears to the other threads to take effect at one instant between its call and its return. The points of effect are the prover's choice; the history, with its calls, returns and values, is what the run gave. A history may end with an operation that was called and has not returned: a push, for instance, by a thread that the scheduler stopped in the middle of it. To show that such a history is linearizable, the explanation either gives that operation a return value and a point of effect, or leaves it out of the history, whichever makes the history linearizable.

thread A thread B push(1) pop() → 2 push(2) pop() → 1 1 2 1 1 empty the sequential stack, in the order of the ticks the points of effect: one instant inside each bar, chosen so that the sequential stack returns what the history did

A history of two threads, each operation a bar from its call to its return.

  1. The history: thread A pushes 1, then pops and gets 2; thread B pushes 2, then pops and gets 1. The two pushes overlap, and so do the two pops.
  2. The points of effect, one instant inside each bar, as ticks, chosen so that the sequential stack run in their order returns what the history returned: push 1, push 2, pop giving 2, pop giving 1. Above each tick, the stack after it.

The history of the figure, with the two pops returning the other way round: thread A's pop returns 1 and thread B's returns 2. Can this history be explained by a stack?

  1. No: thread A's push was called first, so 1 is below 2 and the first pop must return 2.
  2. Yes: the two pushes overlap, so their points of effect may be placed in either order, and with push(2) before push(1) the pops return 1 then 2.
  3. No: a history with overlapping operations is never explained by a sequential specification.
The answer

The second answer. The call to push(1) comes first, but push(1) has not returned when push(2) is called, so nothing a client can observe says which took effect first. Place push(2)'s tick before push(1)'s, both inside their bars: the sequential stack then holds 2 below 1, the pop that comes first returns 1, the other returns 2. The locked stack itself can produce this history: thread B may take the lock before thread A although A called first. A history that cannot be explained is one where both pops return 2, or where a pop returns a value never pushed: no placement of the ticks makes a sequential stack do that. Two operations that do not overlap keep their order: the one that returned before the other was called has the earlier point of effect.

The locked stack is linearizable by construction. Under the lock the operations happen one after another; each holds the lock for its whole body, and so any instant inside its critical section serves as its point of effect. This holds provided block 1's obligation is met: every access to the stack's state is under the lock. A structure with one lock for the whole of it is called coarse-grained; the locked stack is the coarse-grained stack. Every observation that a client makes of the values returned by a linearizable stack, calling push and pop, is one that the coarse-grained stack could also give: each history of the linearizable stack is explained by a run of the sequential stack, and the coarse-grained stack produces that same history when each operation holds the lock at its point of effect. In that sense the coarse-grained stack is the interface of every linearizable stack: as far as the returned values go, a client observes nothing in a linearizable stack that the coarse-grained stack cannot also show. A client can still tell the coarse-grained stack from another by progress, which the progress conditions below make precise. The locked stack is the reference: a stack built without a lock meets the same standard for its values exactly when every history it can produce is explained by the sequential stack, as every history of the locked stack is. Whether its operations return is the separate standard of progress, next.

Progress conditions

Linearizability says what the values are. It says nothing about whether an operation ever returns. Block 1 defined safety and liveness. A safety property says that something bad never happens: every run that violates it has a finite beginning in which the violation has already happened. A liveness property says that something good eventually happens: no finite beginning of a run can show its violation. Linearizability is a safety property: a history that cannot be explained shows it in finitely many operations. The conditions on progress are liveness properties. Each contains the clause "whichever threads are stopped", and without that clause a condition would not be about progress at all.

A step is one instruction of a thread. In a run, some threads may be stopped at some point and never run again, by the scheduler or for any other reason; the others keep taking steps. A structure is blocking when a thread's progress in an operation can depend on another thread's being scheduled: a lock is blocking, since a thread that holds the lock and is stopped stops every thread that waits for that lock. A structure is non-blocking when no thread's progress depends on another thread's being scheduled.

Lock-free: in every run, from any point on, as long as at least one thread keeps taking steps inside an operation on the structure, some operation completes within finitely many further steps, whichever threads are stopped and whenever. Every lock-free structure is non-blocking. The slide draws blocking and lock-free on three threads, A stopped for good at a cross: under a lock, B and C wait for A's lock for ever; lock-free, B keeps completing while each of B's successes fails C's attempt, and C starves. The definitions are Herlihy's; the clause on stopped threads is the form Herlihy and Shavit gave them.2,3,25

thread A thread B thread C stopped, never scheduled again an operation returns holds the lock waits for the lock waits for the lock
Blocking: thread A holds the lock and is stopped for good at the cross; B and C wait for the lock for ever, and no operation returns.
thread A thread B thread C stopped, never scheduled again an operation returns an attempt fails
Lock-free: thread A is stopped for good at the cross; B keeps completing, and each of B's successes fails C's attempt, the dashes, so C starves.

The appendix sets out wait-freedom, the clause on stopped threads, and how the way a structure is built differs from the progress it guarantees.

Where block 1's way stands against these standards: a lock-based operation is linearizable by construction, and its progress is blocking. What this section leaves open is block 1's closing question, now sharpened: can an operation be linearizable and non-blocking? The next section gives one, on the counter.

2. Compare-and-set

Block 1 built a lock from one instruction, test-and-set, and put the counter's three steps, read, add, write, inside it. The second way removes the lock. In its place it uses one instruction of the same kind as test-and-set but stronger, compare-and-set, and lets the three steps run with no protection but a check at the end.

Compare-and-set (CAS in the figures) is a read-modify-write instruction on one memory location: it takes two values, the expected value and the new value. In one indivisible step it reads the location and, if the value read is the expected value, writes the new value; it reports whether it wrote. No other thread accesses the location between its read and its write. Like test-and-set, it also synchronizes: whatever a thread did before a compare-and-set that succeeded is ordered before whatever another thread does after reading the value that this compare-and-set wrote. Block 1's definition of a data race now receives the clause it needs: a data race is two accesses to one location from two threads, with no synchronization between them, of which at least one is a write and at least one is a plain access, that is, not atomic. Two accesses that are both atomic are therefore never a data race. This definition, with its clause, is the wording of OCaml's and of C++'s; Java reaches the same result because accesses to volatile fields and accesses through the atomic classes used here are synchronization actions, which all fall in one order.15,19 In OCaml the comparison is physical, the test ==. A value held in the word itself, an int or a constant such as [] or None, is compared by its value; a value allocated in memory, a list cell for instance, is compared by its address, so the location must hold the very same cell, not merely an equal one. In Java, compareAndSet on an AtomicReference compares references by identity, ==, never by equals. Fetch-and-add adds a number to the location and returns the old value, in one indivisible step, with the same synchronization. In Java these are compareAndSet and getAndAdd on an AtomicInteger, with getAndIncrement for adding one; in OCaml 5, Atomic.compare_and_set and Atomic.fetch_and_add, with Atomic.incr for adding one.

The counter on compare-and-set, and on fetch-and-add

Example 6, Java: CounterCas.java

static final AtomicInteger n = new AtomicInteger(0);   // the counter, one word
final int N = 1_000_000;                               // increments per thread

// returns how many attempts failed before the one that succeeded
static int increment() {
  int failed = 0;
  while (true) {
    int v = n.get();                              // read
    if (n.compareAndSet(v, v + 1)) return failed; // still v? then v + 1, in one step
    failed++;                                     // another thread wrote first: retry
  }
}

n.set(0);                                                 // the counter back to 0
Runnable work = () -> { for (int i = 0; i < N; i++) n.getAndIncrement(); };  // fetch-and-add
$ java CounterCas
compare-and-set: expected 2000000, got 2000000, failed attempts 653147
fetch-and-add:   expected 2000000, got 2000000

Example 6, OCaml 5: counter_cas.ml

let n = Atomic.make 0

(* Adds 1 to n; returns the number of failed attempts. *)
let increment () =
  let rec attempt failed =
    let v = Atomic.get n in
    if Atomic.compare_and_set n v (v + 1) then failed
    else attempt (failed + 1)   (* another domain wrote n meanwhile: retry *)
  in
  attempt 0
let m = Atomic.make 0
let increment_faa () = ignore (Atomic.fetch_and_add m 1)
$ ./counter_cas
compare-and-set  expected 2000000  got 2000000  failed attempts 679563
fetch-and-add    expected 2000000  got 2000000

The loop is the second way's whole mechanism. The thread reads the current value; it computes the new one, outside any protection; it asks the instruction to write it provided the location still holds what it read. If another thread wrote in between, the instruction fails, which detects the interleaving by what it changed; the thread retries from a fresh read. An attempt fails only when another thread's compare-and-set on the counter succeeded between this thread's read and its attempt; nothing else changes the counter. With two threads, each success of one thread makes at most one attempt of the other fail, since the other re-reads after it; so in this program at most two million attempts fail, and the sample's 653,147 is within that bound.

Two threads each call increment one million times. Can the total be wrong, and can an attempt fail?

  1. The total is exact, and no attempt ever fails.
  2. The total is exact; an attempt fails when another thread wrote the counter between this thread's read and its attempt.
  3. The total is wrong whenever an attempt fails.
The answer

The second answer. The run above is one sample: the total was exact and 653,147 attempts failed, each one an increment that read a value, found the counter changed, and read again. A failed attempt loses nothing, because the loop re-reads before it tries again, and the compare-and-set writes only when the counter still holds what was read. Whether the loop can spin for ever, so that the program never ends, is a further question, and in this program it cannot happen: a failure needs another thread's success, and the other thread succeeds at most a million times, so every loop ends. Whether it could happen in general is the question of progress, below.

The contract, the obligation, the progress, who checks

Block 1's way forbade the interleaving; this one accepts it, detects it and retries. Each way is stated in the four terms of the session's frame: the contract, what the way guarantees; the obligation, what the programmer must establish; the progress risk; and who checks the obligation.

The contract. The operation is atomic without exclusion, and linearizable: its point of effect is the compare-and-set that succeeds, the one indivisible step at which the counter changes. Every other step of the loop, the reads and the failed attempts, changes nothing that another thread can see.

The obligation. The loop re-reads: every attempt starts from a fresh read, never from a value kept from an earlier attempt. Every write keeps the invariant of the location. Here the invariant is that every write replaces the current value v by v + 1, and the compare-and-set guarantees it, because it writes v + 1 only where the location still holds v. And the point of effect is named by the programmer, in a comment on the line and in the argument that the operation is linearizable, as section 3 makes for the stack.

read v compute v + 1 compare-and-set v, v + 1 succeeded point of effect failed, another thread wrote since the read: the next attempt read v fresh, every attempt compare-and-set v, v + 1 keeps the invariant, v to v + 1
The loop of the second way: read, compute, compare-and-set; the dot is the point of effect, the lower arrow the retry. The obligation: a fresh read every attempt, and a write that keeps the invariant.

The progress. A compare-and-set on the counter fails only because another thread's compare-and-set on the counter succeeded between this thread's read and its attempt. So every failed attempt is matched by an increment that took effect. Suppose some thread keeps taking steps in an increment that never completes. Its attempts keep failing, and each failure needs a success by another thread after the failing thread's read. A success ends the increment of the thread that succeeds, and that thread can succeed again only in a new increment, after returning from the old one. So increments keep completing. The loop is lock-free. It is not wait-free, which would require every thread to complete each of its operations within finitely many of its own steps: nothing stops one thread from failing at every attempt, another thread having written first each time; in principle that thread retries for ever while the others keep completing operations. The one-instruction version, fetch-and-add, is wait-free in the model of block 1, where one atomic instruction is one step: it takes no expected value and never retries, so it cannot fail, and each call is one step of its thread. Calls on one word from several threads do compete for the word, and the hardware orders them, but none is turned away. The model's step is one instruction of the machine where the processor has the instruction; where it has not, the library builds fetch-and-add as a loop of the same kind as the one above, which is lock-free.

Who checks. Nobody but the programmer, by proof. Java and OCaml accept a loop that keeps a value from an earlier read, a write that breaks the invariant, or a sequence of two atomic steps that was meant to be one. Section 3 shows that last mistake. Tools exist that check histories after the fact, and section 3 names them. Java's library offers the loop ready-made, updateAndGet with a function, and its documentation warns, as Clojure's documentation of swap! does in section 3, that the function may be run several times.

What this section leaves open: a counter is one word, and the whole state fits in the location the instruction covers. A stack is a structure of many nodes. The next section shows that the same loop serves, provided the structure is arranged so that one word is enough.

3. Treiber's stack

The method that makes the loop apply to a stack is to make one reference stand for the whole structure. A stack is a chain of nodes; if each node, once built, never changes, then the reference to the top node determines the whole stack, and changing the stack is changing that one reference. Treiber published the algorithm in 1986.4

An immutable node is a node whose fields are never changed after it is built; in Java, a record, whose fields are final. An atomic reference is a location holding a reference, read and written only by atomic instructions, compare-and-set among them; in Java an AtomicReference, in OCaml 5 an Atomic.t.

Example 7b, Java: Treiber.java

record Node(int value, Node next) { }             // immutable: final fields, never changed

// invariant: top points to a well-formed stack, a chain of nodes ending in null
static final AtomicReference<Node> top = new AtomicReference<>(null);

static void push(int x) {
  while (true) {
    Node old = top.get();
    Node fresh = new Node(x, old);                // built beside the stack
    if (top.compareAndSet(old, fresh)) return;    // point of effect: this compare-and-set
  }
}
static Integer pop() {                            // null when the stack is empty
  while (true) {
    Node old = top.get();                         // empty: point of effect is this read
    if (old == null) return null;
    if (top.compareAndSet(old, old.next())) return old.value(); // point of effect
  }
}

static void pushBroken(int x) {                   // broken on purpose
  Node old = top.get();                           // read
  top.set(new Node(x, old));                      // write: another push may have come between
}
$ java Treiber
compare-and-set: pushed sum 125000500000, popped 62557066183 + remaining 62443433817 = 125000500000
read, then write: pushed 1000000 items, on the stack 307454, lost 692546

Example 7b, OCaml 5: treiber.ml

(* Invariant: the atomic holds a well-formed stack, an OCaml list.
   The list is never changed, only replaced by another one. *)
type 'a stack = 'a list Atomic.t

let rec push (s : 'a stack) x =
  let l = Atomic.get s in
  (* Point of effect: the compare-and-set that succeeds. *)
  if not (Atomic.compare_and_set s l (x :: l)) then push s x
let rec pop (s : 'a stack) =
  match Atomic.get s with
  | [] -> None   (* Point of effect: the read that saw the stack empty. *)
  | x :: rest as l ->
      (* Point of effect: the compare-and-set that succeeds. *)
      if Atomic.compare_and_set s l rest then Some x else pop s
(* Broken on purpose: read the top, then write it, with no compare-and-set.
   A push by another domain between the get and the set is lost. *)
let push_broken (s : 'a stack) x =
  let l = Atomic.get s in
  Atomic.set s (x :: l)
$ ./treiber
pushes and pops, 4 domains
  sum pushed          125000500000
  sum popped + left   125000500000
pushes only, 4 domains
  treiber  1000000 items in the stack, of 1000000 pushed
  broken    350362 items in the stack, of 1000000 pushed

The harness of a program is the code around the lines under study that runs them and prints the result. The first part of each run is Treiber's stack in the harness of the locked stack, four threads pushing and popping: what was popped and what remains add up to what was pushed, and ten more runs agreed. The second part runs the broken push alone, four threads pushing only, and the stack ends with fewer items than were pushed, in this sample fewer than a third in Java and about a third in OCaml; in ten more runs in OCaml the stack held between a quarter and a half of the million items. One run each shown, one sample.

How push and pop work

A push reads the current top and builds its new node, not yet reachable from the stack, with its next pointing at the top it read. It then calls compare-and-set to replace the top reference by the new node, provided the top is still the node it read. If the top is no longer the node it read, because other threads pushed or popped in between, the attempt fails, and the push reads again and builds a new node. If other threads moved the top and moved it back to the very same node, the attempt succeeds, and rightly, since that node, never changed, still heads the same chain. A pop reads the top. If the top is null, the stack was empty at that read, and the pop returns null. Otherwise the pop calls compare-and-set to replace the top by the node below, provided the top is still the node it read, and when the compare-and-set succeeds it returns the value of the node it read. In both languages a read of the top is a snapshot of the whole stack, a complete stack as it was at the instant of the read, since the chain the top reaches never changes; the stack itself may move on after the read. In OCaml the snapshot is literally a value of the language, an immutable list, and the "node" of the figure below is one cell of the list.

a push that succeeds top 7 4 null 9 built beside the stack, pointing at the top it read top the compare-and-set swings top to it: the point of effect a failed attempt: the top moved after the read top 2 7 4 … Another thread pushed 2 meanwhile, so top is no longer 7: the attempt expecting 7 fails, and the push reads again and builds a new node above 2. nodes 7 and 4 are shared by both versions of the stack: they never change
Treiber's push. The new node is built outside the stack, pointing at the top that was read; the compare-and-set replaces the top reference by it. If the top is another node meanwhile, the attempt fails and the push starts from a fresh read. Nodes are never changed, so an older version of the stack and the new one share the chain they have in common.

The broken push

The broken push reads the top, then writes a new node above it with an atomic write alone, top.set in Java and Atomic.set in OCaml, no compare-and-set. Four threads push only, a million pushes in all, and the stack ends with 307,454 items. Where does it go wrong, and is it a data race?

  1. Between its read and its write another thread's push took effect; the write then installs a node pointing at the old top, and the other push is lost. Both accesses are atomic, so it is not a data race: it is an atomicity violation.
  2. The read and the write of the broken push are a data race, since nothing orders them against the other threads' writes.
  3. The immutable nodes are the problem: a node built before the top moved cannot be re-pointed, so its push is lost.
The answer

The first answer. Recall block 1's two words, with section 2's clause. A data race is two accesses to one location from two threads, with no synchronization between them, of which at least one is a write and at least one is plain; two atomic accesses to one location are never a data race. An atomicity violation is a multi-step operation not protected as a unit. The broken push is the counter's bug again, on a reference: a read and a write with a step of another thread between. It is the session's clearest example of a data race and an atomicity violation told apart: both accesses are atomic, so there is no data race, and the bug is an atomicity violation. No run can settle the second half of the question; the definition does. The third answer is wrong: the lost pushes come from the write that is not a compare-and-set, not from the nodes. A node whose compare-and-set failed was never installed, so no other thread can reach it, and setting its next to the new top before the next attempt would be just as correct as building a new node. What matters is that a node never changes once another thread can reach it: then the chain below a node that a thread has read is fixed, which the proof sketch uses.

The proof sketch

The standard of section 1 is that every history be explained by the sequential stack, and that progress be guaranteed. The argument has four parts: the invariant, the points of effect, safety and liveness. Each part names something in the code, and a remark on who checks follows the four parts.

The invariant. The top reference points to a well-formed stack: a chain of nodes ending in null, each node immutable once another thread can reach it. The stack that the top stands for is the list of the values read from the top node down to null; the invariant makes this list well defined. The invariant holds at the start, when the top is null. Every write to the top is a compare-and-set, and each one keeps it: a push installs a node whose next is the top it read, which was well-formed, and the node never changes; a pop installs the next of the top it read, which is the rest of a well-formed chain. A failed attempt writes nothing.

The points of effect. A push takes effect at its compare-and-set that succeeds. A pop on a non-empty stack takes effect at its compare-and-set that succeeds. A pop on an empty stack takes effect at the read that saw the top null: at that instant the stack was empty, and the sequential pop of an empty stack returns null. Each of these is one indivisible step inside the operation's call and return.

top 3 2 1 well-formed: a chain of nodes down to null, none changed once another thread can reach it 4 CAS push(4): one compare-and-set on top; the dot is its point of effect

Treiber's stack: top points to the first node, and each node holds a value and a pointer to the next, the last one null.

  1. The invariant: top points to a well-formed stack, a chain of nodes down to null, none of which changes once another thread can reach it.
  2. push(4): the node is built aside, pointing at the old top, node 3; one compare-and-set swings top from node 3 to node 4, and the old pointer is left as a ghost. The orange dot on the compare-and-set is the push's point of effect.

Safety, which is linearizability. Order the operations of a history by their points of effect. Between two consecutive points of effect the top does not change, since failed attempts and reads write nothing. At each point of effect, the stack that the top stands for changes exactly as one sequential push or pop changes it. A successful push's compare-and-set replaces the top by a node whose next is the top that was there, which adds one value on top, as the sequential push does. A successful pop's compare-and-set replaces the top by the node below it, which removes the value on top, as the sequential pop does. An empty pop's read changes nothing, as the sequential pop of an empty stack changes nothing. So the sequence of stacks the top stands for is exactly the sequence of states a sequential stack passes through when the operations are applied in the order of the points of effect. And each operation returns what the sequential stack returns at that point: a pop returns the value of the node that was the top at its point of effect, which is the value the sequential pop removes; an empty pop returns null when the sequential stack is empty. An operation stopped after its successful compare-and-set has taken effect, and is given the return value the sequential stack gives at that point; one stopped before has written nothing and is left out. The history is explained by the sequential stack.

Liveness. As for the counter. A compare-and-set on the top fails only because another compare-and-set on the top succeeded between this thread's read and its attempt, and that success is the point of effect of a push or a pop. Suppose some thread keeps taking steps in an operation that never completes. Its attempts keep failing, and each failure needs a success by another thread after the failing thread's read. A success ends the operation of the thread that succeeds, and that thread can succeed again only in a new operation, after returning from the old one. So the successes go on, and since there are finitely many threads, some thread completes operations again and again. The stack is lock-free. It is not wait-free: every attempt of one thread may fail.

thread A thread B push(1) pop() → 1 push(2) pop() → 2 2 1 2 2 empty the sequential stack after each tick A's attempt fails: B's compare-and-set succeeded since A's read; A re-reads and succeeds

The history of the quiz, with the point of effect of each operation as a tick and, above it, the sequential stack after the tick.

  1. The points of effect in the order push 2, push 1, pop giving 1, pop giving 2: run in this order, the sequential stack returns what the history returned.
  2. A's first attempt at its push fails, the dashed tick, because B's compare-and-set succeeded after A's read; A reads the top again and succeeds.

A top that changes and comes back between a thread's read and its compare-and-set is the ABA problem; the appendix treats it, with a garbage collector and without one.

Who checks. The programmer, by this proof. The types check part of the invariant: in OCaml the type 'a list Atomic.t guarantees a well-formed chain of immutable cells outright, and in Java the record's final fields guarantee that a node never changes. Nothing in either language checks that every write to the top is a compare-and-set from a fresh read, or where the points of effect are; the broken push compiles and runs. At test time there are checkers that take a recorded history and search for a placement of the points of effect that the sequential specification accepts: Lincheck for Java and Kotlin, which generates the concurrent runs as well; Knossos and Porcupine, which take histories. They do not replace the proof; they are what practice uses, and the mini-project's checker is one of this kind.

The bridge to Part 1

A data structure is persistent when an update leaves the old version usable and gives a new one; the usual way, Part 1's, is for the new version to share the unchanged part of the old, and Part 1's lists and ropes were persistent. What made the stack fit in one word is a persistent value: the chain of immutable nodes. Treiber's stack is a persistent value behind one atomic reference, and an operation is one compare-and-set on that reference. Herlihy made this general in 1993.3 For an object small enough to copy, an operation reads the reference to the object, copies the object, applies the sequential operation to the copy, and then replaces the reference by one to the copy, retrying when the replacement fails. In Herlihy's protocol the replacement is a store-conditional. Load-linked and store-conditional are a pair of instructions: load-linked reads a location, and the store-conditional that follows writes it only if nothing has written the location since the load-linked. On compare-and-set instead, the same protocol needs the garbage collector against ABA, as Treiber's stack does. For an object too large to copy, the operation builds a new version that shares the parts it does not change, which is exactly a persistent update, and then replaces the reference to the root by a reference to the new version. Clojure's atom is one atomic reference holding an immutable value, and swap! is Herlihy's protocol as a library call on compare-and-set: it reads the atom's value, applies the given function, and attempts a compare-and-set, retrying in a loop. It may run the function several times, so the function must have no effects; nothing checks it. In the course's three runs, eight threads doing 800,000 swaps in all each run had the function called between 4.2 and 4.6 million times, each call beyond one per swap a retry. Java's updateAndGet on an atomic reference is the same loop, with the same warning in its documentation.13

ref r1 L R version 1 r2 L′ version 2 shares R CAS read the reference apply f to the value compare-and-set the ref failed point of effect r2′ L″ another's v2′ CAS the compare-and-set fails, and f runs again, on v2′

A persistent value behind one reference, on the left; on the right the loop of Clojure's swap!, which applies a function f to the value.

  1. Version 2 shares R with version 1 and copies only the path it changes; one compare-and-set swings the reference from r1 to r2. When the compare-and-set fails, the loop reads the reference again.
  2. Another thread's version, r2′, is installed first: the compare-and-set expecting r1 fails, and f runs again, on the value of r2′.

What this section leaves open: whether a structure without a lock is always the better choice, and whether every structure has such a version.

4. Contention

Section 3 answered block 1's question: an operation can be atomic without a lock around it, and a proof sketch establishes it. Two further questions follow at once, whether lock-free is always best and whether every structure has a lock-free version; this section answers the first.

Whether lock-free is always best

Not always, for two reasons: contention, and an uncontended lock, which costs no more than one attempt of the loop.

Contention. Contention is several threads wanting the same word at the same time. Every failed compare-and-set is wasted work, and when many threads retry on one word, the top of the stack for instance, most attempts fail: every operation on the stack passes through the top, which Hendler, Shavit and Yerushalmi, who built a faster stack on Treiber's, call a sequential bottleneck.11 The clearest measurement is flat combining, by Hendler, Incze, Shavit and Tzafrir. Each thread writes the operation it wants into a shared list of requests; one thread takes a coarse lock and performs all the requests it finds there, one after another, while the others wait for their results. The authors measured on a Sun SPARC T2 machine, from 1 to 64 threads. Their flat-combining queue overtakes Michael and Scott's lock-free queue from about four threads on and is four to seven times faster at the higher thread counts; their flat-combining stack is up to nine times faster than Treiber's stack, whose top is the bottleneck.10 Flat combining is lock-based and blocking. So a structure with a lock can be faster than a structure without one.

top thread 1 thread 2 thread 3 one succeeds the others fail and retry: wasted steps every operation passes through the top
Contention: three attempts meet at top; one succeeds, the others fail and retry.
flat combining request 1 request 2 request 3 request 4 one thread, under the lock the structure one thread performs every request; the others publish theirs and wait
Flat combining: each thread publishes its request; one thread, under the lock, performs them all.

The uncontended lock. Taking a lock that no thread holds is itself one atomic instruction, the test-and-set of block 1's spin lock, the same kind of step as one compare-and-set attempt. Each is costly when several threads want the word, and neither is costly when no other thread does.

The appendix sets out operations on the whole structure, the case where only a non-blocking structure will do, and the universality of compare-and-set, which answers the second question.

What this section leaves open: the second way keeps the sharing and pays for it in retries. The third removes the sharing itself.

5. Deterministic parallelism

The first two ways accept that the threads share state and make its operations atomic, by exclusion or by one instruction. The third way arranges the work so that the order in which the threads run cannot change the result. Then no interleaving is harmful, and nothing has to be forbidden or redone.

A count per thread, then the sum

Example 8 (a), Java: PerThread.java

final int N = 1_000_000;
long[] counts = new long[2];                    // slot t written by thread t, read after join
Thread[] ts = new Thread[2];
for (int t = 0; t < 2; t++) {
  final int id = t;
  ts[t] = new Thread(() -> {
    long mine = 0;                              // local: no other thread sees it
    for (int i = 0; i < N; i++) mine++;
    counts[id] = mine;
  });
}
for (Thread t : ts) t.start();
for (Thread t : ts) t.join();
System.out.println("expected " + 2 * N + ", got " + (counts[0] + counts[1]));
$ java PerThread
expected 2000000, got 2000000

Example 8 (a), OCaml 5: per_thread.ml

(* (a) Each domain counts in its own variable and returns the count. *)
let count () =
  let c = ref 0 in   (* local: no other domain can reach it *)
  for _ = 1 to 1_000_000 do incr c done;
  !c

let per_domain () =
  let a = Domain.spawn count and b = Domain.spawn count in
  Printf.printf "expected %d\ngot      %d\n" 2_000_000 (Domain.join a + Domain.join b)
$ ./per_thread
(a) a count per domain, then the sum
expected 2000000
got      2000000

This is the counter's third version in this session, after the lock of block 1 and the compare-and-set of section 2: exact, with no lock and no atomic instruction. Each thread counts in a variable of its own, which no other thread can reach; the order in which the threads run cannot matter, because nothing is shared while they run. Nothing shared while the threads run means, precisely, that no location written by one thread is read or written by another thread while they run. At the end the counts are added by one thread, after the others have ended. One sample; ten more runs printed the same.

One line carries the whole argument, and it is the join. In the Java program the array counts is shared, but each slot of it is written by one thread only, and the main thread reads the slots after join, which orders each thread's last step, its write of its slot, before the main thread's read. The join is what makes each count visible to the thread that sums. Without the join the same program has a data race by block 1's definition: two accesses to one location from two threads, one a write, with nothing of the program ordering them. The main thread may then read a slot before or after its one write, and the program may print 0, one million or two million; a slot is a long, so Java would also allow a value made of half of each write, which here gives nothing new, since both values, 0 and one million, have zero in their high 32 bits. In the OCaml program the count comes back as the value Domain.join returns, with no shared variable in the program; the join still carries the argument, since everything the domain did is ordered before the join returns. The first of the lab's questions on paper asks the same of a worker that writes its result into counts[id]: what the main thread may read there before the join, after the join, and after joining only the other workers.

A pure function is one whose result depends on its arguments only and that changes nothing outside itself; a map over a sequence applies a function to each element and collects the results, a word the course uses in this sense only, never for a dictionary. A parallel map is the same arrangement as the count per thread, over a sequence. With a pure function the elements' results are independent, so any thread may compute any of them in any order, and the only shared step is putting each result in its own slot. No program for it here; in Java the library's parallel streams, which run a map or a fold over a collection on several threads, do it.

The parallel fold

A fold combines the elements of a sequence with a binary operation, starting from a seed and going from left to right: the fold of 1, 2, 3 with subtraction from 0 is ((0 − 1) − 2) − 3. A parallel fold splits the sequence into parts, folds each part on a thread of its own from the seed, and combines the parts' results in their order, as a tree. With the parts' results p0, p1, p2, p3, two halves give p0 op p1, and four quarters give (p0 op p1) op (p2 op p3). A split is one way of cutting the sequence into parts. An operation is associative when (x op y) op z = x op (y op z) for all x, y, z; it has an identity e when e op x = x = x op e for all x; it is commutative when x op y = y op x for all x, y.

Example 8 (b) and (c), Java: PerThread.java, the fold

// one thread per part folds its part from e, from left to right;
// then the main thread combines the parts' results as a tree:
// two parts p0 op p1, four parts (p0 op p1) op (p2 op p3)
static long fold(long[] a, int parts, long e, LongBinaryOperator op)
    throws InterruptedException {
  long[] partial = new long[parts];
  Thread[] ts = new Thread[parts];
  int size = a.length / parts;
  for (int p = 0; p < parts; p++) {
    final int lo = p * size, id = p;
    ts[p] = new Thread(() -> {
      long acc = e;
      for (int i = lo; i < lo + size; i++)
        acc = op.applyAsLong(acc, a[i]);
      partial[id] = acc;
    });
  }
  for (Thread t : ts) t.start();
  for (Thread t : ts) t.join();
  for (int n = parts; n > 1; n /= 2)    // one level of the tree
    for (int p = 0; p < n / 2; p++)
      partial[p] = op.applyAsLong(partial[2 * p],
                                  partial[2 * p + 1]);
  return partial[0];
}
$ java PerThread
+ in two halves:    36
+ in four quarters: 36
- in two halves:    16
- in four quarters: 0

Example 8 (b) and (c), OCaml 5: per_thread.ml, the fold

(* (b), (c) Fold a.(lo) .. a.(hi - 1) with op from e, as a tree of depth
   levels: the left half in a new domain, the right half in this one,
   op at the node. depth 1 gives two halves, depth 2 four quarters. *)
let rec pfold op e a lo hi depth =
  if depth = 0 then Array.fold_left op e (Array.sub a lo (hi - lo))
  else
    let mid = (lo + hi) / 2 in
    let left = Domain.spawn (fun () -> pfold op e a lo mid (depth - 1)) in
    let right = pfold op e a mid hi (depth - 1) in
    op (Domain.join left) right
$ ./per_thread
(b) fold of 1 .. 8 with ( + ) from 0
two halves     36
four quarters  36
(c) fold of 1 .. 8 with ( - ) from 0
two halves     16
four quarters  0

In the Java fold, LongBinaryOperator is the library's type for a function of two long arguments, applied with applyAsLong; the last loop combines the parts' results level by level, two parts at a time, which for four parts is (p0 op p1) op (p2 op p3). The parts are combined in their order, after every thread has been joined, never in the order the threads finish. As written, the Java fold assumes that the number of parts is a power of two and divides the length of the array; with three parts it would drop the third part's result, and the test's fold of question 11, with its three pairs, is a different program.

The array is 1 to 8 and the seed is 0. The sequential fold with subtraction, one thread from left to right, gives −36. Does the parallel fold with subtraction agree with it in two halves? In four quarters? Does its answer change from run to run?

  1. Yes, yes, no: a fold is a fold, and the threads only share the work.
  2. No, no, no: the two halves give 16 and the four quarters give 0, and each grouping prints the same number on every run.
  3. No, no, yes: the result depends on which thread finishes first.
The answer

The second answer. Two halves: (0 − 1 − 2 − 3 − 4) − (0 − 5 − 6 − 7 − 8) = −10 − (−26) = 16. Four quarters: ((0 − 1 − 2) − (0 − 3 − 4)) − ((0 − 5 − 6) − (0 − 7 − 8)) = (−3 + 7) − (−11 + 15) = 4 − 4 = 0. The parts are always combined in their order, after every thread has been joined, so the interleaving plays no part and each grouping is deterministic: ten more runs printed the same. What fails is agreement across splits, not across runs. The intended specification is "the same answer as the sequential fold, for any number of threads", and subtraction breaks it because it is not associative. Question 11 of the session's test-yourself page asks the same of a fold of 1 to 6 whose parts start from their first element instead of a seed; it gives 3 in two halves and 1 in three pairs by the same arithmetic.

two halves four quarters 1 2 3 4 5 6 7 8 −10 −26 16 each part folded from 0 −10 − (−26) 1 2 3 4 5 6 7 8 −3 −7 −11 −15 4 4 0
The fold of 1 to 8 with subtraction from 0, grouped as two halves and as four quarters. The parts are the same numbers in the same order; only the bracketing differs, and the roots differ, 16 against 0. With addition both trees have the root 36, and so does the sequential fold, because addition is associative.

Associativity is what guarantees the specification, the same answer as the sequential fold for every split, provided that op is a function without side effects: it changes no state, and its result depends only on its arguments. An op that also wrote to a shared variable, or read a clock, could give a different answer from run to run, whatever its associativity. For an associative operation, every bracketing of x1 op x2 op … op xn gives the same value; so, when every part is folded from the identity, every split of the sequence agrees with the sequential fold, whatever the number of threads. Every part needs the identity, not only a part with no elements: each part is folded from the seed, so the seed must be a value that changes nothing when combined, or it is counted once per part; with seed 5 and addition, two halves give 46 against the sequential 41. A part with no elements must fold to that value. Zero is not an identity of subtraction, since x − 0 = x but 0 − x ≠ x. In two halves, the first part starts from 0, as the sequential fold does, and gives −10, the value the sequential fold reaches after 1 to 4; the error enters with the second part, which starts from 0 instead of continuing from −10, and the combine −10 − (−26) gives 16 where the sequential fold gives −36. Combining the parts in their order is what makes associativity enough: the program joins every thread and then combines p0 with p1, then with p2 and p3, in the order of the sequence. A program that combined the parts in the order the threads finish would need the operation to be commutative as well. Addition of integers is both, even when it overflows, since Java's long and OCaml's int wrap around; addition of floating-point numbers is commutative and not associative, so a parallel sum of doubles may differ from the sequential sum in its last digits, and differ again with another number of parts. Concatenation of strings is associative and not commutative, and a parallel fold with it is right exactly because the parts keep their order; maximum is both, with the smallest number the type can represent as its identity. Java's library states the same condition in its own words: Stream.reduce requires an identity and an operation that is associative and, in the library's words, non-interfering and stateless.13

The three forms of the third way

The independence of the order comes in three forms.

First form: no shared mutable state during the run, and a combine step
The count per thread, the parallel map, the parallel fold. The threads share nothing that any of them writes while they run; a combine step after the join puts the results together. The obligation is that the combine is a function without side effects, associative with an identity, and that the parts are combined in their order, or, if they are combined in the order the threads finish, that the combine is commutative as well.
Second form: updates that commute, each applied as one step, or to a replica of its own that is merged at the end
Two updates commute when applying them in either order gives the same state. Increments commute; so do insertions into a set. The first case, each update applied as one step, is fetch-and-add on one word. The first way or the second makes each step atomic, and the interleaving still orders the steps; what commutativity adds is that the final state is the same for every order the steps took. The Java library's LongAdder is this case made faster: under contention it spreads the updates over several cells, each updated by compare-and-set, so that fewer threads compete for any one word; sum adds the cells, and is not an atomic snapshot of them.13 The second case applies each update to a replica, a copy of the state that one thread alone updates and that is merged with the others at the end: a set per thread, merged by union; the structures session 9 calls CRDTs, conflict-free replicated data types, replicas merged by an operation that is commutative, associative and idempotent, so that merging in any order and any number of times gives one state. The condition is the atomic step or the private replica. Commuting updates that are not atomic are the racy counter of block 1: its increments commute, and it loses updates, because the read, add and write of one increment interleave with another's. Commutativity of the updates does not make the counter correct unless each update is atomic.
Third form: determinism by construction
Languages in which every interleaving gives the same result, by the rules of the language. Dataflow: a program is a network of sequential programs, each with memory of its own, connected by unbounded queues, each queue written by one program and read by one. Kahn showed in 1974 that such a network computes the same function whatever the schedule, provided that each program is deterministic, reads each of its input queues in order, waits when a queue is empty, and never tests whether a queue is empty.9 Single-assignment variables: a variable written once, a second write being an error, and a read that waits until the write has happened, so that no read can see a value that a different order would have changed.

Immutability is not a fourth way. It is a technique that serves the second way, Treiber's immutable nodes and Herlihy's copy-and-swap, and the third, where nothing is shared because nothing is mutable.

thread 1 part 1 thread 2 part 2 thread 3 part 3 combine, in order result nothing shared while the parts run; the combine associative, with an identity
The first form: independent parts, combined in their order after the joins.
thread 1 +1 thread 2 +1 thread 3 +1 n one atomic step each: any order gives the same total or a replica per thread, merged at the end
The second form: commuting updates, each one atomic step on one word, or each to a replica merged at the end.
program 1 queue one writer, one reader program 2 queue one writer, one reader program 3 the same function in every schedule (Kahn, 1974); single-assignment variables do the same
The third form: a dataflow network, sequential programs connected by queues with one writer and one reader each.
an immutable value the second way: Treiber's nodes, copy-and-swap the third way: nothing shared, because nothing mutable not a fourth way
Immutability serves the second way and the third; it is not a fourth way.

The counter against the stack

For the counter every way gives the same final value, because increments commute: once each increment is atomic, under a lock or by one instruction, or is made in a slot of its own, the order of the steps does not show in the result. For a stack shared while the threads run, two pushes do not commute, and the pops show which came first; so what the pops return depends on the interleaving under every way, and the only demand on the stack is that each run be explained by some order of its operations, which is linearizability. The third way is for work whose intended result is one value, the same for every order: a count, a sum, a fold. Its second form needs updates that commute. Its first form needs only a combine that is associative and is taken in the order of the parts; that is why concatenation is third-way work, and so is a stack that each thread builds for itself and that the program concatenates with the others in order after the joins. Its third form needs neither. Threads that push and pop on one shared stack, each using what its pops return while the threads run, have no such result: which pop returns which value depends on the order, and the specification of the stack allows every order. That is why the third way applies to the counter and not to a shared stack, and why linearizability is the whole demand on the stack.

thread 1 +1 thread 2 +1 thread 3 +1 n = 3 in every order one intended result, the same for every order: the third way's work
The counter: increments commute, so every order gives the same total.
thread 1 pushes a thread 2 pushes b b a or a b the pops show which came first no single intended result; linearizability suffices
The stack: two pushes do not commute, and the pops show which came first; linearizability is the whole demand.

The contract, the obligation, the progress, who checks

The contract: a deterministic final result, the same in every interleaving; the values an atomic step returns on the way, the old value of a fetch-and-add for instance, still depend on the order. The obligation: one of the three forms, in full: nothing shared while the threads run and a combine without side effects that is associative with an identity, the parts combined in their order; or updates that commute, each applied as one step or to a replica of its own merged at the end; or determinism by construction. The progress risk: none from the interleaving; but the join is blocking in the sense of section 1, since the thread that combines waits for every worker, and a worker that is stopped stops the result. What the way costs besides is the combine step, which runs after the threads it waits for. Who checks: the type system can check that nothing is shared while the threads run. In Haskell a pure function cannot touch mutable state: a mutable variable is a cell that only code whose type shows it may write, IO for an IORef, and the compiler rejects a function of type Int -> Int that tries to write one, with the error "Couldn't match expected type ‘Int’ with actual type ‘IO Int’".23 In Rust the compiler checks that each thread owns its slot. Rust's borrowing rules give the right to change a value, a mutable borrow, to one holder at a time, and the right to read it, a shared borrow, to any number of holders. In the per-thread count under thread::scope, each thread holds the mutable borrow of a different slot and a shared borrow of its own part of the data, with no lock and no atomic, and the scope ends before the main thread reads the slots.18 That the combine is associative, or that the updates commute, nobody but the programmer checks: the fold with subtraction type-checks in Haskell and in Rust as it does in Java.

What this section leaves open: all three ways make one operation atomic, or make one result order-independent. The transfer of block 1 needs two operations to be one. Two atomic operations compose when the operation that performs the one and then the other is itself atomic, so that no other thread can observe the state between them; the next section shows whether atomic operations compose.

6. Composition

Block 1 showed the transfer: a withdrawal under the source's lock, then a deposit under the destination's lock, each atomic, and a third thread reading both balances under both locks saw 199 where the sum should be 200. Two atomic steps are not one atomic step. The same holds for the second way: a compare-and-set on the source and a compare-and-set on the destination are two points of effect, and a reader may read both balances between them. Neither locked nor compare-and-set operations compose by themselves into one atomic operation.

Example 4 (a), Java: Accounts.java, the transfer in two halves, and the reader

static final Account A = new Account("A", 1, 100), B = new Account("B", 2, 100);  // name, id, balance

// (a) each step under its lock, the transfer as a whole under none: broken on purpose
static void transferA(Account from, Account to, int x) {
  synchronized (from) { from.balance -= x; }
  synchronized (to)   { to.balance   += x; }
}
// the reader: both balances under both locks, A's first (the order of the ids)
static int[] read() {
  synchronized (A) { synchronized (B) { return new int[] { A.balance, B.balance }; } }
}
$ java Accounts a
reading 1: A = 99, B = 100, sum = 199 (should be 200)
after the transfers: A = 100, B = 100, sum = 200

Example 4 (a), OCaml 5: accounts.ml, the transfer in two halves

(* (a) Two atomic steps. lock w a takes account a's mutex and records,
   in w, who holds what, for the watchdog that detects the deadlock of (b). *)
let transfer_split w src dst k =
  lock w src; src.balance <- src.balance - k; unlock w src;
  lock w dst; dst.balance <- dst.balance + k; unlock w dst
$ ./accounts split
2000000 transfers, A = 100, B = 100, sum 200
the reader: 39283783 readings, 29828667 with a sum other than 200
  first wrong reading: A = 234, B = -35, sum 199

In both languages the two balances always add up to 200 between transfers, since every transfer moves money from one account to the other; a reader that holds both locks and sees 199 has read between the two halves of a transfer. Each line is one sample, one run of that program on one machine.

Two senses of "compose"

Herlihy and Wing proved that linearizability is local: a history over several objects is linearizable if and only if, for each object, the part of the history that concerns that object is linearizable.1 So two linearizable objects used together are still a linearizable system, each operation at its own instant; in that sense linearizability composes across objects, a sense different from two operations composing into one. Locality is what tells linearizability apart from sequential consistency applied to objects, which keeps each thread's order but not the real-time order between threads and does not compose across objects. What is not given is one instant for two operations: the withdrawal and the deposit each have their own point of effect, and nothing makes them one. The system of two accounts is linearizable; there is no operation on both accounts that takes effect at one instant, which is what a transfer would be.

Three ways give two operations one instant: both locks held around both steps, both accounts behind one reference, or a transaction; the appendix sets out each, with its price.

What this section leaves open: every argument of this session has rested on the assumption that a run is an interleaving. Section 7 says who guarantees that.

7. Memory models

Block 1 began with four assumptions about the machine. The fourth was stated once and not explained: there is one memory, and every read returns the value of the latest write before it in the interleaving. Lamport in 1979 called this property sequential consistency,5 and the language guarantees it for every program none of whose interleavings has a data race. Every argument since has used it: the exactness of the counter under the spin lock, the points of effect of this block. Even the lost update of the racy counter was explained by an interleaving, although that program is outside the guarantee, as this section's question shows. This section says what the assumption was.

The memory model's guarantee

It is a guarantee, and the one that gives it is the language's memory model: the part of a language's definition that says which values a read may return in a multi-threaded program. A processor and a compiler reorder a thread's reads and writes for speed, so that another thread may see them in an order other than their order in the program. The slide's example: thread 1 writes x = 1 and then y = 1; with the two writes swapped by the processor, thread 2 may read y as 1 and then x as 0, which no interleaving of the two threads' steps gives. Adve and Hill proposed the guarantee in 1990 as a contract between programs and hardware: a program that is free of data races may be run by a machine that reorders memory operations, and will still behave as if the memory were one sequence of operations.6 The literature calls this guarantee DRF-SC, sequential consistency for data-race-free programs. The languages took it over as a contract between programs and the language. Java, in chapter 17 of its specification, guarantees it for correctly synchronized programs, those none of whose interleavings has a data race.15 C and C++ guarantee it for programs that synchronize with mutexes and with default atomics only, atomic accesses that ask for the strongest ordering, under which all atomic accesses fall in one order that every thread sees the same.16 Rust's memory model is C++'s, with the same condition on its atomics.18 Go guarantees it in its memory model of 2022.17 OCaml 5 guarantees it on the model of Dolan, Sivaramakrishnan and Madhavapeddy.7,19

thread 1 thread 2 w x = 1 r y → 0 w y = 1 r x → 1 the interleaving: each read returns the latest write before it the guarantee holds for programs none of whose interleavings has a data race
One memory, one interleaving: each read returns the latest write before it.
thread 1 thread 2 w x = 1 w y = 1 swapped r y → 1 r x → 0 no interleaving gives this race-free programs still run as one sequence: Adve and Hill, 1990, DRF-SC
Why a guarantee: the two writes swapped by the processor, and a read of y = 1 followed by a read of x = 0, which no interleaving gives.

The condition is the one block 1 defined, with section 2's clause. A data race is two accesses to one location from two threads, with no synchronization between them, of which at least one is a write and at least one is a plain access. Synchronization is any of these orders: a lock's release before its acquire; a thread's start before its first step; a thread's last step before the join that waits for it; an atomic or volatile write before the read that sees it. In each case the order carries everything the first thread wrote before its release, its last step or its write. Program by program, this is what made the guarantee apply. The spin lock's program was race-free because test-and-set synchronizes, block 1's second guarantee of the instruction. What one thread did before releasing the flag is ordered before what the next thread does after acquiring it, provided the flag is released by an atomic write, as it is in block 1's spin lock. So no two threads access the plain counter inside the lock without that order between them. The count per thread was race-free because of the join. The compare-and-set loop and Treiber's stack were race-free because every access to the top is atomic. A node's fields are written only before the node is published through the top, and read only after the node was read from the top; the atomic write of the top and the read that sees it order the two. In each case the guarantee applied, every run behaved as some interleaving, and the reasoning by interleavings was sound.

the spin lock release: atomic write of the flag acquire: test-and-set synchronizes the count per thread the thread's last step the join synchronizes Treiber's stack the node built, then top written top read, then the node synchronizes every run behaved as an interleaving; the reasoning by interleavings was sound
What synchronizes in the session's programs: the release before the acquire, the last step before the join, the write of top before its read.

What a racy program gets

Block 1's unlocked reader is the program outside the contract. The transfers take their locks in a global order and are correct; the reader takes none.

Example 4 (d), Java: Accounts.java, the reader with no lock

// (d) the reader with no lock: broken on purpose, a data race
static int[] readUnlocked() {
  return new int[] { A.balance, B.balance };
}
$ java Accounts d
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

Example 4 (d), OCaml 5: accounts.ml, the reader with no lock

(* (d) The reader with no lock: broken on purpose, a data race. *)
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

What a racy program gets, language by language, from each language's own definition. A race is bounded in space when it affects no location but the one raced on, and bounded in time when it affects no access to that location before or after the racing ones.

  • C and C++: undefined behaviour, which means that the standard places no requirement on what the program does. The compiler may act on it: in the course's run a compiler at its usual optimization level removed a loop that waited on a plain flag, and the program read the data before the flag and printed the value from before the write.16
  • Java: the behaviour is defined, and bounded in space. A read returns a value that some thread wrote to that variable, never a value that no thread wrote, and the program's objects stay intact; but a race is not bounded in time, a race on one variable can affect later reads of it, and a long or double that is not volatile, a 64-bit value, may be read as one 32-bit half of one write and the other half of another, which the specification allows although most 64-bit machines do not do it.15,7
  • OCaml 5: the behaviour is defined, and bounded in space and in time. If no access to a location races during an interval of a run, meaning that every write to it by another thread is ordered before or after the interval by synchronization, then the accesses to it in that interval behave as in an interleaving, whatever races happen on other locations or at other times; this is the local data-race freedom of Dolan, Sivaramakrishnan and Madhavapeddy, and the manual's chapter lists the operations outside the guarantee.7,19
  • Go: like Java for one word, a read sees a preceding or concurrent write and nothing out of thin air; a race on a value of several words can corrupt memory arbitrarily; an implementation may also report the race and halt.17
  • Rust: no data race can be written in safe Rust. Ownership rejects a variable that two threads can reach while one changes it, unless a lock or an atomic stands between, and two marks on types, Send and Sync, say which values may be given to or shared with another thread; the guarantee assumes that the code marked unsafe underneath, where the check is off, keeps its guarantees. Deadlocks and race conditions remain: a race condition is a wrong result that depends on the order of events, with or without a data race, and the transfer in two halves is one.18

The reader's two reads are each a data race with the transfers' writes. The program compiles and runs with no warning, in Java and in OCaml. What does the language guarantee for this program?

  1. Nothing: a program with a data race has no defined meaning in any language.
  2. That every run is some interleaving of the threads' steps, since the transfers themselves are correctly locked.
  3. That the guarantee of an interleaving is off for this program; what is left depends on the language, and in Java and OCaml the damage is bounded.
The answer

The third answer. The guarantee holds for programs none of whose interleavings has a data race, and this one has; so nothing guarantees that a run is an interleaving. What is left is what each memory model says about a racy program, and that differs from language to language, as the list above says. The wrong sums inspected are of the kind an interleaving gives, the reader's two reads falling on either side of a transfer's two writes, so that the sum is off by one. Neither language guarantees even that: Java bounds a racy read only to some value once written to that variable, possibly an old one, and the two plain reads may be reordered; nothing worse showed in this run, on this machine, and the record does not say that every wrong sum was 199 or 201. No run can decide between the second and the third answer; the definition does. The first answer is true of C and C++ and false of Java, OCaml and Go. In OCaml the two reads of the tuple are evaluated in an order the language does not fix, which changes nothing here, since either order can fall around a transfer.

The languages also differ in how much control they give over the order of memory operations. An access mode is the strength of ordering that one read or write requests. C++ and Rust let the programmer choose an access mode for each atomic access. Java offers four access modes, from the weakest to the strongest: plain; opaque; release and acquire, one mode, release for writes and acquire for reads; and volatile. Each mode gives every guarantee of the mode before it, and more.20 OCaml offers two modes only: its plain fields, stronger than Java's plain mode since a race on them is bounded in time, and its atomics, which behave like Java's volatile.7 Go offers no choice: all its atomic operations have the strongest mode. These notes take the access modes no further.

Question 2 of the session's test-yourself page asks what the absence of data races guarantees, and the rest of this paragraph answers it. Provided that every atomic access uses the strongest mode, the absence of data races guarantees that every run behaves as some interleaving of the threads' steps. In Java the strongest mode is that of volatile fields and of the ordinary methods of the atomic classes (get, set and compareAndSet among them, which have the semantics of volatile accesses); in OCaml every atomic has it; in C, C++ and Rust it is the sequentially consistent ordering. The absence of data races guarantees nothing more: which interleaving is not fixed, so runs differ; locks taken in a cycle still deadlock; and a counter with a lock around each of its three steps has no data race and still loses updates.

What this section leaves open: a type system that checks more than the absence of data races, session 12.

8. Summary

The session's frame was one sentence: a multi-threaded program is a set of interleavings, and the paradigm question is what to do about them. Three answers, each a contract with an obligation, a progress risk and someone who checks.

The three contracts

The wayOn the slideContractObligationProgress riskWho checks
Mutual exclusionforbid the interleaving: the counter under a lock, the transfer, the bounded bufferoperations atomic by exclusion; linearizable by constructionevery access to the state under the lock; the invariant across all the state the operation touches; a global order of the locksdeadlock, starvation; a stopped holder stops every thread that waits for its locknot the language (Java, C, C++, Go); a race detector at run time, on the paths the run takes (Go's detector, ThreadSanitizer); the compiler (Rust, for data races only)
Atomic instruction with retrydetect it and redo: the counter on compare-and-set, Treiber's stackoperations atomic without exclusion; linearizable at a point of effectthe loop re-reads; the invariant; the point of effect namedthe loop is lock-free, not wait-free: a thread may retry for ever while the others keep completing operations; the one-instruction case, fetch-and-add, is wait-freethe programmer, by proof; the garbage collector removes ABA when no node is reused; checkers of histories at test time
Independence of the ordermake it irrelevant: the count per thread, the parallel folda deterministic final resultnothing shared while they run, and a combine without side effects that is associative with an identity, the parts combined in their order; or updates that commute, each applied as one step or to a replica of its own merged at the end; or determinism by constructionnone from interleaving; the join waits for every worker; the combine's costthat nothing is shared, the type system can (a pure function in Haskell; one owner per slot in Rust); that the combine is associative or the updates commute, the programmer only

The appendix compares nine languages by what the programmer expresses, who checks the discipline, what a data race costs and what is true by construction.

The session's question, the lab, the mini-project

Three questions apply to every multi-threaded program, whether or not its author asked them: which contract it chooses, how that contract is stated, and which obligation is left to the programmer. Under a lock, the obligation is that every access takes the lock and that the locks have an order. Under one instruction, that the loop re-reads and the point of effect is named and proved. Under independence, that nothing is shared while the threads run and the combine is associative, or the updates commute. The exit question of the session is this one, asked of an unfamiliar program.

The lab's warm-up is four classes in Java, each given with its contract and with a check, a small program that fails when the contract is broken. They are the counter in three versions; the workers, which start a number of threads over a task, join them and stop them through a flag; the bounded buffer as a monitor; and, as an extension, a barrier, a point in the program that every worker must reach before any goes on. Then a small ray tracer, a program that computes a picture pixel by pixel, is made multi-threaded with these structures, and each mistake shows in the picture. The thread that starts the workers owns them, in the sense that it is the one that joins them, which is not Rust's sense of the word; stopping them is a request, a flag that each worker reads and that ends nothing by itself, so that a task that never looks at the flag never stops. The mini-project rebuilds the bounded buffer as a queue three ways, with a lock, with two locks and without locks, behind one interface, with a checker of histories and a measurement.

What the session leaves open: no sharing at all, messages, session 8; transactions, snapshot isolation and the structures that merge replicas, session 9; types for concurrency, session 12.

Appendix

The material of this appendix lies outside the lecture's argument: nothing in sections 1 to 8 builds on it, and the lab does not need it. Its parts follow the appendix of the slides, in the same order, and each is reached by a link from the place in sections 1 to 8 whose slide points to it.

Wait-freedom and the clause on stopped threads

Wait-free: in every run, every thread that keeps taking steps inside an operation completes that operation within a finite number of its own steps, whichever other threads are stopped and whenever. Every wait-free structure is lock-free. On the slide's three threads, A stopped for good at a cross, B and C both complete.

thread A thread B thread C stopped, never scheduled again an operation returns if A may run, A finishes
Wait-free: B and C both complete. The ghost bar is a lock without the clause: if A may run, A finishes, which is why the clause is needed.

The clause "whichever threads are stopped" is what makes these conditions about progress rather than about one particular run. Without it, a lock would count as lock-free: if the scheduler lets the thread that holds the lock run, that thread finishes its operation. With the clause, a lock is not lock-free: stop the holder, and no operation ever completes, however many steps the others take. "Finitely many" is a bound that exists, not a small one: the condition rules out waiting for ever, not waiting long. In older papers, among them Michael and Scott's, "non-blocking" is used for what this block calls lock-free.12

Construction and progress

Two pairs of words keep one meaning each throughout the session. Lock-based and without locks say how a structure is built. Lock-free and wait-free say what progress it guarantees, and nothing else. A structure built without locks is not thereby lock-free, and a lock-based structure is never lock-free, since stopping the holder stops every waiter. The Disruptor is a queue over a ring buffer, an array used in a circle; its authors call it lock-free in the sense that its path has no lock. A thread that puts claims a slot and then publishes it. A putter stopped between the two steps stops every thread that takes, once that thread reaches the slot, and that is blocking.21 Three more terms describe how a structure is built; they are defined here so that the reader meets them with a meaning, and the lecture does not use them. A fine-grained structure has a lock per part, a node of a list for instance, where the coarse-grained one has one lock for the whole. An optimistic operation reads without a lock and checks, before writing, that what it read still holds. A lazy removal first marks an element as removed and only later takes it out of the chain.

non-blocking blocking lock-free wait-free lock-based without locks spin lock; synchronized impossible impossible the Disruptor the loop; Treiber's stack fetch-and-add the Disruptor
Construction against progress. A lock-based structure is never lock-free; a structure without locks may still block, the Disruptor.

The ABA problem

The ABA problem, and why it does no harm here. The ABA problem is this hazard: a thread reads the value A from a location, meanwhile other threads change the location to B and back to A, and the thread's compare-and-set, expecting A, succeeds although the structure it reasoned about has changed. Values do return to the top of this stack. Between a thread's read and its compare-and-set, other threads may push a node and pop it again, and the top is once more the very node the thread read, or the empty stack, null or [], once more. That return is harmless: the very same node, never changed, heads the very same chain, so a compare-and-set that succeeds against it is right. The harmful case is a different node at the same address. Java and OCaml, among other languages, have a garbage collector, the part of the runtime that frees memory no thread can reach any more. In such a language the harmful case, a different node at the same address, cannot arise for this stack: a node that any thread still holds a reference to is never freed, so its address is never reused, and every push allocates a fresh node. A thread whose read is stale then finds a new node at the top, not the one it read: its compare-and-set fails and it reads again, which is what the slide shows with the node 9. The garbage collector removes ABA for a structure that allocates a fresh node for every push and compares references. A program that reuses its own nodes, from a pool of its own, or whose compare-and-set compares numbers that stand for a structure, an index into an array for instance, meets ABA again, collector or not; Java's AtomicStampedReference, a reference paired with a counter, is the library's answer for that case. Without a collector, in C or C++, a popped node may be freed and its memory reused for a new node at the same address, and a pop whose read is stale meets two hazards. If the pop reads the next of its node after that node was freed, it reads freed memory: a use after free. If it read next before the frees, as thread 1 does in the figure, its compare-and-set, expecting the old address, finds the new node at that address, succeeds, and installs as the top a node that was freed: the stack is corrupted. Two techniques exist for that case, hazard pointers and epochs, and both delay the freeing of a node until no thread can still hold it.

thread 1, in pop thread 2 the stack after the event reads top = a, next = b top a b c pops a, pops b top c pushes a again top a c compare-and-set a → b: succeeds top b c b was popped: corrupted
The hazard, on a stack whose nodes are reused: thread 1 has read top = a and next = b; thread 2 pops a and b and pushes a again at the same address; thread 1's compare-and-set succeeds and brings back b, a node already popped.
thread 1, in pop thread 2 the stack after the event reads top = a, next = b top a b c pushes x top x a b c pops x top a b c same node a compare-and-set a → b: succeeds top b c right
On this stack: thread 2 pushes x and pops it; the same node a heads the same chain, and thread 1's compare-and-set is right.
thread 1, in pop thread 2 the stack after the event reads top = a, next = b top a b c pops a and b; not freed top c a and b still held by thread 1 pushes 9: a fresh node top 9 c a new address compare-and-set a → b: fails top 9 c right: thread 1 re-reads
With a collector: a and b are not freed while thread 1 holds them; the push gets a fresh node at a new address; thread 1's compare-and-set, expecting a, fails, and thread 1 reads again.
thread 1, in pop thread 2 the stack after the event reads top = a, next = b top a b c pops a and b: both freed top c a and b freed pushes 9 at a's address top 9 c the address a again compare-and-set a → b: succeeds top b c top = b, freed: corrupted
Without a collector: a and b are freed, the push reuses a's address, thread 1's compare-and-set succeeds, and top is b, freed memory.

Operations on the whole structure, and the progress guarantee

The operations on the whole structure. A structure whose nodes change in place has no instant at which the whole of it is unchanged by the other threads. The Java library's ConcurrentLinkedQueue, built on Michael and Scott's lock-free queue, documents three consequences. Its size needs a traversal of the whole queue and may report an inaccurate result if the queue is modified meanwhile, so it "is typically not very useful in concurrent applications". A traversal of its elements is weakly consistent: it shows no element twice and shows every element present from its start to its end, but may or may not show the elements added or removed meanwhile, so what it shows need not be the content of the queue at any one instant. And an operation on many elements at once, adding a whole collection for instance, is not atomic.13 Under a lock, size and iteration are one critical section each. A persistent structure behind one reference, Treiber's stack among them, does have such an instant, the read of the reference, which is why its size and its traversal are linearizable at that read; the price is the one paid at the single reference.

nodes changed in place top 7 4 9 5 size traverses while nodes change: no instant of the whole a persistent value behind one reference the read of the reference is a snapshot of the whole
Nodes changed in place: a traversal has no instant at which the whole is unchanged. A persistent value behind one reference has that instant, the read of the reference.

Where it wins. The progress condition is the point, not speed. A thread that holds a lock and is stopped stops every thread that waits for the lock. The holder may be stopped by the scheduler, by the operating system while the system brings in memory that the thread touched, or by waiting for a device inside its critical section. Block 1's Pathfinder, where a stopped holder held up a more urgent thread, is such a case. A thread stopped in the middle of a push on Treiber's stack stops nobody: it holds nothing, and every other push and pop goes on. Where a stopped thread must not stop the others, only a non-blocking structure, lock-free or wait-free, will do. The guarantee is the algorithm's, in the model where allocating a node is one step; the runtime underneath can still stop every thread, as a garbage collection does.

under a lock thread A thread B waits for A's lock, for ever without one thread A thread B nobody waits
The progress guarantee: a stopped lock holder stops every waiter; a thread stopped in mid-push stops nobody.

Whether every structure has a lock-free version

Yes, by a general construction, and the construction is slow. Herlihy proved in 1991 that compare-and-set is universal: with compare-and-set and a fixed, known number of threads, any object with a sequential specification has a wait-free, linearizable implementation.2 Herlihy ranks the instructions by their consensus number: the largest number of threads for which the instruction lets every thread agree on one value, wait-free. Reads and writes have consensus number 1. Test-and-set, fetch-and-add, and a stack or a queue shared by two threads have consensus number 2. Compare-and-set, and load-linked with store-conditional, have an infinite consensus number: they let any number of threads agree, which is what makes them universal. He also proved that with reads and writes alone not even a queue that two threads may both take from can be built, wait-free, and the same holds for a stack; the lock-free case follows, since the proof lets each thread do one operation. The construction is a proof, not a program. Each thread appends its operations, one after another, to one shared list of all the operations ever requested, and every thread applies that list, in the same order, to its own copy of the object. A thread that appends also appends the announced operation of the thread whose turn it is, and this help is what makes the construction wait-free rather than lock-free. So nothing runs in parallel, and, by the paper's own count, the construction needs memory cubic in the number of threads and a number of steps per operation that grows as a higher power of the number of threads. Michael and Scott state the consequence: implementations from general methodologies are "generally inefficient compared to specialized algorithms".12 The efficient structures each exploit something the general method cannot see. A queue has two ends, and Michael and Scott's queue lets a put and a take proceed on each end at once. A stack has cancelling pairs: in the elimination stack of Hendler, Shavit and Yerushalmi, a push and a pop that meet in a side array exchange the value and both complete without touching the stack, which is where the stack's parallelism comes from.11 A counter's additions commute, and section 5 shows what the Java library makes of that. No method yet derives an efficient lock-free structure from a sequential specification alone, and each fast structure is a paper of its own.

consensus number (Herlihy, 1991) ∞ compare-and-set; load-linked, store-conditional 2 test-and-set, fetch-and-add; a two-thread stack 1 reads and writes ∞: every object, wait-free; 1: not even a stack two threads share
Herlihy's consensus numbers: reads and writes 1; test-and-set, fetch-and-add and a two-thread stack 2; compare-and-set and load-linked, store-conditional every number.
the log of all operations op 1 op 2 op 3 op 4 op 5 CAS thread 1's copy thread 2's copy thread 3's copy append: one compare-and-set on the last node's next; every thread replays the log on its copy
The universal construction: one log of all operations, appended by one compare-and-set on the last node's next; every thread replays the log on a copy of its own.

What composes, and at what price

Locks compose by hand. One critical section around both steps, holding both locks, makes the transfer one operation; block 1 showed the cost, deadlock when two threads take the locks in opposite orders, and the repair, a global order of the locks. The obligation grows with every lock the operation touches.

lock A, lock B, in the global order withdraw from A deposit to B unlock B, unlock A one operation; the price: deadlock, and a global order of locks
Locks compose by hand: both locks around both steps, in the global order.

One compare-and-set covers one reference. Treiber's stack showed that the reference may stand for a whole persistent structure. With both accounts behind one reference to a persistent dictionary, from account names to balances, that is updated by building a new version, the transfer is one swap: it reads the dictionary, builds a new dictionary with both balances changed, and replaces the reference by compare-and-set. This transfer is correct and composes with every other operation on the dictionary, at the cost that every update of the dictionary now competes for that one reference and retries against every other. That cost is the cost of Clojure's atom of section 3. Compare-and-set on several words at once exists as a technique, multi-word compare-and-set, and OCaml 5 has a library for it; the lecture does not use it.26 Clojure's refs, references that only a transaction may change, are the way to have several references and still compose.

ref {A: 100, B: 100} {A: 90, B: 110} CAS the transfer: one compare-and-set every update of the dictionary competes for this one reference
One compare-and-set covers one reference: both accounts behind one reference to a persistent dictionary, the transfer one compare-and-set.

A transaction is a block of reads and writes on several locations whose writes take effect together, at one instant, or not at all. The runtime, the part of the language's implementation that runs along with the program, detects a conflict with another transaction and then discards the transaction's writes and runs it again. Software transactional memory, STM, is a runtime that provides transactions on a program's memory. What counts as a conflict differs between systems, and the difference matters below. Harris, Marlow, Peyton Jones and Herlihy state the contrast in their own words: "lock-based programs do not compose: correct fragments may fail when combined", whereas "transactions are compositional: small transactions can be glued together to form larger transactions", in sequence and, in their system, as alternatives, the second transaction tried when the first cannot proceed.8

atomically withdraw from A deposit to B both writes take effect here, or not at all on a conflict with another transaction, the runtime runs it again
A transaction: both writes take effect at one instant, or not at all; on a conflict the runtime runs it again.

Two observations, both from the course's runs. In Haskell, two threads ran the counter as a transaction, atomically $ modifyTVar' tv (+ 1), which adds one to the transactional variable tv inside a transaction, and the count was exact in ten runs of ten. That shows the step atomic, not yet composition. The compiler rejects a transaction that prints: "Couldn't match type ‘IO’ with ‘STM’", because a transaction may be run again and the type keeps irreversible actions out of it.23 Haskell's STM reruns a transaction when anything it read has changed, so every run is explained by running the transactions one at a time. In Clojure, the transfer is one transaction over two refs, (dosync (alter from - amount) (alter to + amount)), which subtracts from one ref and adds to the other inside one transaction. Eight threads made 800,000 transfers in both directions, and the total was 2000 at the end. A reader that took both balances inside one dosync never saw a total other than 2000 in 4,352,597 reads; a reader that took them outside any transaction saw a wrong total 5,345 times.14 That is composition: the two halves of the transfer appear to every reader inside a transaction as one step. The consistency belongs to the transaction, not to the refs. Clojure's transactions give snapshot isolation: every read in a transaction sees the state as it was when the transaction started, and the runtime runs a transaction again only when another transaction has committed a write to a ref that the first one also writes, or to a ref that the first one has read with ensure. A plain read of a ref, @r, is not checked for conflicts; (ensure r) reads the ref r and puts it under the same check as a ref that the transaction writes. Two transactions that each read both balances without ensure and each change a different one can then both commit, since neither writes or ensures a ref that the other writes. The resulting state is one that neither order of running the two transactions one after the other gives. That case, write skew, is session 9's; ensure on the ref that a transaction reads and does not write is Clojure's way to exclude it. The transfer here writes both refs, and the reader reads both inside one transaction, so neither meets it.

Clojure, eight threads, 800,000 transfers, the course's run a reader inside a transaction never wrong, in 4,352,597 reads a reader outside wrong 5,345 times Haskell: the counter under atomically exact, ten runs of ten
The course's run in Clojure: a reader inside a transaction never wrong, a reader outside wrong 5,345 times.

The languages

The table sets out what each language lets the programmer express, who checks the discipline, what a data race costs, and what is true by construction. The first five rows are section 7's; the last four are from the course's runs of the same counter in each language and from the languages' own documentation.

        
LanguageWhat the programmer expressesWho checks the disciplineWhat a race costsWhat is true by construction
Javalocks (synchronized, the library's locks), atomics with four access modes, volatile, join; all three waysnobody in the language or the JDK; a static analysis outside itthe behaviour is defined; a read sees a value written to that variable; bounded in space, not in time; long and double may teara correctly synchronized program runs as some interleaving; the objects stay intact15
OCaml 5Mutex, Condition, Atomic (plain fields and atomics, no modes between), Domain.join; all three waysnothing in the standard compiler; a compiler built with ThreadSanitizer, OCaml 5.2 and later, reports races at run time on the paths the run takesthe behaviour is defined; bounded in space and in timea race-free program runs as some interleaving, and in any program a location free of races during an interval behaves there as in an interleaving7,19
Rustownership; a Mutex<T> that owns its data; atomics with an ordering per access; thread::scopethe compiler, for data races only; not the lock order, not race conditionsa data race cannot be written in safe Rustshared or mutable, never both, unless a lock or an atomic stands between; a race-free program whose atomics use the strongest mode runs as some interleaving18
Gosync.Mutex, atomics, channels (session 8); sharing allowed, and the language's proverb, "share memory by communicating", advises against itthe race detector at run time, on the paths the run takesone word, like Java; several words, arbitrary memory corruption; the runtime may report and halta race-free program runs as some interleaving, since the memory model of 202217
C and C++std::mutex, std::atomic with an ordering per accessnobody in the language; ThreadSanitizer at run timeundefined behaviour: the compiler may remove a wait on a plain flaga race-free program that uses mutexes and default atomics only runs as some interleaving16
Haskellpure functions; mutation only in cells reached through a type that shows it (IORef and MVar in IO, TVar in STM); atomicModifyIORef'; transactions with atomicallythe type system: a pure function cannot mutate; a transaction cannot do I/Oa read then a write on an IORef from two threads is a data race and an atomicity violation at once, and loses updates as the racy counter does, in ten runs of ten; atomicModifyIORef' and a transaction were exactan ordinary value cannot change; a transaction takes effect as one step and transactions compose23
Erlangprocesses that share no heap and communicate by messages; sending a message copies its terms. The exceptions are the ETS tables (Erlang term storage), which several processes can read and write through the ETS library, and the arrays of the atomics module; both exist for speednothing between processes, which share no heap; on an ETS table, nobody checks a read followed by a writeno data race between processes; the counter as a process was exact; what remains is the atomicity violation: a protocol of two messages, a get then a set, lost about half the updates, and a shared table read then written loses them as Java doesa process's state is its own, and changes one message at a time22
Clojureimmutable values; an atom, one reference swapped by compare-and-set (swap!); refs with transactions (dosync); agents, references updated by functions queued to run one at a timenothing: the function given to swap! should be free of effects, and nothing enforces itthe function of swap! is run once per attempt, more than five times per swap under contention in the course's run; its effects repeatan atom's value is one immutable structure, replaced as a whole; a transaction sees a snapshot and its writes appear at one point14
JavaScriptworkers that receive copies; shared memory only through a SharedArrayBuffer; Atomics on itnothinga plain ++ on a shared array is the racy counter and loses updates, in twenty runs of twenty; Atomics.add does notwithout a shared buffer nothing is shared: a worker gets a copy of every message; one thread runs all of a worker's code24
 

Sources

  1. M. P. Herlihy and J. M. Wing, "Linearizability: A Correctness Condition for Concurrent Objects", ACM Transactions on Programming Languages and Systems 12(3), July 1990. PDF. The definition, and the locality theorem.
  2. M. Herlihy, "Wait-free synchronization", ACM Transactions on Programming Languages and Systems 13(1), January 1991, 124–149. PDF. The progress conditions; compare-and-set universal; the universal construction (section 4, its cost stated on page 143 as cubic in memory with a higher power in time); the queue and the stack impossible from reads and writes (section 3).
  3. M. Herlihy, "A methodology for implementing highly concurrent data objects", ACM Transactions on Programming Languages and Systems 15(5), November 1993. PDF. Lock-free and wait-free in those words; copy-and-swap for small objects, shared versions for large ones.
  4. R. K. Treiber, "Systems programming: Coping with parallelism", Technical Report RJ 5118, IBM Almaden Research Center, April 1986. Cited by Michael and Scott 1996 and by Hendler, Shavit and Yerushalmi 2004; no copy is online.
  5. L. Lamport, "How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs", IEEE Transactions on Computers C-28(9), September 1979. PDF. Sequential consistency.
  6. S. V. Adve and M. D. Hill, "Weak Ordering: A New Definition", ISCA 1990. PDF. The contract between data-race-free programs and hardware.
  7. S. Dolan, K. C. Sivaramakrishnan and A. Madhavapeddy, "Bounding Data Races in Space and Time", PLDI 2018. PDF. OCaml 5's memory model; Java bounded in space, OCaml in space and time; OCaml's atomics against Java's volatile.
  8. T. Harris, S. Marlow, S. Peyton Jones and M. Herlihy, "Composable Memory Transactions", PPoPP 2005. PDF. Transactions compose, lock-based operations do not.
  9. G. Kahn, "The Semantics of a Simple Language for Parallel Programming", Information Processing 74 (IFIP Congress), North-Holland, 1974, 471–475. Dataflow networks compute the same function in every schedule.
  10. D. Hendler, I. Incze, N. Shavit and M. Tzafrir, "Flat combining and the synchronization-parallelism tradeoff", SPAA 2010. PDF. One thread under a coarse lock performs every thread's request. On a Sun SPARC T2, from 1 to 64 threads: the flat-combining queue ahead of Michael and Scott's lock-free queue from about 4 threads on and 4 to 7 times faster at high thread counts (section 6.1, figure 2); the flat-combining stack up to 9 times faster than Treiber's (section 6.2, figure 4). The abstract claims better performance than fine-grained structures up to a certain concurrency level, beyond which, by section 1.1, a fine-grained structure wins.
  11. D. Hendler, N. Shavit and L. Yerushalmi, "A scalable lock-free stack algorithm", SPAA 2004. PDF. Treiber's stack described, its top a sequential bottleneck; elimination.
  12. M. M. Michael and M. L. Scott, "Simple, fast, and practical non-blocking and blocking concurrent queue algorithms", PODC 1996. General methodologies "generally inefficient compared to specialized algorithms".
  13. Java SE 21 API (the runs are Java 26; the sentences cited are unchanged there): ConcurrentLinkedQueue (size not constant-time and possibly inaccurate; weakly consistent iterators; bulk operations not atomic) and LongAdder (cells under contention; sum not an atomic snapshot), AtomicReference.updateAndGet (the function should be free of side effects, since it may be applied again when an update fails under contention), and Stream.reduce (an identity and an associative, non-interfering, stateless operation required).
  14. Clojure, Atoms (swap! retries in a spin loop; the function should be free of side effects) and Refs and Transactions (multiversion concurrency control with snapshot isolation). The counts of calls and of readings are the course's runs of 12 October 2026.
  15. The Java Language Specification, SE 21, chapter 17, Threads and Locks: correctly synchronized programs (17.4.5), no values out of thin air (17.4.8), non-atomic treatment of long and double (17.7).
  16. C++ working draft, [intro.races]: a data race results in undefined behaviour; the sequentially consistent subset. H.-J. Boehm and S. V. Adve, "Foundations of the C++ Concurrency Memory Model", PLDI 2008. The removed wait loop is the course's run of 12 October 2026.
  17. The Go Memory Model, go.dev/ref/mem, version of 6 June 2022: word-sized races see a preceding or concurrent write; multiword races may corrupt memory; an implementation may report and halt.
  18. The Rust Reference, Behavior considered undefined; the Rustonomicon, Data Races and Race Conditions. The per-thread count under thread::scope is the course's run of 12 October 2026.
  19. The OCaml manual 5.4, chapter 10, Memory model: the hard bits: data-race freedom gives sequential consistency; the bounds in space and time; the exceptions.
  20. D. Lea, Using JDK 9 Memory Order Modes; the VarHandle API: the four access modes, each defined in addition to the one below.
  21. M. Thompson, D. Farley, M. Barker, P. Gee and A. Stewart, "Disruptor: High performance alternative to bounded queues", LMAX, May 2011. PDF. A ring buffer whose authors say "lock-free" for "no locks"; a producer claims a slot and publishes it, and a stalled producer stalls the consumers (sections 3 and 4).
  22. Erlang: Concurrent Programming (processes share no data), Processes (messages are copied), ets (public tables). The counts are the course's runs of 12 October 2026.
  23. Haskell: Data.IORef and Control.Monad.STM. The two compiler errors and the ten runs are the course's runs of 12 October 2026.
  24. Node.js, worker_threads (workers share memory only through SharedArrayBuffer; other data is cloned); MDN, Atomics. The twenty runs are the course's runs of 12 October 2026.
  25. M. Herlihy and N. Shavit, "On the Nature of Progress", OPODIS 2011. The progress conditions stated with the clause on stopped threads; obstruction-freedom and the blocking counterparts.
  26. Kcas, an OCaml 5 library: the opam package kcas and its repository. Software transactional memory built on a lock-free multi-word compare-and-set.

The programs of examples 4, 6, 7 and 8 and their outputs are the course's own, run on 12 and 13 October 2026 in Java 26 and OCaml 5.4.0 on one machine; each output shown is one run.