PROGRAMMING PARADIGMS · PART 2 · SESSION 7, BLOCK 1

Multi-threading : mutual exclusion,
atomics, and independence

Block 1. Mutual Exclusion

Which ways control the interleavings of a multi-threaded program, and what does each guarantee, require and risk?

PART 1

Introduction

threads and the interleaving; data races and atomicity violations; synchronization; the terms

A program with several threads runs in many orders. Before any way of controlling them: the model of those orders, the two faults they allow, and the terms every way is judged in.

Threads, memory and the scheduler

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

Thread. A sequence of instructions that the processor executes one after another, with its own position in them and its own local variables.

Instruction. One step the processor executes as a whole: a read of one memory location into the processor, a write of one value to one location, an operation inside the processor.

A line of source code is usually several instructions: n++ is a read, an addition and a write.

Shared memory. Locations that every thread can read and write by their address: fields and array elements, not the local variables of a Java method.

Scheduler. Decides which thread runs where; may stop a thread between any two instructions and resume it later.

Its parts: a queue of the threads ready to run; a policy that picks the next one; a timer interrupt that stops the running thread; a context switch that saves its registers and program counter and loads another's.

The interleaving

thread Athread B read nadd 1write n read nadd 1write n one interleaving read n add 1 write n read n add 1 write n another interleaving read n read n add 1 add 1 write n write 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

Definition. An execution of a multi-threaded program is an interleaving of its threads' instructions: one sequence of the instructions the threads execute, each thread's in the order the thread issues them.

Two threads of m and n instructions have \(\tbinom{m+n}{n} = \tfrac{(m+n)!}{m!\,n!}\) interleavings: an interleaving is fixed by the n positions of the second thread among the m + n. Here \(\tbinom{6}{3} = 20\); for the counter's two loops of \(3\cdot 10^6\) steps, \(\tbinom{6\cdot 10^6}{3\cdot 10^6} > 10^{1\,800\,000}\).

Two threads that each execute a million three-step increments have more interleavings than any test could run.

! A correctness argument does not look at runs. It should cover every interleaving at once;
that is what the rest of this block does.

The interleavings of two increments

r1 a1 w1 r2 w2 a2r1 a1 w1 a2 r2 w2r1 a1 w1 a2 w2 r2r1 a1 w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's own order, r before a before w: the interleavings.

Of the 720 orders of the six steps, program order within each thread leaves these 20.

Data race

thread Athread B read nadd 1write n read nadd 1write n shared memoryn timetime write n read n data race: nothing orders them

Data race. Two accesses to one memory location from two threads, at least one a write, with nothing of the program ordering one before the other.*

To avoid the race, the two threads must coordinate: what can the program put between the two accesses?

* The Java Language Specification, 17.4.5; C++, Rust and OCaml add: at least one access not atomic.

Synchronization mechanisms

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

Synchronization. The order a program can impose; three mechanisms give it.

A lock. Its release is ordered before the acquire that follows it: what the releasing thread wrote before, the thread that acquires next sees after.

A thread's start and join. The call of start is ordered before the new thread's first instruction, and its last instruction before the return of the join that waits for it.

An atomic. A write to an atomic or volatile variable is ordered before the read that sees it, with everything the writer did before.

Each mechanism orders one thread's instructions before another's: what the first thread wrote before, the second sees after. Two accesses with none of them between are a data race.

A data race is missing order. Is order all that an operation of several steps needs?

Atomicity violation

thread Athread B timetime one unit read nadd 1write n write n write na step falls inside the unit read ndata race

Atomicity violation. An operation of several steps meant as a unit, atomic, every other thread seeing all of it or none, and not protected as a unit, so that another thread's step can fall between two of its steps.

This increment has both: a data race, the two accesses unordered; an atomicity violation, the unit split. Part 4 shows an operation with the second fault and not the first.

Two senses of atomic. An instruction of the model is atomic: the processor executes it as one step; test-and-set, in part 2, is one that a real processor provides. An operation of several steps is logically atomic: it appears to take effect at one instant between its start and its end, and block 2 states this standard in full as linearizability.

Four assumptions

  1. Several threads. Two or more, each a sequence of instructions.
  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, 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; with assumption 3, this is Lamport's sequential consistency*.Each processor buffers its writes and compilers reorder, so this is not literally what the hardware does: a guarantee of the language, given only for programs without data races, as defined earlier.

* L. Lamport, IEEE Transactions on Computers C-28(9), September 1979, pages 690–691: the definition.

The terms of each way

Three ways: mutual exclusion in this block; an atomic instruction with retry, and independence of the order, in block 2. Each is judged in the same four terms, and a table answers them at the end of each block.

  1. The guarantee. What holds in every interleaving: for the first two ways a logically atomic operation, which block 2 states in full as linearizability; for the third, one result in every order.
  2. The obligation. What the program must do for the guarantee to hold.
  3. The progress risk. Where a program that meets the obligation can still stop; block 2 states it as a progress condition.
  4. Who checks. Nobody; a checker at compile time or a detector at run time; the compiler.
PART 2

Mutual exclusion

what makes several steps logically atomic, and what it costs

The terms are set. The first way begins where every way begins, with the program that has none of them: the counter, unprotected.

Example 1: the counter, unprotected

JavaOCaml 5
CounterRacy.javastatic int n = 0;   // shared

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("got " + n);
counter_racy.mllet n = ref 0   (* shared *)

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 "got %d\n" !n

Two threads each add one to n, N times. What does the program print as n?

  1. Always 2N.
  2. At most 2N.
  3. Possibly more than 2N.
  4. Always less than 2N.
$ java CounterRacy
expected 2000000
got      1017204

One sample of a run. Ten further runs printed ten other numbers, none of them 2,000,000.

Where does an increment lose a step?

The three steps of n++

JavaOCaml 5
CounterRacy.javaint v = n;      // read
v = v + 1;      // add
n = v;          // write
counter_racy.mllet v = !n in      (* read  *)
let v = v + 1 in   (* add   *)
n := v             (* write *)

The Java compiler produces four bytecodes, getstatic, iconst_1, iadd, putstatic: the first is the read, the last the write, and the scheduler may run another thread between them.

Lost update. A write whose effect is overwritten by a write based on an older read.

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

The table is the interleaving that loses an update, from n equal to 5: both read 5, both write 6; "register" is the thread's own copy of the value. Two increments were executed and n grew by one.

appendixthe bounds on the printed value, at most 2N, exactly 2N and at least 2, each with its reason

How many of the twenty interleavings lose an update?

The interleavings that lose an update

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 a2 r2 w2 a1r1 w1 a2 w2 a1 r2r1 w1 a2 w2 r2 a1r1 w1 w2 a1 r2 a2r1 w1 w2 a1 a2 r2r1 w1 w2 r2 a1 a2r1 w1 w2 r2 a2 a1r1 w1 w2 a2 a1 r2r1 w1 w2 a2 r2 a1r1 r2 a1 w1 w2 a2r1 r2 a1 w2 w1 a2r1 r2 a1 w2 a2 w1r1 r2 w1 a1 a2 w2 r1 r2 w1 a1 w2 a2r1 r2 w1 a2 a1 w2r1 r2 w1 a2 w2 a1r1 r2 w1 w2 a1 a2r1 r2 w1 w2 a2 a1r1 r2 a2 w1 a1 w2r1 r2 a2 w1 w2 a1r1 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1 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 20 interleavings of the two increments, each thread's own order kept.

18 of the 20 read before the other thread's write and lose an update; 2 count correctly: one increment after the other.

The counter's two faults

thread Athread B timetime one unit read nadd 1write n write n write na step falls inside the unit read ndata race
Atomicity violationThe increment is meant to be logically atomic, its three steps seen whole or not at all. B's write falls inside them, and A's write stores one more than a value B already replaced: the unit is split.
Data raceA's read of n and B's write of n, nothing ordering them: the order is missing.
BothA lock removes both at once; part 4 shows the violation without the race.

What makes the three steps logically atomic?

Roadmap

Part 2Mutual exclusionWhat makes three steps logically atomic, and what does it cost? A lock, built from one atomic instruction; its contract, its obligation, its progress risk.
Part 3Race detection and preventionWho checks that every access is under the lock? Nobody by default; a checker or a detector; Rust's compiler.
Part 4DeadlockAre two logically atomic steps one? A transfer with no data race and a wrong sum; two locks and a program that stops; the order that cures it.
Block 2The questionCan a logically atomic operation exist without any lock?

Naive lockTest-and-set and its guarantees

flag thread Athread B timetime false true read flag write true critical section reads false read flag write true critical section between A's read and write reads false both inside 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

A naive lock. To acquire, a thread reads the flag and, if it is false, writes true; then it enters the critical section.

Two steps on a shared location: the other thread reads the flag between them, also finds false, and both threads enter.

The lock protects the critical section; but then what protects the lock itself?

Test-and-set. 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.

Indivisibility. It reads the old value and writes the new one as one step: no thread sees the location between.

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.

Spin lock. A flag, a boolean location, and a loop: to acquire, a thread repeats test-and-set on the flag until the old value is false, spinning while it finds true; to release, it writes false.

The first guarantee makes the lock exclusive; the second makes the plain variable inside it race-free.

Example 2: the spin lock

JavaOCaml 5
SpinLock.javastatic final AtomicBoolean held =
    new AtomicBoolean(false);
static void lock() {
  while (held.getAndSet(true)) { }
}
static void unlock() { held.set(false); }

static int n = 0;   // plain, as in example 1
// the loop of each of the two threads
for (int i = 0; i < N; i++) {
  lock(); n++; unlock();
}
spin_lock.mllet 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   (* plain, as in example 1 *)
(* the loop of each of the two domains *)
for _ = 1 to 1_000_000 do
  lock (); n := !n + 1; unlock ()
done

Java provides the instruction as getAndSet(true), a method with the two guarantees, carried out by the processor's own atomic instruction where it has one; OCaml 5 as Atomic.exchange flag true.

$ java SpinLock
expected 2000000
got      2000000

One sample of a run.

The lock is the instruction with a loop around it. The counter is exact for two reasons, the two guarantees: at most one thread at a time is between lock() and unlock(), and the release orders its write of n before the next holder's read.

Example 3: the counter under one lock

JavaOCaml 5
CounterLocked.javastatic final Object lock = new Object();
static int n = 0;   // guarded by lock

// the loop of each of the two threads
for (int i = 0; i < N; i++) {
  synchronized (lock) {   // critical
    n++;                  // section
  }
}
counter_locked.mllet n = ref 0   (* guarded by m *)
let m = Mutex.create ()

(* the loop of each of the two domains *)
for _ = 1 to 1_000_000 do
  Mutex.protect m (fun () ->   (* critical *)
    n := !n + 1)               (* section  *)
done
$ java CounterLocked
expected 2000000
got      2000000

One thread at a time inside; the interleaving is forbidden there. One sample of a run.

A waiting thread is suspended until the release, after at most a brief spin; the closing brace releases the lock even on an exception.

thread Athread B timetime shared memoryn lockread nadd 1write nunlock critical section lock waits held by A lockread nadd 1write nunlock critical section lock waits held by B

Lock. An object with two operations, acquire and release: between a thread's acquire that returned and its release, no other thread's acquire returns.

Critical section. The instructions a thread executes while holding the lock.

The contract and the obligation

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

Contract. Operations are logically atomic by exclusion, in every interleaving: 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 coarse way: no two operations overlap at all.

Obligation, two parts here. Every access to the protected state, read or write, while holding the lock; and the lock held for the whole operation, over every piece of state its invariant mentions, the statement that holds whenever no thread is inside a critical section.

A lock protects only against the threads that take it: a new lock per call, synchronized (new Object()) { n++; }, is held by one thread and never taken by another. 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.

Where can a program that keeps the obligation still stop?

The progress risk of a lock

thread Athread Blockread nA stopped by the schedulerlockwaits as long as A is stoppedtimetime thread Atimethread Btimethread Ctimelockunlockheld by Alockunlockheld by Blockunlockheld by Alockunlockheld by Blockstarvation: C is passed over

Progress risk, first source: a stopped holder. A thread that holds a lock and is stopped stops every thread that needs it. Stopped in a cycle, it is deadlock; not scheduled, a missed deadline, in the appendix.

Second source: starvation. A lock that keeps changing hands may never reach one thread. An order among the waiters removes it, and block 2's wait-freedom rules it out.

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 finishthe waiters leave the processor to the holder, and still wait as long as it is stopped
A lock changing handsno order among the waiters: starvation is possiblea woken waiter competes with newcomers: 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 spins in turn, a fair lock suspends in turn.

And who checks that every access is under the lock -- programmer's discipline or can a language enforce it ?

PART 3

Race detection and prevention

who checks that every access is under the lock

A lock enforces none of its obligation, and a discipline nobody checks is a fault waiting for its run. Who can check it: a tool watching the run, or the compiler before any run?

Example 4d: the unlocked reader

JavaOCaml 5
Accounts.java// (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 };
}
accounts.ml(* lock w x: takes x.lock; w notes it *)
(* (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)

Two accounts, A (id 1) and B (id 2), one lock each; t1 and t2 transfer in opposite directions; a reader takes no lock. Does it compile, and what did the compiler establish about the reader's reads?

  1. No: a balance is read outside its lock.
  2. Yes; the runtime reports the unlocked read.
  3. Yes; the two reads are data races, and nothing reports them.
  4. Yes; reading an int is one instruction, so the reads are correct.
$ java Accounts d
readings with no lock: 138670249
sums other than 200:    20954124
first wrong: A = -5811, B = 6012

Who checks that every access is under the lock

LanguageWho checks that every access is under the lock
JavaNobody by default. A comment beside the field, // guarded by lock, records the rule; Error Prone, a static checker, checks every access at compile time when the rule is written as the annotation @GuardedBy("lock").
OCaml 5; Go; C and C++Nobody by default; a detector at run time when run with Go's -race or ThreadSanitizer, a race detector in clang and gcc, and in an OCaml compiler of 5.2 or later built with it: it reports two unordered accesses the run made, even when the timing kept them apart and the answer was right, as far as its record of recent accesses reaches; a path the run did not take is not checked.
RustThe compiler, before any run, for data races only.
For one word, a variable of one location, that one thread writes and another reads, Java offers volatile: every write is synchronization for the read that sees it. n++ on a volatile field is the same three steps as before.

Rust: the counter rejected

Rust
r1a_scoped_mut.rslet 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);
error[E0499]: cannot borrow `count` as mutable
               more than once at a time
  |
6 |   s.spawn(|| for _ in 0..1_000_000 { count += 1 });
  |   -------    first mutable borrow occurs here
7 |   s.spawn(|| for _ in 0..1_000_000 { count += 1 });
  |           ^^ second mutable borrow occurs here

error: aborting due to 1 previous error

Ownership, the intuition: every value has one owner at a time, and a value may be shared by several threads or changed by one, never both at once, unless a lock or an atomic stands between*. A mutable borrow is a reference through which a thread may change a variable; two threads that both change count are two mutable borrows, and the compiler rejects the second.

* Session 12 gives the rule.

Rust: Mutex<T>, the lock and its data

Rust
r1b_arc_mutex.rslet 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

A Mutex<T> holds the T; Arc lets the threads share the lock. While it is shared, the only way to the T is the guard that lock() returns, which releases the lock when it goes out of scope: no thread reaches the integer without holding its lock.

In Java, example 3's lock and n are tied only by a comment: the compiler accepts n++ outside synchronized (lock). In Rust, as in a monitor of the appendix, the data is reachable only under its lock; the rule is stated in the types of a library, and the compiler checks it.

Rust checks the first part of the obligation, every access under its lock; the others remain the programmer's.

Not checked: the order of the locks, so the deadlock of part 4 compiles; nor atomicity, so the transfer in two halves compiles. A compiler can rule out a data race, not an atomicity violation.
PART 4

Deadlock

two logically atomic steps, and whether they are one

Rust's compiler rules out data races and nothing else. The fault with no data race in it needs two locks: a transfer in two halves, and the deadlock behind its repair.

Example 4a: the transfer in two halves

JavaOCaml 5
Accounts.java// (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 };
  } }
}
accounts.ml(* lock w x: takes x.lock; w notes it *)
(* (a) each step under its lock,
       the transfer as a whole under none *)
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
(* the reader: both balances, both locks *)
let read_locked () =
  lock w a; lock w b;
  let x = a.balance and y = b.balance in
  unlock w b; unlock w a; (x, y)

A and B hold 100 each; the invariant is that the sum is 200. The withdrawal and the deposit are each under a lock. Is the transfer atomic?

  1. Yes: each of its two steps is atomic, so the sequence of the two is.
  2. No: between the two steps a thread holding both locks can read a sum of 199.
  3. No, and the reads of the balances are data races.
  4. Yes, provided the reader takes both locks.
$ java Accounts a
reading 1: A = 99, B = 100,
           sum = 199

What if both locks are held for the whole transfer?

Example 4b: both locks, deadlock

JavaOCaml 5
Accounts.java// (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();
while (bean.findDeadlockedThreads() == null)
  Thread.sleep(50);
accounts.ml(* lock w x: takes x.lock; w notes it *)
(* (b) both locks, the source's first *)
let transfer_deadlock w src dst k =
  lock w src; lock w dst;
  src.balance <- src.balance - k;
  dst.balance <- dst.balance + k;
  unlock w dst; unlock w src
(* a watchdog domain reads, every 0.1 s,
   what each domain holds and waits for,
   and prints the cycle when it finds one *)

Deadlock. 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.

$ 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
thread t1thread t2 lock of Alock of B held byheld by t1 waits for the lock of B t2 waits for the lock of A

Safety and liveness

Safety property. Something bad never happens; a violation is a finite run, one that reaches the bad state. Liveness property. Something good eventually happens; no finite run can show a violation, since the good thing may still come.*

The deadlock violates both kinds. That each thread holds one lock and waits for the other's is a state, and the detector finds it: "never deadlocked" is a safety property. That no transfer will ever complete is the liveness property it ruins; no detector can see "ever".

* Lamport 1977 (IEEE TSE SE-3(2), 125–143); Alpern and Schneider 1985 (Inf. Proc. Letters 21(4), 181–185).

What are the conditions of a deadlock?

The Coffman conditions (1971)

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

Four conditions are all necessary for a deadlock:

  1. Mutual exclusion. A resource is held by one thread at a time.
  2. Hold and wait. A thread holds a resource while it waits for another.
  3. No preemption. A held resource cannot be taken away.
  4. Circular wait. A cycle of threads, each waiting for a resource the next holds.

A global order of the locks removes the fourth, circular wait: the next example.

Example 4c: a global order of the locks

JavaOCaml 5
Accounts.java// (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;
    }
  }
}
accounts.ml(* lock w x: takes x.lock; w notes it *)
(* (c) the locks always taken
       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
$ java Accounts c
transfers: 1000000 A to B,
           1000000 B to A
readings: 530369, wrong sums: 0
at the end: A = 100, B = 100

Every thread that takes several locks takes them in the same order. A thread waits only for a lock later in the order than every lock it holds; along a chain of waiting threads the locks come later and later, and a chain that only goes up cannot return to its start.

The order is the obligation's third part, after every access under the lock and the lock held over the invariant. No compiler checks it, and the deadlock compiles in safe Rust; tools find it only in runs.

appendixprogress lost with one lock and no cycle: Mars Pathfinder, 1997

Mutual exclusion in summary

The guaranteeOperations logically atomic by exclusion: under the lock they happen one after another, each at one instant inside its critical section.
The obligationEvery access to the protected state under the lock; every lock the invariant needs, held for the whole operation; one global order of the locks.
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, for the fields annotated @GuardedBy; a detector at run time, with Go's -race or ThreadSanitizer, for the accesses a run made; Rust's compiler, for data races only, never the lock order or atomicity.

Where can a program that locks every access still stop, failure by failure?

Progress failures

DeadlockEvery thread of a set waits for a lock that another thread of the set holds: example 4b. Removed by one global order of the locks, example 4c.
A missed deadlineThe holder is ready to run and the scheduler does not run it, so a thread that needs its lock waits past its deadline: Mars Pathfinder, in the appendix. Removed by priority inheritance.
StarvationThe lock keeps changing hands, and one thread is passed over for ever: the figure of part 2. Removed by an order among the waiters, a ticket lock or a fair lock.
A lost wake-upA notification reaches no thread that waits for it, because it came before the wait or woke a thread of the wrong kind, and the waiter sleeps for ever: the monitor's one waiting set, in the appendix. Removed by testing the condition and waiting under one lock, and by notifyAll or one condition variable per kind of waiter.

Was the lock around the instruction needed at all?

The question for block 2

thread A time shared memoryn critical section read n add 1 write n held by A fetch-and-add 1 one instruction, no lock

The counter has been exact twice, under the spin lock and under the language's lock, both by exclusion. The spin lock was built from one instruction that is itself atomic, test-and-set.

Then can a logically atomic operation be built from atomic instructions, without exclusion?

Block 2: the standard of logical atomicity in full, linearizability and progress; compare-and-set with retry, the second way; and the fourth assumption's condition.

APPENDIX

Bounds and priority inversion

the bounds on the printed value; Mars Pathfinder and priority inheritance

The bounds on the printed value

printed value 02N2N at most 2N exactly 2N at least 2

At most 2N: every write stores one more than a value read.

Exactly 2N is possible: in every interleaving in which no two increments overlap, that is, no read of n falls between another increment's read and its write.

At least 2, for every N of at least two.

back

Mars Pathfinder (1997)

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

In July 1997, days after landing, Mars Pathfinder's computer began to reset itself, each reset stopping the day's work (Reeves, 1997).

The cause was a priority inversion: a high-priority task waited for a lock held by a low-priority task, which medium-priority tasks kept from running.

The lock did its job: one task at a time held it. What failed was progress: the high-priority task missed a hard deadline, and the system reset. Not a deadlock: one lock, no cycle. An unbounded priority inversion: the holder was ready to run, and the scheduler kept choosing the medium tasks.

back

Priority inheritance and the priority ceiling

high priority task medium priority task low priority task time holds lock blocked on the lock held by low holds lock inherits high's priority release ready, not running holds lock deadline

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 by a patch sent from Earth.

Inheritance alone does not prevent deadlock on two locks taken in opposite order; a fixed order does, anywhere, and on one processor so does the priority ceiling protocol (Sha, Rajkumar and Lehoczky, 1990).
back
APPENDIX

Condition synchronization

semaphores, monitors and condition variables

Dijkstra's bounded buffer (1965)

Semaphore. A counter with two indivisible operations: P waits until the counter is above zero and then decreases it by one; V increases it by one. In the introduction to Part 2 of the course and in Java's library: acquire and release.*

Three semaphores around a queue of N places:

  • number of empty positions, starting at N
  • number of queuing portions, starting at 0
  • buffer manipulation, starting at 1

The one that starts at 1 is a lock: its P is acquire, its V is release, at most one process between them.

The two that count are waiting devices: a P on a counter at zero makes the producer wait for a free place, or the consumer for a portion, until the other's V.

* Dijkstra, Cooperating sequential processes, EWD 123, 1965, section 4.3.

back

The monitor

monitor entry setthe ownerwait set slots count = 0 count = 1 acquire wait release notifyAll P C C P C C C holds the lock wait: releases the lock, sleeps put, then notifyAll woken, must acquire again wait returns, holding the lock

Monitor. A module that packages some shared state, one lock that every operation on the state holds, and condition variables.*

Java: every object is a monitor; a synchronized method holds its lock, wait() and notifyAll() are its one condition variable. OCaml 5: a record with a Mutex.t and one Condition.t per thing to wait for.

* Brinch Hansen, Operating System Principles, 1973; Hoare, Communications of the ACM 17(10), 1974.

back

Example 5: the bounded buffer as a monitor

JavaOCaml 5
Buffer.javafinal Integer[] slots = new Integer[K];
int head = 0, tail = 0, count = 0;
public synchronized void put(int x)
    throws InterruptedException {
  while (count == K) wait();   // full
  slots[tail] = x;
  tail = (tail + 1) % K; count++;
  notifyAll();
}
public synchronized Integer take()
    throws InterruptedException {
  while (count == 0) wait();   // empty
  Integer x = slots[head]; slots[head] = null;
  head = (head + 1) % K; count--;
  notifyAll();
  return x;
}
buffer.mllet 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
    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)

A ring of K slots and a count. A thread that finds the ring full, or empty, releases the lock and waits, and is woken by the next take, or put.

The invariant: count items are in the ring, from head on. put and take keep it, and wait is called only while it holds.

$ java Buffer while
put:   200000 items, sum 10000100000
taken: sum 10000100000
back

Example 5 with if

The same buffer with if (count == 0) wait(); in place of the while, and likewise in put. Two producers, two consumers. What changes?

  1. Nothing: a consumer is woken only when an item has been put.
  2. A consumer woken by a put finds the buffer empty again, the other consumer having taken the item first, and takes from an empty buffer.
  3. Both consumers wait for ever.
  4. A consumer takes the same item twice.
$ java Buffer if
c1 took from an empty buffer: got null,
   at its take 6 of 100000
WhoWhatcount
C1take: count is 0, waits, releasing the lock0
C2take: count is 0, waits, releasing the lock0
Pput: stores an item; notifyAll wakes C1 and C21
C1gets the lock first, does not look again, takes the item0
C2gets the lock, does not look again, takes from an empty slot−1
back

Mesa's monitors and Hoare's

signaler waiter time wait lock signal Hoare 1974 stops wakes take lock handed over at once Mesa 1980; Java, OCaml another thread continues unlock taketakes the slot first wakes lock lock back later checks again while spurious wake-up: no signal

Hoare's monitors (1974) hand the lock over to the woken thread at once, at the signal.

Mesa's monitors (Lampson and Redell, 1980) hand the lock back later, when it is free; Java's and OCaml's condition waits are Mesa's.

So the condition is checked again, in a while.

wait may return with no notify at all, a spurious wake-up, which Java and OCaml allow.

The obligation's fourth part: every wait in a loop that checks its condition again. And notifyAll rather than notify: an object has one waiting set, and waking one thread may wake one of the wrong kind.
back