CComputer Science, Built

Act VI · One Machine, Many Programs

Part 33 of 61

Concurrency

Degreestarts at this level49 min of film18 chaptersprerequisites: Part 10, Part 31, Part 32

Why do two threads that each add one to a counter raise it by only one, and what makes that impossible?

Four threads add ten million each to one counter on this machine and it ends at 10,547,788: an addition is a load, an add and a store, and they interleave. The part builds an exhaustive interleaving model checker and counts: of the 20 schedules of two increments, 18 lose one. Mutual exclusion is then built from plain reads and writes, with Peterson's lock proved and checked in 258 states, and the bakery for any number of threads. The part turns when the hardware reorders stores: under TSO the checker breaks Peterson in 10 steps, and one fence repairs it. Hardware locks from test-and-set to MCS, semaphores, monitors with Mesa semantics, and deadlock with the dining philosophers and the banker's algorithm follow. Two theories answer the reordering: memory models, where data-race freedom gives sequential consistency, and linearizability, with the Treiber stack, its ABA problem and Herlihy's consensus numbers, at whose top compare-and-swap implements every object. It ends with real bugs, from Therac-25 to the 2003 blackout, and with PebbleOS gaining threads, cas and amoadd: two threads of 2,000 plain increments end at 2,765 at quantum 500, and with amoadd or a lock always at 4,000.

What you need. Programming with threads in any language helps; the store buffer and MESI caches of Part 10 are assumed.

Mathematics, ideas and history
races, Peterson and the bakery, atomics, MCS locks, semaphores and monitors, deadlock, memory models, linearizability, lock-free, consensus numbers
What we build or compute
an interleaving model checker

What you will be able to do

Degree

  • List the interleavings of two short threads, find the ones that lose an update, and repair the race with a lock or an atomic instruction.
  • Write a bounded buffer with semaphores or a monitor, and explain why a condition is rechecked in a while loop.
  • Name Coffman's four conditions, find the cycle in a deadlock, and remove it with a lock order.

Graduate

  • Prove Peterson's lock safe by an invariant, and show the schedule that breaks it under TSO and the fence that repairs it.
  • Decide whether a history of a queue or a register is linearizable, and find the ABA schedule of the Treiber stack.
  • Explain by valency why registers cannot solve consensus for two threads, and show that test-and-set solves it for two and compare-and-swap for any number.

Research

  • State Herlihy's hierarchy and the universality of consensus, and what the Burns-Lynch bound says about mutual exclusion from registers.
  • Explain why linearizability checking is NP-complete and how state counts grow from SC to TSO to PSO, and state the open problems of weak-memory verification.

Industry

  • Choose between a mutex, an atomic, a channel and a lock-free structure for a shared object, from contention and measured cost per handoff.
  • Use a race detector, and say which bugs it cannot see: atomicity violations made of individually atomic steps.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Degree 22 min · Graduate 46 min · Research 49 min · Industry 26 min.

  1. 0Two threads, one counterDegree1 min
  2. 1Why concurrencyDegree2 min
  3. 2The raceDegree3 min
  4. 3Mutual exclusion from reads and writesDegree4 min
  5. 4Peterson meets the store bufferGraduate3 min
  6. 5Hardware locksGraduate3 min
  7. 6SemaphoresDegree3 min
  8. 7Monitors and condition variablesDegree2 min
  9. 8DeadlockDegree3 min
  10. 9Memory modelsGraduate4 min
  11. 10LinearizabilityGraduate3 min
  12. 11Lock-free structuresGraduate3 min
  13. 12Consensus numbersGraduate4 min
  14. 13Transactional memory, channels and actorsIndustry2 min
  15. 14Concurrency bugs in the wildIndustry2 min
  16. 15PebbleOS gains threads and CASDegree3 min
  17. 16Frontier: checking concurrent programsResearch3 min
  18. Recap, problems, and where this comes backAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

Two threads, one counterDegree1 min

Four threads on this machine share one counter, and each adds one to it ten million times. The answer should be forty million. The machine printed ten and a half million. Nearly three quarters of the additions vanished, and running it again gives a different number. With one thread, the answer is exactly right. Nothing is wrong with the processor. The program is wrong, in a way that no test of one thread can find.

Here is where an addition goes. In the machine, count equals count plus one is three instructions: load the count into a register, add one, store it back. Thread A loads zero. Before it stores, thread B loads zero too. A adds one and stores one. B adds one to its own stale zero, and stores one again. Two additions, and the count went up by one. A timer interrupt can switch threads between any two instructions, and on a multicore machine both threads run at once, so this happens all the time.

1Why concurrencyDegree2 min

There are two reasons to run more than one thing at once. The first is overlap. A server handling one request at a time spends most of its life waiting: for the disk, for the network. With two threads, while one waits, the other runs, and the same work finishes in seven units instead of twelve. That is Part 31's scheduler, used inside one program. The second is parallelism. Around 2005, processor clock rates stopped rising, and since then a faster computer means more cores, which only a program with several threads can use. Either way, several threads of control end up touching the same data.

Part 31 ran programs as processes, each with its own address space. Two processes share nothing unless they ask the kernel, through a pipe for instance. A thread is a second flow of control inside one process: its own registers and its own stack, but the same code, the same heap, the same page table. So every variable not on a stack is shared. On this machine, creating and joining a thread takes about forty microseconds; forking a process and waiting for it, about a hundred and eighty. Threads are cheap to make and cheap to communicate between, since a message is just a store. And, as the hook showed, easy to get wrong.

2The raceDegree3 min

How many ways can two threads interleave three instructions each? Draw it as a tree. At each step, either thread A or thread B takes its next instruction: left for A, right for B. Every path from the top to a leaf is one schedule, and each leaf shows the final count. There are six choose three, twenty schedules, one for each way to place A's three steps among the six. Only two of them give the right answer: the ones where one thread finishes before the other begins. The other eighteen lose an update. A test that runs the program a few times sees whichever schedules the hardware happens to pick.

Instead of hoping a test finds the bad schedule, we can try all of them. We wrote a small model checker. It takes a program written in a tiny assembly language, one list of instructions per thread. A state is where each thread is, what its registers hold, and what memory holds. A step lets one thread execute one instruction. Starting from the initial state, it explores every reachable state, breadth first, visiting each only once, so loops are fine. In each state it checks a property, such as: at most one thread is in its critical section. And because the search is breadth first, a violation comes with the shortest schedule that produces it. This is model checking, invented independently by Clarke and Emerson and by Queille and Sifakis around 1981, in its simplest form.

Here is what the checker finds as each thread does more increments. The number of schedules is a binomial coefficient, and grows exponentially: two point seven million for four increments each. But the number of distinct states grows only polynomially, under two thousand, because many schedules arrive at the same state, and the checker visits each state once. That is what makes model checking feasible. And it finds a surprise. With k increments each, the final count can be as low as two, whatever k is. Thread A loads zero and stalls; B does all but its last increment; A stores one, so B's last load reads one; then A finishes; and finally B stores two. Make the increment atomic, with a fetch-and-add instruction or a lock around the three steps, and the checker proves that only the right answer remains.

3Mutual exclusion from reads and writesDegree4 min

Suppose the hardware gave us only loads and stores. Could we still build a lock? A lock must guarantee three things. Safety: never two threads in the critical section. Progress: if some thread wants to enter, one does. And bounded waiting: nobody is passed over forever. The obvious attempt: wait until the other thread's flag is down, then raise your own. The checker breaks it in eight steps. Both threads look, both see the other's flag down, both raise their flags, both enter. Checking and acting are two separate steps, and the other thread can slip between them.

Gary Peterson found the simple answer in 1981. Each thread raises its flag: I want in. Then it sets the shared variable turn to the other thread: but you go first. Then it waits while the other thread wants in and it is the other's turn. If both want in at once, the one that deferred last waits, and the other enters. The first correct solution, Dekker's, which Dijkstra published in 1965, was far more complicated. Peterson's is four lines, and our checker finds no violation in any of the one thousand four hundred and eighty-seven states of two rounds.

Why does it work? Suppose both threads are in the critical section. Each wrote turn once on the way in. Say thread zero wrote it last, so turn is one from then on. Thread one raised its flag before writing turn, so before thread zero's write too. So after its write, thread zero read flag one equal to one, and turn equal to one, and it must have kept waiting. It could not have entered. That is a contradiction, so at most one thread is ever inside. Notice what the proof relies on: that each thread's own writes and reads happen in the order the program gives them. Remember that.

For any number of threads, Lamport's bakery algorithm of 1974 works like the ticket machine at a shop counter. To enter, take a number one larger than any number you can see. Then wait for every thread with a smaller number. Two threads can pick the same number if they choose at the same moment, so ties go to the smaller thread id. The choosing flag makes others wait while a thread is still reading the numbers, so nobody is judged by a number that is not yet written. It serves threads first come, first served, and Lamport showed it stays correct even if a read that overlaps a write returns any value at all. It needs no hardware atomicity whatsoever.

The checker can also show us the whole state space. Group Peterson's states by where each thread is: before the lock, flag raised, waiting, inside, or after. For one round each there are two hundred and fifty-eight states, and twenty-four of the twenty-five combinations occur. The one that never occurs is both inside. The checker confirms the bakery too, for two threads and for three, where it has over ninety thousand states. But there is a price. Burns and Lynch proved in 1980 that with only reads and writes, n threads need at least n shared variables. Real locks use a stronger instruction, and chapter five shows why that is not just a matter of convenience.

4Peterson meets the store bufferGraduate3 min

The proof assumed that each thread's writes and reads happen in program order. Real processors do not promise that. Each core puts its stores into a small store buffer, and lets them drain to memory later, so that a store never makes the core wait. The next load does not wait for the buffer: it reads memory directly. So core zero writes x, then reads y; core one writes y, then reads x. Both writes are still in the buffers, so both reads find zero. If instructions simply interleaved, one of the stores would have to come first, and at least one load would see a one. Part 10 ran exactly this test on this machine. Both loads read zero in most of a million runs, and never once with a fence between the store and the load.

Now give our checker the same store buffers. Under this model, called total store order, which is what x86 processors do, a store goes into a first-in, first-out buffer, and draining it is a separate step. The checker finds a schedule in ten steps. Thread zero raises its flag and sets turn, but both stores are still in its buffer. It reads flag one: zero, so it enters. Thread one does the same. Its own stores are buffered too, and it reads flag zero from memory, where it is still zero. Both are inside. The proof was right; its assumption was false. The fix is a fence after the two stores: an instruction that waits until the buffer has drained. On x86 that is m-fence, or any locked instruction.

Here is the whole picture. Under sequential consistency, Lamport's name for simple interleaving, Peterson is safe with no fences. Under total store order it breaks, and one fence before the loads repairs it. A weaker model, partial store order, lets stores to different addresses drain in either order. Now thread one's turn can reach memory before its flag, and Peterson breaks even with that fence. It needs a second fence, between the two stores. The same weakness breaks the most common pattern of all, message passing: write the data, then raise a flag. Under partial store order, a reader can see the flag and still read the old data. Arm and Power processors are weaker still, which is why every language now needs a memory model, the subject of chapter nine.

5Hardware locksGraduate3 min

Real locks use one atomic instruction, such as test-and-set, which writes a one and returns the old value in a single indivisible step. The core does it by holding the cache line in the modified state of Part 10's coherence protocol. The simplest lock spins on test-and-set. But every attempt is a write, so the cache line bounces from core to core even while the lock is held. Test and test-and-set spins on an ordinary read instead, which hits in the core's own cache, and tries the atomic only when the lock looks free. But at each release, every waiter misses and rushes at once. The ticket lock is a bakery in hardware: take a ticket with fetch-and-add, and wait for your number. It is fair, but each release invalidates every waiter's copy. And the MCS lock, from Mellor-Crummey and Scott in 1991, puts the waiters in a queue, each spinning on a flag in its own cache line. In every case, what contention costs is coherence traffic.

Here is the MCS queue. Each thread brings its own little node, with a locked flag and a next pointer. To wait, it swaps its node into the shared tail pointer, with one atomic exchange, and links itself behind the thread that was the tail. Then it spins on its own flag, which lives in its own cache line, so the spinning makes no traffic at all. To release, the holder writes zero into its successor's flag: one line, moved to one cache. The waiters are served in order. Linux's queued spinlocks, since 2015, are built on this idea.

We put these locks on Part 10's simulated caches, with a single bus that each transaction occupies for eight cycles, and counted. With test-and-set, the traffic per handoff grows with the number of cores, about two transactions per waiting core. Test and test-and-set is a little better, and the ticket lock better again, but both still grow linearly. The MCS lock stays flat at about seven, whatever the number of cores. With thirty-two cores, a test-and-set handoff takes over five hundred cycles, and MCS under sixty. And MCS serves the waiters in order, while test-and-set lets some cores win far more often than others.

And on this machine, which has four cores. Uncontended, the simplest lock is the fastest, seven nanoseconds, and MCS pays for its queue. With two or four threads fighting over one lock, everything is ten to thirty times slower, because the lock's cache line has to travel between cores on every handoff. With only four cores, MCS's advantage cannot show. The library mutex does best under contention here: it spins briefly, and then asks the kernel to put the thread to sleep, using Linux's fast user-space mutex, the futex.

6SemaphoresDegree3 min

Locks protect data. But threads also need to wait for each other: for an item to arrive, for space to free up. In 1965 Dijkstra proposed one primitive for all of it, the semaphore: a counter with two operations. P waits until the counter is positive, then decrements it, as one atomic step. V increments it, and wakes a waiting thread if there is one. Start it at one, and it is a mutex. Start it at n, and it counts n identical resources. Start it at zero, and it is a signal: one thread waits until another says go. The letters are Dutch, try and raise, and the waiting is done by the kernel, which puts the thread to sleep instead of letting it spin.

The classic use is the bounded buffer: producers put items into n slots, consumers take them out. Two counting semaphores do the waiting. Empty starts at n, and a producer does P on it before putting an item, so it waits when the buffer is full. Full starts at zero, and a consumer does P on it before taking, so it waits when the buffer is empty. Each side does V on the other's semaphore when it is done. A third semaphore, used as a mutex, protects the buffer itself. The checker confirms that the count of items always ends at zero. Remove the mutex, and the waiting still works, but the shared count is updated by load, add and store, and the checker finds final counts anywhere from minus two to two.

Semaphores can express almost any pattern of waiting. Readers and writers: many readers may share the data, but a writer needs it alone. The first reader to arrive locks the writers out, and the last to leave lets them in. But a steady stream of readers then starves the writers forever. Fixing that costs some of the readers' parallelism, and every real reader-writer lock chooses a point on that trade-off. Allen Downey's Little Book of Semaphores collects dozens of such puzzles, each a pattern that turns up in real systems. Yet semaphores fell out of favour. The P's and V's end up scattered across a program; forget one V and a thread sleeps forever; and nothing in the code says which data a semaphore protects.

7Monitors and condition variablesDegree2 min

Hoare in 1974, and Brinch Hansen, proposed a structure instead: the monitor. A monitor bundles shared data with a lock, and the language itself takes the lock around every operation, so it cannot be forgotten. For waiting, it has condition variables. Wait releases the lock and goes to sleep, as one atomic step, so no signal can be lost between them. Signal wakes one sleeper. This is Java's synchronized methods with wait and notify, and the condition variables of every threads library.

But there is a subtlety, and our checker finds it. A consumer takes the lock, finds the buffer empty, and waits. Written with if: one producer adds an item and signals. In Hoare's original monitors, the signal would hand the lock straight to the sleeper. But real systems, starting with Xerox's Mesa language in 1980, only make the sleeper runnable. In between, a second consumer can take the lock first, and take the item. When the first consumer finally runs, it does not look again, and takes from an empty buffer. The checker finds this in twenty-nine steps. Written with while, the consumer checks again after every wake-up, and the checker finds no violation at all. So the rule in every threads library is: wait in a while loop.

8DeadlockDegree3 min

Dijkstra's dining philosophers. Five philosophers sit at a round table with a fork between each pair. To eat, a philosopher picks up the fork on the left, then the one on the right, eats, and puts both down. The checker finds the problem in five steps: each philosopher picks up the left fork. Now each holds one fork and waits for the next, which its neighbour holds. The waits form a cycle, and nobody ever eats. The fix is to break the symmetry: let one philosopher pick up the right fork first. Then the forks are always taken in a fixed global order, a cycle is impossible, and the checker finds no deadlock in any of its three thousand states.

Coffman and his colleagues named the four conditions for deadlock in 1971. Mutual exclusion: a resource is held by one thread at a time. Hold and wait: a thread holds some resources while asking for more. No preemption: nobody can take a resource away. And circular wait: a cycle in the graph of who waits for whom. Deadlock needs all four, so preventing it means breaking one. The usual choice is the last: give every lock a place in a global order and always take them in that order. Linux even checks its own lock order as it runs, with a tool called lockdep.

Dijkstra also showed how to avoid deadlock without forbidding any pattern, by refusing dangerous requests. Each process declares in advance the most it may ask for. The system knows what each holds and what is free. A state is safe if there is some order in which every process can get what it still needs, finish, and return its resources. Here one exists. When P1 asks for one, zero and two, the system pretends to grant it and checks that a safe order remains. It does, so the request is granted. Later P0 asks for zero, two, zero. The resources are free, but granting them would leave no safe order, so P0 must wait. The banker's algorithm needs every maximum declared in advance, which real programs rarely know, so it lives mostly in textbooks and batch systems.

9Memory modelsGraduate4 min

Hardware is not the only thing that reorders. Here is a thread waiting for another to set a flag, written in plain C, with an ordinary int. And here is what the C compiler on this machine makes of it, with optimisation on. It loads done once. If it is not set, it jumps to a label that jumps to itself, forever. The compiler saw no write to done inside the loop, so it read it only once. That is perfectly legal, because a data race has no defined meaning, so the compiler may assume that no other thread writes the flag. Declare the flag atomic, and every pass of the loop must load it again. The same model tells both the processor and the compiler what they may not do.

Every modern language answers the question of what a load may return with the same idea. Within a thread, operations are ordered by the program. Between threads, certain pairs synchronize: an unlock of a mutex, and a later lock of the same mutex. Happens-before is the order you get by following both kinds of arrow, transitively, Lamport's idea from 1978 that Part 38 uses between computers. Here the write of data happens before the read. A data race is two accesses to the same variable, at least one a write, that happens-before does not order. The hook's counter is full of them.

Modern memory models rest on one bargain. Take the store-buffering test. With its races, total and partial store order allow an outcome that sequential consistency forbids: both loads read zero. Now put every shared access under a lock. The checker finds that under all three models, exactly the same outcomes remain, the sequentially consistent ones. Sarita Adve and Mark Hill made this a theorem in 1990. If a program has no data races in any sequentially consistent execution, then the hardware may reorder as much as it likes, and the program will still behave as if executed in sequence. So the programmer's side of the bargain is: no data races. The other side, for the hardware and the compiler, is to put the right fences at every lock, unlock and atomic operation.

Languages give programmers atomic variables to synchronize with. Here the writer stores the data, then sets a flag with release ordering: nothing before the release may be moved after it. The reader loads the flag with acquire ordering: nothing after it may be moved before it. When the acquire reads the value the release wrote, the two synchronize, and the data is guaranteed to be there. This is chapter four's message passing, repaired. Java adopted such a model in 2005, and C and C plus plus in 2011, after work by Hans Boehm and Sarita Adve. In C plus plus, a data race is undefined behaviour: the program has no meaning at all. And one problem is still open. With the weakest, relaxed atomics, the formal models seem to allow a value to appear out of thin air, justified by a circular argument, though no real machine produces one. Nobody has yet found a definition that forbids it without forbidding useful optimisations too.

10LinearizabilityGraduate3 min

A lock makes a queue correct by making every operation happen one at a time. But what does correct mean for a queue with no lock, where operations overlap? Draw each operation as an interval, from the moment it is called to the moment it returns. Here thread zero enqueues x while thread one enqueues y, and thread two's dequeue overlaps them and returns y. Herlihy and Wing's answer, in 1990: the history is linearizable if each operation can be given a single instant inside its own interval, such that, in the order of those instants, the operations make sense for an ordinary sequential queue. Here they can. Put enqueue y first, then enqueue x, then the dequeue of y, then the dequeue of x. Operations that overlap may be ordered either way; operations that do not overlap must keep the order in which they really happened.

Now a history that is wrong. Here enqueue x finishes before enqueue y even starts, so any explanation must put x first. Then the first dequeue must return x. It returned y. No choice of instants can explain this, and our checker, which tries every order the intervals allow, reports that there is none. Linearizability has a property that makes it the standard: it is local. If each object in a system is linearizable, the whole system is, so each object can be built and checked on its own.

Linearizability is stronger than the sequential consistency of chapter four. For an object, sequential consistency asks only for some order of all the operations that respects each thread's own order. Here thread zero's enqueue finishes before thread one's dequeue begins, yet the dequeue reports an empty queue. Put the dequeue first and the order is legal, so the history is sequentially consistent. But linearizability also respects real time: the enqueue had finished, so the dequeue must see it. Not linearizable. The difference matters. Herlihy and Wing showed that sequential consistency is not local: two queues, each sequentially consistent on its own, can together produce a history that no order explains.

Our checker does this for any history. It is Wing and Gong's search from 1993: pick an operation that could go next, apply it to the sequential object, and backtrack if its result disagrees, remembering combinations already ruled out. On histories from a correct queue, stack, register or counter, every one is linearizable. When three answers in ten may be stale, the checker rejects about a third of the queue histories and nearly every counter history. The rest either contain no stale answer, or have one that another order happens to explain. And the cost is the catch. For eighty operations the median search is ten thousand steps, but a quarter of the histories run past three hundred thousand, where we gave up. Chapter sixteen explains why that is not our fault.

11Lock-free structuresGraduate3 min

With an atomic compare-and-swap, a stack needs no lock at all. Kent Treiber described this one at IBM in 1986. To pop, read the top, read the node below it, and then, with one compare-and-swap, change top from the node you read to its successor. If another thread changed top in the meantime, the compare-and-swap fails, and you simply try again. This is lock-free: at any moment, some thread is making progress, and a thread that is descheduled halfway through holds nothing that others wait for. A thread holding a lock, descheduled, blocks everyone.

But the checker finds a flaw, the famous ABA problem. Thread one starts a pop. It reads top, A, and A's successor, B, and then it is descheduled. Thread two pops A, pops B, and then pushes A back, reusing the node, as a memory allocator would. The stack is now A, then C. Thread one wakes, and its compare-and-swap checks that top is still A. It is, so it succeeds, and sets top to B. But B was popped by thread two, which may be using it for something else entirely. The stack is corrupted. The checker found the schedule. The compare-and-swap compares values, and the value came back, so it cannot see that everything underneath has changed.

There are several cures. Tag the pointer with a version number that every successful compare-and-swap increments. Then a top that comes back is still different. Our checker confirms that the tagged stack is never corrupted. Underneath ABA is a harder problem: when is it safe to free a node another thread might be reading? Hazard pointers let each thread announce the nodes it is reading, so nobody frees them. Epochs free a node only after every thread has passed a point where it could still hold one. And read-copy-update, used more than ten thousand times inside Linux, lets readers take no lock at all: a writer copies the data, publishes the new version, waits for every reader that might see the old one, and only then frees it. The Michael and Scott queue of 1996 applies the same ideas to a queue, and Java's concurrent queue is built on it. These designs are classified by the progress they guarantee: wait-free, the strongest, means every thread finishes in a bounded number of its own steps.

12Consensus numbersGraduate4 min

Maurice Herlihy asked in 1991 which atomic instructions are more powerful than others, and found an exact answer through one problem: consensus. Each of n threads proposes a value and must decide one. All must decide the same value, and it must be one of the proposals. And it must be wait-free: each thread decides within a bounded number of its own steps, even if the others stop. No locks. With test-and-set, two threads can do it: write your proposal where the other can see it, then test-and-set a flag. The winner decides its own value, and the loser decides the winner's. The checker confirms agreement. But with three threads, a loser knows only that it lost, not which of the other two won, and the checker finds disagreement. Compare-and-swap does it for any number: the first to swap its value into an empty decision wins, and everyone reads the decision.

This gives every object a number: the most threads for which it can solve wait-free consensus. Plain reads and writes: one. They cannot even solve it for two. Test-and-set, swap, fetch-and-add, and even atomic queues and stacks: exactly two. Some exotic objects sit at numbers in between. And compare-and-swap, or the load-linked and store-conditional pair of Arm and RISC-V: infinity. The ladder is strict. No object can implement one with a higher number, wait-free, however clever the program. And at the top, Herlihy proved universality: with consensus for n threads, you can build a wait-free implementation of any object at all for n threads. That is why every modern processor provides compare-and-swap or its equivalent.

How can consensus build any object at all? Keep a log of operations, one slot after another. To perform an operation, a thread proposes it for the next empty slot, and the threads run consensus to agree on which proposal fills that slot. Every thread can then replay the agreed log, in order, on its own private copy of an ordinary sequential object, and so knows the state and the answer to its own operation. A thread that keeps losing could starve, so winners also help: they propose operations that others announced but have not yet placed. That makes it wait-free. It works for every object, which is the point of the theorem. It is also slow, with work growing with the number of threads, so it is a proof of possibility rather than a recipe.

Why can't reads and writes solve consensus for two threads? The proof is a beautiful argument about valency. Call a state bivalent if both decisions are still possible from it. Some initial state must be bivalent, because which proposal wins depends on the schedule. Follow bivalent states as far as possible, and you reach a critical state, where thread zero's next step would make the decision zero, and thread one's next step would make it one. But those steps are reads or writes. Two reads, or steps on different registers, commute, so the order cannot matter. If one is a write that overwrites the other's, then a thread running on alone afterwards sees the same memory in both cases and must decide the same way. Either way, a contradiction. Our checker shows it on one natural protocol: write your proposal, read the other's, take the smaller one seen. Some schedule makes them disagree. The same argument, applied to messages and crashing computers, is the famous impossibility result of Fischer, Lynch and Paterson, which Part 38 meets.

13Transactional memory, channels and actorsIndustry2 min

What if we could mark a block of code atomic, and let the hardware make it so? That is transactional memory, proposed by Herlihy and Moss in 1993. The block runs speculatively, its writes kept private, and commits all at once at the end. If another core touches any of its cache lines in the meantime, the coherence protocol notices, and the transaction aborts and starts again. This machine has Intel's version. We ran a million tiny transactions, and all but seventy-three committed. But hardware transactions have had a hard life. A bug forced Intel to disable them on its 2014 processors; in 2019 they turned out to leak data, and were switched off by default; and Intel's consumer processors no longer have them. And a transaction can abort forever, say because its data does not fit in the cache, so every use still needs an ordinary lock as a fallback.

Another answer is to stop sharing memory. In Hoare's communicating sequential processes, from 1978, processes share nothing and meet only on channels: a send waits for a matching receive. Go's channels come straight from it. In Hewitt's actors, each actor owns its state and a mailbox, and handles one message at a time. Erlang, built at Ericsson for telephone switches, runs millions of them. And async and await interleave many tasks on one thread, switching only at the points the programmer marks, which makes most races impossible. Go's proverb puts it well: do not communicate by sharing memory; share memory by communicating. Data races disappear. Deadlock does not: two actors can each wait for a message from the other forever.

14Concurrency bugs in the wildIndustry2 min

Races are not just lost increments. The Therac-25 radiation therapy machine, in the mid nineteen-eighties: an operator who edited the treatment settings quickly could race the software task that configured the beam, and the machine delivered massive overdoses. Six patients were harmed, and Nancy Leveson's investigation became required reading for engineers. Mars Pathfinder, which Part 31 met: priority inversion through a shared lock, and a rover that kept resetting itself. And in 2003, a race in the alarm software of an Ohio power company silenced its alarms; operators did not see the failures spreading, and fifty million people lost power. What these share: schedules too rare to show up in testing, and certain to occur in years of operation.

Tools now catch many of these. Here is ThreadSanitizer, built into the C compiler, run on the hook's program on this machine. It reports a data race on count, on line four, between a read in one thread and a write in another. It works by keeping a vector clock for every thread and every variable, Lamport's happens-before relation made concrete, which Part 38 builds. Two accesses that the clocks do not order are a race. But notice what happens if we make count an atomic variable and keep the same code. ThreadSanitizer is silent, because every load and every store is now atomic. And the program still loses updates: it printed one point two million, out of two million. Using the atomic increment, plus-equals, gives exactly two million. So a detector finds data races, not every race: atomic steps can still be combined wrongly, and only reasoning, or a model checker, finds that. Detectors go back to Eraser in 1997. Go has one built in, and Rust's type system rejects data races before the program even runs.

15PebbleOS gains threads and CASDegree3 min

Our own machine needs two things to run this part's programs. The first is an atomic instruction. Compare-and-swap: load the word at the address, and if it equals the expected value in rd, store the new value; either way, rd receives what was there. And atomic add, for counters: load, add, store, and return the old value. They take the two opcodes that Part 6 left reserved, and each is a single step of the machine, so nothing can come between its load and its store. A real core does that by holding the cache line in the modified state for both halves. And under Part 32's memory-management unit, they translate and fault exactly like ordinary loads and stores.

The second thing is threads. In PebbleOS a thread is simply another process control block whose page-table root is the same as its parent's, with its own stack pages. The kernel needed no change at all: switching between two threads just reloads the same page table. And here is a lock built on the new instruction. Compare-and-swap the lock from zero to one. If the old value was not zero, someone holds it: count the failure, and yield the processor instead of spinning, since on one core the holder cannot release it while we spin. Unlocking is an ordinary store of zero.

Now the hook's experiment on our own machine: two threads, each adding one to a shared counter two thousand times, under three timer quanta. With load, add and store, the count comes out short at quanta of five hundred and three thousand, whenever the timer interrupt lands between a thread's load and its store. At ninety-seven instructions it happens, by luck of the arithmetic, never to land there, and the answer is right. With the atomic add, or with the compare-and-swap lock, the answer is always four thousand. The lock is not free: at quantum five hundred it costs nearly three times the instructions, with every failed attempt a yield. And notice the lucky quantum. A test that happens to pass proves very little; the race only needs the right schedule, which is why chapter two's checker tries them all.

How lucky was that quantum of ninety-seven? We ran the racy counter under seventy-five more quanta. Every one of them loses updates. The count ends between about two thousand six hundred and three thousand, never four thousand. The losses are large because one badly timed preemption loses everything the other thread did between the load and the store: a whole quantum's worth of increments, overwritten at once. And the sawtooth comes from where, inside the five-instruction loop, each timer interrupt happens to land, which shifts steadily as the quantum grows. Ninety-seven was a fluke of that arithmetic.

16Frontier: checking concurrent programsResearch3 min

The first frontier is checking. Our linearizability checker's search grows quickly with the length of the history. The median stays modest, but the worst of twenty random queue histories hits our limit of three hundred thousand steps by sixty operations. This is not a weakness of our code. Gibbons and Korach proved in 1997 that deciding linearizability is NP-complete. There are tractable special cases. With a fixed number of threads it is polynomial, and for queues and stacks whose values are all distinct, Bouajjani and his colleagues showed that a few small bad patterns explain every violation. The testers used on real databases, Knossos and Porcupine, survive by splitting a history by key and by time.

The second frontier is weak memory. Store buffers multiply the state space: two rounds of Peterson's algorithm have under fifteen hundred states under sequential consistency, and sixty-one thousand under partial store order. With buffers of unbounded size, Atig and colleagues proved in 2010 that checking reachability under total store order is decidable, but with a complexity beyond any tower of exponentials; for the Power and Arm models it is harder still. Practical tools avoid exploring equivalent orders, by stateless model checking with partial-order reduction, and the best, such as GenMC, now handle the C and C plus plus model. Checking a whole kernel or a lock-free library on Arm's real model remains out of reach.

The third frontier is the price of the strongest guarantees. Attiya and colleagues proved in 2011 that linearizable sets, queues and counters cannot avoid an expensive fence or atomic instruction in some operation: the cost of chapter five is a law, not an engineering failure. Wait-free structures were long thought too slow for practice, until Kogan and Petrank paired a lock-free fast path with a wait-free slow path taken only by a starving thread. Herlihy's universal construction proves that anything can be made wait-free, but its cost grows with the number of threads. And testing can come with guarantees: the PCT scheduler of Burckhardt and colleagues assigns random priorities, and finds any bug that needs d ordering constraints with a probability that can be computed in advance.

Recap, problems, and where this comes backAll tracks3 min

What we built in this part. A model checker that tries every interleaving, and the race it finds in one line of code. Peterson's lock, proved, then broken by store buffers and repaired with fences. Spin locks and the coherence traffic they cost, semaphores, monitors and deadlock. Memory models and the data-race-free bargain, linearizability, and lock-free structures with their ABA trap. Herlihy's hierarchy, with compare-and-swap at the top. And PebbleOS, with threads and an atomic instruction.

Where this comes back. Part 34 faces the cousin of the race: a crash in the middle of a write. Part 35's databases turn locks into transactions. Part 38 asks this part's consensus question between computers that can fail, and meets Fischer, Lynch and Paterson. Part 39 weakens consistency deliberately, for speed. Part 54 builds the verification methods we used informally here, and Part 59 the theory of distributed computation.

In practice. Share less: pass messages, use immutable data, give each object one owner. When you need locks, write down one lock order, hold them briefly, and never call unknown code while holding one. Wait on condition variables in a while loop, or better, use the library's queues and channels. Use sequentially consistent atomics unless you can prove the weaker ones correct. And run a race detector in every test, and a model checker on the small, tricky core.

Six problems, with full solutions in the part's notes. Pause on any of them. The fifth is a build problem: give PebbleOS the futex system calls, and a mutex that sleeps instead of yielding. The last, marked with a star, is a research problem: finding the fewest fences that make a program correct on a weak memory model, with our checker as the oracle.

Next time, Part 34: Storage. Memory forgets when the power goes, so data must live on spinning disks or in flash that wears out. Disks and flash, measured; file systems; and the crash that cuts an update short between two of its writes, with the journals, logs and copy-on-write trees that survive it. PebbleOS gets a disk and a file system. Part 34, Storage.

The books and papers this part follows are on screen and in the notes. Thank you for watching.

Where it goes next. Part 34 faces the cousin of the race, a crash in the middle of a write, and Part 35's databases turn locks into transactions. Part 38 asks the consensus question between computers that can fail and meets Fischer, Lynch and Paterson; Part 39 weakens consistency deliberately. Part 54 builds the verification methods used informally here, and Part 59 the theory of distributed computation.

Key results

The part's results in one place, for revision.

Interleavings of two threads\(\displaystyle \binom{6k}{3k}\ \text{schedules};\quad\allowbreak 2\le\text{final }\allowbreak \text{count}\le 2k\ \ (k\ge 2\text{ increments }\allowbreak \text{each})\)
Peterson's lock\(\displaystyle \text{flag}_i\leftarrow 1;\ \ \text{turn}\leftarrow j;\ \ \text{wait }\allowbreak \text{while }\text{flag}_j\wedge\text{turn}=j\)
Coffman's conditions\(\displaystyle \text{deadlock}\Rightarrow\text{exclusion}\wedge\text{hold-and-wait}\wedge\text{no }\allowbreak \text{preemption}\wedge\text{cycle}\)
DRF implies SC\(\displaystyle \text{no }\allowbreak \text{data }\allowbreak \text{race }\allowbreak \text{in }\allowbreak \text{any }\allowbreak \text{SC }\allowbreak \text{execution}\ \Rightarrow\ \text{only }\allowbreak \text{SC }\allowbreak \text{behaviours}\)
Linearizability\(\displaystyle \exists\text{ a }\allowbreak \text{legal }\allowbreak \text{sequential }\allowbreak \text{order }\allowbreak \text{that }\allowbreak \text{keeps }\allowbreak \text{every }\allowbreak \text{real-time }\allowbreak \text{precedence}\)
Consensus numbers\(\displaystyle \text{registers }1,\quad\allowbreak \text{test-and-set, }\allowbreak \text{queues }2,\quad\allowbreak \text{compare-and-swap }\infty\)

Try it

Lab 33 · Every schedule of a race, and a lock that the store buffer breaks

Run the part's model checker on two threads that each add one to a counter k times: count the schedules and the final values, and check them against a brute-force enumeration and a random scheduler. Then ask the checker whether Peterson's lock keeps mutual exclusion under SC, TSO and PSO, with and without fences.

Figure produced by Lab 33: Every schedule of a race, and a lock that the store buffer breaks
Produced by the lab below, seed 0, in 0.4 s.
python -m videos.cs.labs 33 needs numpy, scipy, matplotlib · download lab33.py · source on GitHub
k = 1: 20 schedules                          2 end at 2, 18 at 1   (the film: 2 and 18)
k = 2: 924 schedules, by final count         2: 702   3: 216   4: 6
schedules against states, k = 1..4           20 / 22   924 / 138   48,620 / 585   2,704,156 / 1,846
k = 3, 20,000 random schedules: finals seen  2: 254   3: 12634   4: 6473   5: 630   6: 9   (possible: 2..6)
Peterson under SC                            no fence: safe   one fence: safe   two fences: safe
Peterson under TSO                           no fence: broken in 10 steps   one fence: safe   two fences: safe
Peterson under PSO                           no fence: broken in 10 steps   one fence: broken in 18 steps   two fences: safe
five philosophers                            deadlock after 5 steps; one reversed: none in 3,216 states

Testing samples schedules; the checker visits every state. Two plain increments are almost never safe, and Peterson's proof holds only while stores reach memory in program order.
The code (126 lines; it asserts its own result)
"""Lab 33: enumerate every interleaving of two racing increments, then break and repair Peterson's lock."""

from videos.coursekit import labs  # noqa: I001  (first, so the library imports without manim)

import itertools
from collections import Counter
from math import comb

import numpy as np

from explainer.cs.conc import mc

TITLE = "Every schedule of a race, and a lock that the store buffer breaks"
GOAL = ("Run the part's model checker on two threads that each add one to a counter k times: count the schedules "
        "and the final values, and check them against a brute-force enumeration and a random scheduler. Then ask "
        "the checker whether Peterson's lock keeps mutual exclusion under SC, TSO and PSO, with and without fences.")
TASKS = [
    "Use mc.counter(3, 1): three threads, one increment each. How many schedules are there, and which finals occur?",
    "Explore mc.naive_flags(1) with the mutex invariant and print r.trace(r.violation). Which eight steps break it?",
    "Check mc.bakery(2, 1) under 'tso' with and without fence=True. Does Lamport's bakery need the fence too?",
]
STEPS = ("ld", "add", "st")


def final_count(order):
    """Run one interleaving by hand: `order` lists which thread takes each step; every increment is ld, add, st."""
    c, reg, pc = 0, [0, 0], [0, 0]
    for t in order:
        step = STEPS[pc[t] % 3]
        if step == "ld":
            reg[t] = c
        elif step == "add":
            reg[t] += 1
        else:
            c = reg[t]
        pc[t] += 1
    return c


def brute_force(k):
    """Every way to interleave two threads of 3k steps each, by choosing which positions thread 0 takes."""
    n = 6 * k
    out = Counter()
    for where in itertools.combinations(range(n), 3 * k):
        order = [1] * n
        for i in where:
            order[i] = 0
        out[final_count(order)] += 1
    return dict(out)


def run(seed=0):
    rng = np.random.default_rng(seed)
    lab = labs.Lab()

    def count(s, prog):
        return dict(zip(prog.vars, s[2]))["c"]

    # 1. counter++ twice (Chapter 2): schedules, states and outcomes
    table = {}
    for k in (1, 2, 3, 4):
        prog = mc.counter(2, k)
        table[k] = (mc.schedules(prog, project=count), mc.explore(prog, project=count).states)
        assert sum(table[k][0].values()) == comb(6 * k, 3 * k), "C(6k, 3k) schedules"
        assert min(table[k][0]) == (1 if k == 1 else 2), "for k >= 2 the count can end as low as 2"
    one, two = table[1][0], table[2][0]
    lab.row("k = 1: 20 schedules", f"{one[2]} end at 2, {one[1]} at 1   (the film: 2 and 18)")
    assert one == {2: 2, 1: 18} and one == brute_force(1)
    lab.row("k = 2: 924 schedules, by final count", "   ".join(f"{c}: {n}" for c, n in sorted(two.items())))
    assert two == brute_force(2), "the checker agrees with the brute-force enumeration"
    lab.row("schedules against states, k = 1..4",
            "   ".join(f"{sum(table[k][0].values()):,} / {table[k][1]:,}" for k in (1, 2, 3, 4)))
    assert [table[k][1] for k in (1, 2, 3, 4)] == [22, 138, 585, 1846]
    for how in ("fai", "lock"):
        assert set(mc.explore(mc.counter(2, 3, how), project=count).finals) == {6}, how

    # 2. a random scheduler sees only part of what the checker proves possible
    seen = Counter()
    for _ in range(20000):
        order = rng.permutation([0] * 9 + [1] * 9)
        seen[final_count(order)] += 1
    possible = table[3][0]
    lab.row("k = 3, 20,000 random schedules: finals seen", "   ".join(f"{c}: {n}" for c, n in sorted(seen.items()))
            + f"   (possible: {min(possible)}..{max(possible)})")
    assert set(seen) <= set(possible) and seen[6] / 20000 < 0.01, "almost every schedule loses an update"

    # 3. Peterson under three memory models (Chapters 3 and 4)
    verdict = {}
    for model in ("sc", "tso", "pso"):
        for fence in (False, True, "both"):
            r = mc.explore(mc.peterson(fence, 1), model, mc.mutex)
            verdict[model, fence] = (r.violation is not None, len(r.trace(r.violation)) if r.violation else 0, r.states)
    names = {False: "no fence", True: "one fence", "both": "two fences"}
    for model in ("sc", "tso", "pso"):
        lab.row(f"Peterson under {model.upper()}", "   ".join(
            f"{names[f]}: " + (f"broken in {verdict[model, f][1]} steps" if verdict[model, f][0] else "safe")
            for f in (False, True, "both")))
    assert not verdict["sc", False][0] and verdict["sc", False][2] == 258
    assert verdict["tso", False][:2] == (True, 10) and not verdict["tso", True][0]
    assert verdict["pso", True][0] and not verdict["pso", "both"][0]

    # 4. the dining philosophers (Chapter 8)
    dead, fixed = mc.explore(mc.philosophers(5, False)), mc.explore(mc.philosophers(5, True))
    lab.row("five philosophers", f"deadlock after {len(dead.trace(dead.deadlocks[0]))} steps;"
                                 f" one reversed: none in {fixed.states:,} states")
    assert dead.deadlocks and not fixed.deadlocks
    lab.note = ("Testing samples schedules; the checker visits every state. Two plain increments are almost never "
                "safe, and Peterson's proof holds only while stores reach memory in program order.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    for k, c in ((1, labs.GREY), (2, labs.BLUE), (3, labs.GOLD), (4, labs.RED)):
        sch = table[k][0]
        total = sum(sch.values())
        lost = sorted(2 * k - f for f in sch)
        ax[0].plot(lost, [sch[2 * k - m] / total for m in lost], "o-", color=c, label=f"k = {k}: {total:,} schedules")
    ax[0].set(title="Two threads, k increments each: updates lost", xlabel="updates lost (2k − final count)",
              ylabel="fraction of schedules")
    ax[0].legend()
    ks = [1, 2, 3, 4]
    ax[1].plot(ks, [comb(6 * k, 3 * k) for k in ks], "o-", color=labs.RED, label="schedules: C(6k, 3k)")
    ax[1].plot(ks, [table[k][1] for k in ks], "o-", color=labs.GREEN, label="states the checker visits")
    ax[1].set(title="Why the checker searches states, not schedules", xlabel="increments per thread k", yscale="log",
              xticks=ks)
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Use mc.counter(3, 1): three threads, one increment each. How many schedules are there, and which finals occur?
  2. Explore mc.naive_flags(1) with the mutex invariant and print r.trace(r.violation). Which eight steps break it?
  3. Check mc.bakery(2, 1) under 'tso' with and without fence=True. Does Lamport's bakery need the fence too?

Problems, with solutions

Try each problem before opening its solution.

  1. The counter's minimum. Prove that two threads each doing k ≥ 2 increments, load-add-store, can leave the counter at 2, and never below 2.

    Solution

    Every store writes one more than a value its thread loaded, so every store writes at least 1.

    • Never below 2. The final value is the last store, say by thread X, of v + 1, where v is what X's last load read. X has done at least one increment before this one, so it had already stored a value of at least 1 before its last load. Every later store also writes at least 1. So X's last load read at least 1, and the final value is at least 2.
    • Exactly 2 is reachable. A loads 0 and stalls. B does k − 1 complete increments. A stores 1. B loads 1 and stalls. A does its remaining k − 1 increments. B adds and stores 2. For k = 1 the same argument fails (X has no earlier store), and indeed 1 is reachable, as the tree of 20 schedules shows.
  2. Peterson's bounded waiting. Prove that a waiting thread enters after at most one entry of the other.

    Solution

    Suppose P0 is waiting: it has set flag0 = 1 and turn = 1, and it waits while flag1 = 1 and turn = 1. If P1 enters, leaves (setting flag1 = 0) and comes back, its entry protocol sets turn = 0. From then on P0's condition is false (turn ≠ 1), so P0 can enter at its next look, while P1 waits (flag0 = 1 and turn = 0). P1 cannot pass P0 a second time. So the bypass bound is 1.

  3. The bakery with unreliable reads. Show that the bakery algorithm is correct even if a read that overlaps a write may return any value.

    Solution

    The key lemma: if Pi is in its critical section and Pk has finished choosing (number[k] ≠ 0, written and not being rewritten), then (number[i], i) < (number[k], k).

    • Pi, before entering, waited for choosing[k] = 0, then read number[k] and found it 0, or (number[i], i) smaller.
    • If Pk's choosing ended before Pi's read of choosing[k], then Pi's read of number[k] did not overlap Pk's write, so it read the true value, and the comparison was correct.
    • Otherwise Pk began choosing after Pi read choosing[k] = 0, so after Pi had finished writing number[i]; Pk's reads of number[i] did not overlap that write, so Pk saw number[i] and chose a larger number.

    Two threads in the critical section would each have the smaller pair, a contradiction. Only the choosing flags and finished writes are relied on, never a value read during a write.

  4. Queues have consensus number 2. Prove that a FIFO queue solves 2-thread consensus, and cannot solve 3-thread consensus.

    Solution
    • Two threads. Initialise the queue to (WIN, LOSE). Each thread writes its proposal to prop[i], then dequeues. WIN decides its own value; LOSE decides prop[other], which was written before the other's dequeue.
    • Not three. Suppose a protocol for A, B and C. Take a critical state: A's next step makes the decision 0-valent, B's makes it 1-valent. Both steps must be on the same queue (steps on different objects commute).
      • Both dequeue: the two orders leave the same queue, and differ only in which of A and B got which item. Run C alone from both states: it sees the same queue and decides the same way. Contradiction.
      • One enqueues and one dequeues on a non-empty queue: the two orders leave the same queue too, since the dequeue removes the head and the enqueue adds at the tail. C alone cannot tell them apart.
      • Both enqueue, a then b in one order and b then a in the other: run A alone until it dequeues the item in the first of the two positions, then B alone until it dequeues the item in the second. The queue, the only shared object A and B touched, now holds the same contents in both executions, so C running alone decides the same in both, while their valencies differ. (Herlihy 1991, Theorem 6, has the details of this last case.)
  5. Build: futexes for PebbleOS. Give PebbleOS futex_wait and futex_wake, and a mutex that sleeps instead of yielding; compare instructions.

    Solution
    • Two system calls. futex_wait(addr, val): with the timer held off, translate addr, and if the word still equals val, mark the thread BLOCKED with key = the physical address; otherwise return at once (someone changed it). futex_wake(addr, n): mark up to n threads BLOCKED on that key READY.
    • Drepper's mutex ("Futexes are tricky", 2004), with states 0 (free), 1 (held), 2 (held, maybe waiters): lock: c = cas(m, 0 -> 1); if c ≠ 0, loop: if c = 2 or cas(m, 1 -> 2) ≠ 0, then futex_wait(m, 2); c = cas(m, 0 -> 2); until c = 0. Unlock: if amoadd(m, -1) ≠ 1 then m = 0; futex_wake(m, 1).
    • Test with chapter 15's two threads. The yielding lock pays a full context switch per failed attempt; the futex lock blocks once and is woken once. Counting instructions, at quantum 500 the futex version should cost little more than amoadd, and much less than the yielding lock's 75,953.
  6. ★ Research: minimum fence insertion. For a program and TSO or PSO, find the fewest fences that restore a safety property. Is it NP-hard for PSO? Solve Peterson, the bakery and Dekker with the checker.

    Where to start.

    • The oracle: explainer/cs/conc/mc.explore(program, "tso" | "pso", invariant). A candidate is a set of program points at which to insert ("fence",); it is correct if the checker finds no violation.
    • Counterexample guidance: each violation trace shows a store and a later load (TSO), or two stores (PSO), of one thread that the buffer reordered; any correct fence set must separate at least one such pair in every trace. So the problem is a hitting set over the reorderings that matter, found lazily. This is the method of Abdulla et al., "Counter-example guided fence insertion under TSO" (TACAS 2012).
    • Hardness: minimum hitting set is NP-hard; does every hitting-set instance arise from some program under PSO? A reduction needs a program whose violations correspond to the sets. Compare Kuperstein, Vechev and Yahav, "Automatic inference of memory fences" (FMCAD 2010), and Alglave et al., "Don't sit on the fence" (CAV 2014).
    • Experiments: Peterson needs 1 fence per thread under TSO and 2 under PSO (chapter 4); find the minimum for the bakery with 2 and 3 threads, and for Dekker, and whether it differs between threads.
    • Beyond fences: cheaper repairs (an atomic exchange instead of a store and a fence), and the cost model when fences differ in price.

Notes and sources

Glossary

并发 concurrency · 并行 parallelism · 线程 thread · 竞争条件 race condition · 数据竞争 data race · 丢失更新 lost update · 交错 interleaving · 调度 schedule · 模型检验 model checking · 状态空间 state space · 互斥 mutual exclusion · 临界区 critical section · 安全性 safety · 活性 liveness · 有界等待 bounded waiting · Peterson 算法 Peterson's algorithm · 面包店算法 bakery algorithm · 不变式 invariant · 顺序一致性 sequential consistency · 全存储序 total store order · 部分存储序 partial store order · 存储缓冲区 store buffer · 内存栅栏 memory fence · 内存模型 memory model · 测试并设置 test-and-set · 比较并交换 compare-and-swap · 取并加 fetch-and-add · 自旋锁 spin lock · 票号锁 ticket lock · MCS 锁 MCS lock · 信号量 semaphore · 有界缓冲区 bounded buffer · 读者—写者 readers–writers · 管程 monitor · 条件变量 condition variable · Mesa 语义 Mesa semantics · 死锁 deadlock · 哲学家就餐 dining philosophers · 银行家算法 banker's algorithm · 先行发生 happens-before · 无数据竞争 data-race-free · 获取与释放 acquire and release · 凭空出现的值 out-of-thin-air value · 可线性化 linearizability · 无锁 lock-free · 无等待 wait-free · ABA 问题 ABA problem · 风险指针 hazard pointer · 读—复制—更新 read-copy-update · 共识数 consensus number · 普适性 universality · 价 valency · 事务内存 transactional memory · 通道 channel · 参与者 actor · 竞争检测器 race detector · 向量时钟 vector clock · futex

Sources

Canon. Books:

  • Herlihy, Shavit, Luchangco & Spear, The Art of Multiprocessor Programming (2nd ed., 2020);
  • Arpaci-Dusseau & Arpaci-Dusseau, Operating Systems: Three Easy Pieces, concurrency;
  • Downey, The Little Book of Semaphores (2016); McKenney, Is Parallel Programming Hard, And, If So, What Can You Do About It? (2023); Lynch, Distributed Algorithms (1996), ch. 10;
  • Sorin, Hill & Wood, A Primer on Memory Consistency and Cache Coherence (2nd ed., 2020).

Papers:

  • Mutual exclusion: Dijkstra, "Solution of a problem in concurrent programming control" (1965); Lamport, "A new solution of Dijkstra's concurrent programming problem" (1974); Peterson, "Myths about the mutual exclusion problem" (1981); Burns & Lynch, "Bounds on shared memory for mutual exclusion" (1980/1993).
  • Memory models: Lamport, "How to make a multiprocessor computer that correctly executes multiprocess programs" (1979); Adve & Hill, "Weak ordering: a new definition" (1990); Adve & Gharachorloo, "Shared memory consistency models: a tutorial" (1996); Manson, Pugh & Adve, "The Java memory model" (2005); Boehm & Adve, "Foundations of the C++ concurrency memory model" (2008); Sewell et al., "x86-TSO" (CACM 2010).
  • Locks: Anderson, "The performance of spin lock alternatives" (1990); Mellor-Crummey & Scott, "Algorithms for scalable synchronization on shared-memory multiprocessors" (1991); Drepper, "Futexes are tricky" (2004).
  • Waiting and deadlock: Dijkstra, "Cooperating sequential processes" (1965); Courtois, Heymans & Parnas (1971); Hoare, "Monitors" (1974); Brinch Hansen (1975); Lampson & Redell, "Experience with processes and monitors in Mesa" (1980); Coffman, Elphick & Shoshani, "System deadlocks" (1971).
  • Objects: Herlihy & Wing, "Linearizability" (1990); Herlihy, "Wait-free synchronization" (1991); Treiber (1986); Michael & Scott (PODC 1996); Michael, "Hazard pointers" (2004); Fraser (2004); McKenney & Slingwine, RCU (1998); Herlihy & Moss, "Transactional memory" (1993); Hoare, "Communicating sequential processes" (1978); Hewitt, Bishop & Steiger (1973).
  • Checking: Clarke & Emerson (1981); Queille & Sifakis (1982); Wing & Gong (1993); Gibbons & Korach (1997); Lowe (2017); Bouajjani, Emmi, Enea & Hamza (2015); Atig, Bouajjani, Burckhardt & Musuvathi (POPL 2010); Flanagan & Godefroid (2005); Savage et al., "Eraser" (1997); Flanagan & Freund, "FastTrack" (2009); Serebryany & Iskhodzhanov, ThreadSanitizer (2009); Burckhardt et al., PCT (2010); Attiya et al., "Laws of order" (POPL 2011); Kogan & Petrank (2011, 2012).
  • In the wild: Leveson & Turner, "An investigation of the Therac-25 accidents" (1993); U.S.–Canada Power System Outage Task Force, final report (2004).
About this partfrom its README

Part 33 of a sixty-one-part course in computer science (see the series plan and the syllabus), and the third part of Act VI, One Machine, Many Programs. Two threads each add one to a counter, and the count goes up by one. Mutual exclusion can be built from plain reads and writes (Peterson) until the hardware reorders them. The fix has two parts: a theory of memory models, and a hierarchy that orders synchronization primitives by power, at whose top compare-and-swap can implement every concurrent object. Pebble gains an atomic extension and PebbleOS gains threads.

The instruments are in explainer/cs/conc/ (tested in tests/test_cs33_conc.py):

  • mc.py, an exhaustive interleaving model checker:
    • programs in a tiny assembly language, one instruction list per thread (loads and stores, indexed access, arithmetic, branches, cas, tas, fai, blocking lock and semaphore P/V, fences, critical-section markers, outputs);
    • three memory models: SC (interleaving), TSO (a FIFO store buffer per thread, x86) and PSO (one FIFO per thread and variable, illustrating store-store reordering); atomics and fences drain the buffer;
    • breadth-first search over states, so every violation comes with a shortest schedule; deadlock detection; counting schedules of loop-free programs;
    • the part's programs: counter++, the naive flag lock, Peterson (with fences for TSO and PSO), the bakery, the store-buffering and message-passing litmus tests, the dining philosophers, the bounded buffer, consensus by registers, test-and-set and compare-and-swap, and the Treiber stack with a plain and a tagged CAS;
  • lin.py: a linearizability checker (Wing and Gong's search with Lowe's memo) for registers, counters, queues and stacks; random correct and buggy histories;
  • locks.py: TAS, TTAS, TTAS with backoff, ticket and MCS spin locks on Part 10's MESI caches, with a single bus that each transaction occupies for 8 cycles.

These are operational teaching models, rather than complete x86, Arm or C++ specifications. Allowed behaviors expand from SC to TSO to PSO; the recap's inclusions refer to those behavior sets. A successful exhaustive search establishes a property for the modeled finite program. Exceeding its state budget raises an error.

The linearizability checker accepts completed histories for its named sequential specifications; enqueue, push and register write have void (None) results. It rejects unknown operations and malformed intervals. Its intervals are closed: equal endpoint timestamps alone do not encode returned-before-invoked order. Use ordered timestamps when that order is known. Search-budget exhaustion raises TooHard, with the actual call count retained in stats.

Pebble's atomic extension (explainer/cs/pebble/isa.py, emu.py): cas rd, rs1, rs2 and amoadd rd, rs1, rs2 on opcodes 52 and 53, the two that Part 6 reserved; kept out of OPS, so Part 6's tables are unchanged. PebbleOS threads (explainer/cs/os/vmos.threads_vm): PCBs that share one page table, each with its own stack.

Measured on this machine (videos/cs/cs33/conc.c, and the compiler):

  • a counter incremented 10⁷ times by 1, 2 and 4 threads: plain, atomic and under a mutex;
  • TAS, TTAS, ticket, MCS and pthread_mutex with 1, 2 and 4 threads;
  • creating a thread against forking a process; Intel RTM transactions;
  • ThreadSanitizer on the racy counter, on an atomic load-then-store, and on an atomic increment;
  • gcc -O2 on a spin loop over a plain flag and over an atomic one.
Chapter notes
  • Hook.
    • Four threads add 10⁷ each to one counter on this machine: 10,547,788 instead of 40,000,000. With one thread, exactly right.
    • Where an addition goes: load, add, store, interleaved.
  • 1. Why concurrency.
    • Overlap: two requests in 7 units instead of 12. Parallelism since about 2005.
    • Processes against threads; a thread created and joined in 41 µs here, a process forked and reaped in 179 µs.
  • 2. The race.
    • The tree of all 20 schedules of two increments: 2 give 2, 18 give 1.
    • The model checker. For k = 1 to 4 increments each: 20, 924, 48,620 and 2,704,156 schedules (C(6k, 3k)), but only 22, 138, 585 and 1,846 states. The count can end as low as 2 for any k ≥ 2. Fetch-and-add or a lock: only 2k.
  • 3. Mutual exclusion from reads and writes.
    • Safety, progress, bounded waiting. The naive flag lock broken in 8 steps.
    • Peterson (1981) and its proof; Dekker (1965). Lamport's bakery (1974), any n, safe registers.
    • Peterson's state space: 258 states for one round; 24 of 25 region pairs reachable, never (inside, inside). The bakery checked with 644 states for 2 threads and 92,745 for 3. Burns and Lynch's n-register bound.
  • 4. Peterson meets the store buffer.
    • Store buffers; the store-buffering test (Part 10's run on this machine: both 0 in 942,588 of 10⁶ runs, never with a fence).
    • Under TSO the checker breaks Peterson in 10 steps; one fence repairs it. Under PSO it needs a second fence between the two stores. Message passing fails under PSO.
  • 5. Hardware locks.
    • TAS, TTAS, ticket and MCS; the MCS queue.
    • Simulated, 32 cores: bus transactions per handoff TAS 63, TTAS 46, ticket 31, MCS 7; cycles per handoff 505 against 59; fairness 0.20 against 0.90.
    • This machine (4 cores): TAS 7 ns alone, 105 ns with 4 threads; MCS 18 and 200; pthread_mutex 20 and 69.
  • 6. Semaphores.
    • P and V; mutex, counting, signalling.
    • The bounded buffer: the count always ends at 0 (188 states); without the mutex, anywhere from −2 to 2.
    • Readers and writers, and starvation; The Little Book of Semaphores.
  • 7. Monitors and condition variables.
    • Hoare and Brinch Hansen; Mesa semantics: with if, a consumer takes from an empty buffer after 29 steps; with while, safe in 741 states.
  • 8. Deadlock.
    • Five philosophers deadlock in 5 steps; with one philosopher reversed, none in 3,216 states.
    • Coffman's four conditions; lock order and lockdep.
    • The banker's algorithm on Silberschatz's example: safe order P1, P3, P0, P2, P4; P1's (1, 0, 2) granted; P0's (0, 2, 0) refused as unsafe.
  • 9. Memory models.
    • The compiler reorders too: gcc -O2 turns while (!done); over a plain int into a jump to itself.
    • Happens-before and data races. DRF ⇒ SC (Adve and Hill 1990): store buffering with every access locked gives only SC's outcomes under TSO and PSO.
    • C++ and Java atomics, release and acquire; out-of-thin-air values.
  • 10. Linearizability.
    • Intervals and instants; a linearizable queue history and one that is not.
    • Sequential consistency against linearizability; locality.
    • The checker on random histories: correct objects always pass; with stale answers a third of queue histories and nearly all counter histories fail.
  • 11. Lock-free data structures.
    • Treiber's stack (1986). The ABA problem found by the checker (23 steps); a tagged CAS removes it (1,536 states).
    • Hazard pointers, epochs, RCU; the Michael–Scott queue; wait-free, lock-free, obstruction-free.
  • 12. Consensus numbers.
    • Test-and-set solves 2-consensus (52 states) and fails for 3; CAS solves 3 (145 states).
    • Herlihy's hierarchy; universality as a log of agreements; why registers cannot solve it: valency.
  • 13. Transactional memory, channels and actors.
    • Hardware transactions: 999,927 of 10⁶ commit on this machine; TSX's troubles.
    • CSP and Go, actors and Erlang, async/await.
  • 14. Concurrency bugs in the wild.
    • Therac-25, Mars Pathfinder, the 2003 blackout.
    • ThreadSanitizer finds the hook's race; with an atomic load-then-store it is silent and the count is still wrong (1,225,222 of 2,000,000); an atomic increment gives 2,000,000.
  • 15. PebbleOS gains threads and CAS.
    • cas and amoadd; threads as PCBs sharing a page table; a CAS lock that yields.
    • Two threads, 2,000 increments each: plain load-add-store gives 2,765 at quantum 500 and 2,810 at 3,000 (4,000 at 97, by luck); amoadd and the lock always 4,000.
    • The quantum sweep: every one of 75 other quanta (40 to 3,000 in steps of 40, so 97 is not among them) loses updates.
  • 16. Frontier: checking concurrent programs.
    • Linearizability checking is NP-complete; our checker's cost on random queue histories.
    • Weak-memory verification: 1,487, 21,169 and 61,051 states for Peterson under SC, TSO and PSO.
    • Laws of order, fast wait-free structures, PCT. Open problems. Outro.

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Why concurrency: overlapping I/O, using cores; threads against processes.
  2. The race: counter++ as load, add, store. Interleavings counted (C(2n, n)); the lost update found by our exhaustive interleaving model checker.
  3. Mutual exclusion (safety, liveness, fairness): Dekker (1965); Peterson (1981), proved by invariant; Lamport's bakery (1974); the Burns–Lynch n-register lower bound.
  4. Peterson breaks under TSO: the store-buffer litmus test (callback to Part 10), checked under SC and TSO models, and repaired with a fence.
  5. Hardware locks: TAS, TTAS with backoff, ticket locks, MCS (1991) and its cache-line traffic (callback to MESI).
  6. Semaphores (Dijkstra 1965): the bounded buffer; readers–writers; puzzles from The Little Book of Semaphores.
  7. Monitors and condition variables (Hoare 1974, Brinch Hansen); Mesa semantics, and why while and not if.
  8. Deadlock: Coffman's four conditions (1971); resource-allocation graphs; lock ordering; the banker's algorithm; the dining philosophers, deadlocked and then fixed.
  9. Memory models: happens-before; DRF ⇒ SC (Adve & Hill 1990); the C++11 and Java models; acquire and release; out-of-thin-air values.
  10. Linearizability (Herlihy & Wing 1990), on timelines; a computed history checker.
  11. Lock-free structures: the Treiber stack and ABA; tags, hazard pointers, epochs and RCU; the Michael–Scott queue.
  12. Progress conditions, and consensus numbers (Herlihy 1991): registers 1, test-and-set and queues 2, CAS ∞, proved by valency (a preview of FLP in Part 38); the universality of consensus.
  13. Transactional memory (Herlihy & Moss 1993; TSX's troubles).
  14. Other models: CSP (Hoare 1978) and Go channels; actors and Erlang; async/await.
  15. In the wild: Therac-25 and the 2003 blackout (cited); race detectors with vector clocks (Part 38).
  16. PebbleOS gains a CAS mutex and threads. Outro.

Computed: exhaustive interleavings for counter++, Peterson and the bakery with property checks; SC against TSO model checking; a lock benchmark (C on this machine where available, otherwise a cache-traffic simulation); linearizability checking; the ABA scenario; dining philosophers; the banker's algorithm. Visuals: interleavings branching as a tree; Peterson's state graph with the bad state unreachable; the MCS queue as linked waiters; the consensus ladder. In practice: mutexes, channels and async runtimes (Go, Rust's tokio, java.util.concurrent), race detectors (TSan), lock-free queues in low-latency systems. Reading: Herlihy & Shavit, The Art of Multiprocessor Programming; OSTEP (concurrency); Downey, The Little Book of Semaphores; Lynch, Distributed Algorithms ch. 10; Sorin, Hill & Wood; McKenney, Is Parallel Programming Hard?; Lamport 1974, 1979; Dijkstra 1965; Hoare 1974, 1978; Herlihy 1991; Herlihy & Wing 1990; Adve & Gharachorloo 1996; Boehm & Adve 2008; Mellor-Crummey & Scott 1991.

中文讲义

本讲的中文部分(与英文版对应)。

习题与解答
  1. 计数器的最小值。 证明:两个线程各做 k ≥ 2 次“读—加—写”递增时,计数器可能停在 2,而且绝不会低于 2。

    解答

    每次存储写入的都是本线程读到的某个值加一,所以每次存储写入的值至少为 1。最终值是最后一次存储,设由线程 X 写入 v + 1,v 是 X 最后一次读到的值。X 在这之前至少完成过一次递增,所以在最后一次读之前已经存储过至少为 1 的值,之后的任何存储也 至少为 1。于是 X 最后一次读到的至少为 1,最终值至少为 2。可达性:A 读到 0 后停住;B 完成 k − 1 次递增;A 存入 1;B 读到 1 后停住;A 完成其余 k − 1 次递增;B 加一并存入 2。k = 1 时论证失效(X 没有更早的存储),1 确实可达,正如 20 种调度的树所示。

  2. Peterson 的有界等待。 证明:等待中的线程最多等对方进入一次。

    解答

    设 P0 在等待:已置 flag0 = 1、turn = 1,并在 flag1 = 1 且 turn = 1 时等待。若 P1 进入、离开(置 flag1 = 0)再回来, 它的进入协议会置 turn = 0。此后 P0 的等待条件不成立(turn ≠ 1),下次检查即可进入,而 P1 在 flag0 = 1 且 turn = 0 时等待。 P1 不可能第二次越过 P0,所以越过次数的上界是 1。

  3. 读不可靠时的面包店算法。 证明:即使与写重叠的读可以返回任意值,面包店算法仍然正确。

    解答

    关键引理:若 Pi 在临界区,而 Pk 已选完号码(number[k] ≠ 0,已写好且不在改写),则 (number[i], i) < (number[k], k)。 Pi 进入前等到 choosing[k] = 0,然后读 number[k],发现为 0,或 (number[i], i) 更小。若 Pk 的选号在 Pi 读 choosing[k] 之前 结束,Pi 对 number[k] 的读不与 Pk 的写重叠,读到真实值,比较正确;否则 Pk 是在 Pi 读到 choosing[k] = 0 之后才开始选号,也就是 在 Pi 写完 number[i] 之后,Pk 对 number[i] 的读不与那次写重叠,因而看到了 number[i],选了更大的号码。两个线程同在临界区时 各自的对都更小,矛盾。证明只依赖 choosing 标志和已完成的写,从不依赖写入过程中读到的值。

  4. 队列的共识数为 2。 证明 FIFO 队列能解决两线程共识,而不能解决三线程共识。

    解答

    两线程:把队列初始化为 (WIN, LOSE)。各线程先把提议写入 prop[i],再出队;拿到 WIN 的决定自己的值,拿到 LOSE 的决定 prop[另一方](它在对方出队之前已写好)。三线程不行:设 A、B、C 有一个协议。取一个临界状态:A 的下一步使决定成为 0-价,B 的 下一步使之成为 1-价。两步必须作用于同一个队列(作用于不同对象的步骤可交换)。两者都出队:两种顺序留下相同的队列,只差在 A、B 各拿到哪一项;让 C 单独运行,它看到相同的队列,作出相同的决定,矛盾。一个入队、一个对非空队列出队:两种顺序同样留下相同队列 (出队取头,入队加尾),C 单独运行无法区分。两者都入队,一种顺序先 a 后 b,另一种先 b 后 a:让 A 单独运行到取出前一个位置的项,再让 B 单独运行到取出后一个 位置的项。A 和 B 只触及这个队列,此时它在两次执行中内容相同,所以单独运行的 C 在两种情况下决定相同,而两者的价不同(这一情形的 细节见 Herlihy 1991,定理 6)。

  5. 动手:给 PebbleOS 加 futex。 加上 futex_wait 和 futex_wake,以及一个睡眠而非让出的互斥锁;比较指令数。

    解答

    两个系统调用。futex_wait(addr, val):在暂停定时器的情况下翻译 addr,若该字仍等于 val,就把线程标为阻塞,键为物理 地址;否则立即返回(有人改了它)。futex_wake(addr, n):把最多 n 个阻塞在该键上的线程标为就绪。Drepper 的互斥锁(《Futexes are tricky》,2004),状态 0(空闲)、1(被持有)、2(被持有,可能有等待者):加锁:c = cas(m, 0 -> 1);若 c ≠ 0,循环: 若 c = 2 或 cas(m, 1 -> 2) ≠ 0,则 futex_wait(m, 2);c = cas(m, 0 -> 2);直到 c = 0。解锁:若 amoadd(m, -1) ≠ 1, 则 m = 0; futex_wake(m, 1)。用第 15 章的两个线程测试:让出式锁每次失败都付出一次完整的上下文切换;futex 锁阻塞一次、被唤醒 一次。按指令计数,时间片 500 时 futex 版本应比 amoadd 多不了多少,而远少于让出式锁的 75,953 条。

  6. ★ 研究:最少栅栏插入。 对给定程序和 TSO 或 PSO,找出恢复某个安全性质所需的最少栅栏。在 PSO 下它是 NP 难的吗?用检验器 求解 Peterson、面包店和 Dekker 算法。

    从哪里开始。 预言机:explainer/cs/conc/mc.explore(program, "tso" | "pso", invariant)。候选方案是在若干程序点插入 ("fence",) 的集合;检验器找不到违例即为正确。反例引导:每条违例轨迹都显示同一线程中被缓冲区重排的一对“存储—之后的读取” (TSO)或两次存储(PSO);任何正确的栅栏集合都必须在每条轨迹中至少隔开一对。于是问题成为对“要紧的重排”的命中集问题,可以惰性 地求出。这是 Abdulla 等人《Counter-example guided fence insertion under TSO》(TACAS 2012)的方法。难度:最小命中集是 NP 难的; 是否每个命中集实例都能由某个 PSO 下的程序产生?归约需要构造一个程序,使其违例恰好对应那些集合。可参考 Kuperstein、Vechev 与 Yahav《Automatic inference of memory fences》(FMCAD 2010)和 Alglave 等《Don't sit on the fence》(CAV 2014)。实验:Peterson 在 TSO 下每线程需要 1 个栅栏,在 PSO 下需要 2 个(第 4 章);求面包店算法在 2 线程和 3 线程时、以及 Dekker 算法的最小值,以及 各线程是否不同。更进一步:更便宜的修补(用原子交换代替一次存储加一个栅栏),以及栅栏代价不同时的代价模型。

Build the film

python -m videos.cs.cs33.compute        # the part's numbers, into .cache/cs33
python tools/build.py cs33                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs33 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/cs/cs33. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.cs.cs33.compute           # every number in the part (about three minutes)
python tools/build.py cs33 -q l            # a 480p preview
python tools/build.py cs33                 # 1080p