PROGRAMMING PARADIGMS · PART 2 · SESSION 7, BLOCK 2

Multi-threading

atomic instruction with retry; independence of the order

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

PART 1

Linearizability and progress

what correct means for an operation with no lock around it

The locked stackexample 7a, the reference

JavaOCaml 5
LockedStack.javarecord Node(int value, Node next) { }
Node top = null;   // under the stack's lock
synchronized void push(int x) {
  top = new Node(x, top);
}
synchronized Integer pop() {
  if (top == null) return null;
  Node old = top;
  top = old.next();
  return old.value();
}
locked_stack.mltype 'a stack =
  { mutable items : 'a list; m : Mutex.t }
let push s x =
  Mutex.protect s.m (fun () ->
    s.items <- x :: s.items)
let pop s =
  Mutex.protect s.m (fun () ->
    match s.items with
    | [] -> None
    | x :: rest -> s.items <- rest; Some x)
Java     popped + remaining = 125000500000
OCaml 5  popped + remaining = 125000500000

Four threads each push 1 to 250,000 and pop after every second push: what was popped and what remains add up to what was pushed, 125,000,500,000.

Each operation holds the stack's one lock for its whole body: pushes and pops run one after another, each taking effect at one instant inside its critical section. In OCaml, Mutex.protect m f holds the lock m for the whole of f.

One run of each is one sample; ten more runs agreed.

What may a client rely on in every run, beyond one sample?

HistoriesHerlihy and Wing, 1990

thread A thread B push(1) pop() → 2 push(2) pop() → 1 push(1) push(2) the two pushes overlap: each is called before the other has returned; so do the two pops

A history records one run as seen from outside: for each operation, the thread that called it, which operation it is with its arguments, the instant of its call, the instant of its return, and the value returned.

Two operations overlap when each is called before the other has returned.

The sequential stack is the specification: a pop returns the most recent push not yet popped, or null.

When does the sequential stack explain a history?

LinearizabilityHerlihy and Wing, 1990

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

A history is linearizable, or explained by the sequential stack, when each operation can be assigned one instant between its call and its return, its point of effect, so that the operations taken in the order of these instants form a run of the sequential stack returning what they returned in the history.

An object is linearizable when every history it can produce is.

A history with overlapping pushesthe pops returning 1 and 2

thread A thread B push(1) pop() → 1 push(2) pop() → 2

Thread A's pop returns 1, thread B's pop returns 2. Can the sequential stack explain this history?

  1. No: push(1) was called first, so the first pop must return 2.
  2. Yes: the pushes overlap, so push(2) may take effect first; the pops then return 1, then 2.
  3. No: the sequential stack explains no history with overlapping operations.
No client can tell which push took effect first: the locked stack itself produces this history when thread B takes the lock first.

Does linearizability say that an operation returns at all?

Progress conditionsHerlihy, 1991 and 1993

thread A thread B thread C stopped, never scheduled again an operation returns holds the lock waits for the lock waits for the lock an attempt fails

Blocking: a thread's progress in an operation can depend on another thread's being scheduled. Thread A holds the lock and is stopped: B and C wait for ever.

Lock-free: from any point on, as long as some thread keeps taking steps inside an operation, some operation completes within finitely many steps, whichever threads are stopped and whenever. B keeps completing; each of B's successes fails C's attempt, and C starves.

Can an operation be linearizable and lock-free, without a lock?

appendixwait-free; the clause on stopped threads; how a structure is built against the progress it guarantees
PART 2

Compare-and-set

the second way, in the four terms

The counter on compare-and-setexample 6

JavaOCaml 5
CounterCas.java// n: an AtomicInteger, from 0
static int increment() {
  int failed = 0;
  while (true) {
    int v = n.get();             // read
    if (n.compareAndSet(v, v+1)) // still v?
      return failed;             // wrote v+1
    failed++;                    // retry
  }
}
counter_cas.mllet n = Atomic.make 0

let increment () =
  let rec attempt failed =
    let v = Atomic.get n in           (* read *)
    if Atomic.compare_and_set n v (v + 1)
    then failed                 (* wrote v + 1 *)
    else attempt (failed + 1)         (* retry *)
  in
  attempt 0
Java     got 2000000, failed attempts 653147
OCaml 5  got 2000000, failed attempts 679563
fetch-and-add: got 2000000 in both

Two threads, a million calls each. Can the total be wrong, and can an attempt fail?

  1. exact; no attempt ever fails
  2. exact; an attempt fails when another thread wrote since its read
  3. wrong whenever an attempt fails
A failed attempt loses no increment: the loop reads again. Fetch-and-add, the last line, never retries.

What does this way guarantee, and what does it require?

Compare-and-set with retrythe second way, in the four terms

read v compute v + 1 compare-and-set v, v + 1 succeeded point of effect failed, another thread wrote since the read: the next attempt read v fresh, every attempt compare-and-set v, v + 1 keeps the invariant, v to v + 1

The contract. The operation is atomic without exclusion, and linearizable: its point of effect is the compare-and-set that succeeds.

The obligation. Every attempt starts from a fresh read; every write keeps the invariant, here that it replaces v by v + 1; the programmer names the point of effect.

Compare-and-set with retrythe progress risk; who checks

read v compute v + 1 compare-and-set v, v + 1 succeeded point of effect failed, another thread wrote since the read: the next attempt lock-free: every failure is another thread's success no check: a loop that keeps a stale read compiles and runs

The progress risk. A compare-and-set fails only because another succeeded, so operations keep completing: lock-free. Not wait-free: a thread may retry without end while the others keep completing operations. Fetch-and-add takes no expected value, so it never fails: wait-free, each call one step.

Who checks. Nobody but the programmer, by proof; Java and OCaml accept a loop that keeps an old value, or two atomic steps meant to be one.

Lock-free and wait-free here, deadlock and starvation in block 1: how do the four line up?

Progress conditionsHerlihy and Shavit, 2011

some thread completes every thread completes blocking non-blocking deadlock-free a global order of the locks (4c) starvation-free a ticket lock; a fair lock lock-free the loop; Treiber's stack wait-free fetch-and-add deadlock-free a global order of the locks (4c) starvation-free a ticket lock; a fair lock

The columns say who completes; the rows say what the condition assumes of the scheduler. Deadlock-freedom and starvation-freedom are the blocking counterparts of lock-freedom and wait-freedom.

The blocking row holds only while the scheduler runs every thread, the holder included: a stopped holder stops the waiters under both conditions. The non-blocking row holds whichever threads are stopped, and that is what block 1's progress failures lacked a word for.

How does a structure of many nodes change in one compare-and-set?

PART 3

Treiber's stack

how one compare-and-set changes many nodes

Treiber's stackexample 7b: push and pop as compare-and-set loops

JavaOCaml 5
Treiber.javarecord Node(int value, Node next) { }

static void push(int x) {
  while (true) {
    Node old = top.get();
    Node fresh = new Node(x, old);
    if (top.compareAndSet(old, fresh))
      return;  // point of effect: the CAS
  }
}
static Integer pop() {
  while (true) {
    Node old = top.get(); // effect if empty
    if (old == null) return null;
    if (top.compareAndSet(old, old.next()))
      return old.value(); // effect: the CAS
  }
}
treiber.mltype 'a stack = 'a list Atomic.t
(* the list is never changed, only replaced *)

let rec push (s : 'a stack) x =
  let l = Atomic.get s in
  (* point of effect: the compare-and-set *)
  if Atomic.compare_and_set s l (x :: l)
  then ()
  else push s x                    (* retry *)

let rec pop (s : 'a stack) =
  match Atomic.get s with
  | [] -> None       (* effect if empty *)
  | x :: rest as l ->
      if Atomic.compare_and_set s l rest
      then Some x      (* effect: the CAS *)
      else pop s

top is an atomic reference; the nodes are immutable, a record's fields being set once. The invariant: top points to a well-formed stack, a chain of nodes ending in null, in OCaml a list.

A push builds its node outside the stack, pointing at the top it read, and replaces top by it with a compare-and-set, which succeeds only if top is still the one it read; otherwise it reads again and builds a new node.

Java     popped + remaining
         = pushed 125000500000
OCaml 5  popped + remaining
         = pushed 125000500000

What goes wrong if a push writes top without compare-and-set?

A push without compare-and-seta read, then a write

JavaOCaml 5
Treiber.javastatic void pushBroken(int x) {
  Node old = top.get();        // read
  top.set(new Node(x, old));   // write
}
treiber.mllet push_broken (s : 'a stack) x =
  let l = Atomic.get s in      (* read *)
  Atomic.set s (x :: l)        (* write *)
Java     on the stack 307454 of 1000000 pushed
OCaml 5  on the stack 350362 of 1000000 pushed

Four threads push only, a million pushes in all. Where does it go wrong, and is it a data race?

  1. between its read and its write another push took effect, and the write loses it; not a data race, both accesses being atomic
  2. the read and the write are a data race with the other threads' writes, since nothing orders them
  3. the immutable nodes are the problem: a node cannot be re-pointed at a new top
The bug is the racy counter's: a step of another thread falls between a thread's read and the write that depends on it. An atomicity violation without a data race.

Why is the stack with compare-and-set correct?

Proof sketch for Treiber's stackthe invariant; the points of effect

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

The invariant. top points to a well-formed stack, the list of values from the top node down to null. It holds at the start; every write to top is a compare-and-set that keeps it; a failed attempt writes nothing.

The points of effect. For a push, the compare-and-set that succeeds. For a pop on a non-empty stack, the same. For a pop on an empty stack, the read that saw top null.

Proof sketch for Treiber's stacksafety; liveness

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

Safety. In the order of the points of effect, the operations form a run of the sequential stack: between two of them top does not change, and each does one sequential push or pop and returns what it returns.

Liveness. An attempt fails only because another thread's succeeded since its read, and each success completes an operation; so operations keep completing: lock-free, and not wait-free.

Where does the method of nodes that never change come from?

appendixthe ABA problem: a top that changes and comes back, with a garbage collector and without

Persistent data structures and compare-and-setHerlihy, 1993

ref r1 L R version 1 r2 L′ version 2 shares R CAS read the reference copy; apply the operation compare-and-set the ref failed point of effect

A persistent structure keeps its old version usable after an update; the new version shares the unchanged part. Treiber's stack is such a value behind one atomic reference, and a read of the reference is a snapshot of the whole stack.

Herlihy, 1993. Read the reference, apply the operation to a copy, swing the reference to the copy with a store-conditional, which fails if anything wrote since the read; retry on failure.

Persistent data structures and compare-and-setClojure's atom

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

Clojure's swap! applies a function to the value in an atom, an atomic reference, by that protocol on compare-and-set: read, apply, compare-and-set, retry.

Under contention the function runs several times: in three runs, 800,000 swaps ran it between 4.2 and 4.6 million times. So it must have no effects, and nothing checks it. Java's updateAndGet is the same loop with the same warning.

Is a structure without a lock always the better choice?

PART 4

Contention

whether lock-free is always better

Lock-free against lock-basedcontention

top thread 1 thread 2 thread 3 one succeeds the others fail and retry: wasted steps every operation passes through the top flat combining request 1 request 2 request 3 request 4 one thread, under the lock the structure one thread performs every request; the others publish theirs and wait

Contention. Several threads want the same word at once: one attempt succeeds, the rest are wasted work, and every operation on the stack passes through the top. An uncontended lock costs one step, like one attempt.

Flat combining. Each thread publishes its request; one thread, under a coarse lock, performs them all: lock-based, blocking, and faster (Hendler, Incze, Shavit and Tzafrir, 2010).

What if the threads share nothing while they run?

appendixoperations on the whole structure; where only a non-blocking structure will do; the universality of compare-and-set
PART 5

Deterministic parallelism

the third way: nothing shared while the threads run

A count per thread, then the sumexample 8 (a), the counter's third version

JavaOCaml 5
PerThread.javafinal int N = 1_000_000;    // per thread
long[] counts = new long[2];
Thread[] ts = new Thread[2];
for (int t = 0; t < 2; t++) {
  final int id = t;
  ts[t] = new Thread(() -> {
    long mine = 0;             // local
    for (int i = 0; i < N; i++) mine++;
    counts[id] = mine;
  });
}
for (Thread t : ts) t.start();
for (Thread t : ts) t.join();
System.out.println(counts[0] + counts[1]);
per_thread.mllet count () =
  let c = ref 0 in                  (* local *)
  for _ = 1 to 1_000_000 do incr c done;
  !c

let per_domain () =
  let a = Domain.spawn count
  and b = Domain.spawn count in
  Printf.printf "got %d\n"
    (Domain.join a + Domain.join b)
Java     2000000
OCaml 5  got 2000000

Each thread counts in a variable of its own; the order in which the threads run cannot matter, because no location written by one thread is read or written by another while they run.

The argument rests on the join, which orders each thread's write of its element of counts before the main thread's read. Without it the program has a data race and may print 0, one million or two million.

In Rust the compiler checks that nothing is shared, by giving each slot one owner; in Haskell the types do, since a pure function cannot write a cell. In Java, nobody does.

Does every split of the work give the same result?

The parallel foldexample 8 (b) and (c): 1 to 8 from 0, with + and with −

A fold combines the elements of a sequence with an operation, one after another from a starting value, the seed. Here the sequence 1 to 8 is cut into parts; each part is folded from the seed 0 on a thread of its own; after the joins the parts' results are combined with the same operation, in the order of the parts.

+ in two halves 36, in four quarters 36
- in two halves 16, in four quarters  0
Java and OCaml 5 print the same

The sequential fold with subtraction, one thread from left to right, gives −36. Which is true of the parallel fold?

  1. it agrees in two halves and in four quarters, and the answer is the same on every run: the threads only share the work
  2. it agrees in neither, and the answer is the same on every run
  3. it agrees in neither, and the answer changes from run to run: it depends on which thread finishes first
With subtraction the answer depends on how the sequence is split, never on which thread finishes first. If the operation has no side effects and is associative, every part is folded from its identity, and the parts are combined in their order, every split gives the sequential fold's answer.

Two bracketings of one foldsubtraction on 1 to 8

two halves four quarters 1 2 3 4 5 6 7 8 −10 −26 16 each part folded from 0 −10 − (−26) 1 2 3 4 5 6 7 8 −3 −7 −11 −15 4 4 0 4 − 4

The parts are the same numbers in the same order; only the bracketing differs, and the roots differ. With addition both roots are 36, as is the sequential fold, because addition is associative.

Which forms does independence of the order take?

The forms of the third wayindependent parts; commuting updates

thread 1 part 1 thread 2 part 2 thread 3 part 3 combine, in order result nothing shared while the parts run; the combine associative, with an identity thread 1 +1 thread 2 +1 thread 3 +1 n one atomic step each: any order gives the same total or a replica per thread, merged at the end

Independent parts and a combine step. No location written by one thread is read or written by another while they run; the combine has no side effects and is associative with an identity, and the parts are combined in their order.

Commuting updates. Each update is one atomic step, or goes to a replica merged at the end; the interleaving orders the steps, and commutativity makes the final state the same for every order.

The forms of the third waydeterminism by construction; immutability

program 1 queue one writer, one reader program 2 queue one writer, one reader program 3 the same function in every schedule (Kahn, 1974); single-assignment variables do the same an immutable value the second way: Treiber's nodes, copy-and-swap the third way: nothing shared, because nothing mutable not a fourth way

Determinism by construction. A dataflow network, sequential programs connected by queues with one writer and one reader each, computes the same function in every schedule (Kahn, 1974); single-assignment variables do the same.

Immutability is not a fourth way: it serves the second, Treiber's nodes and copy-and-swap, and the third, nothing shared because nothing mutable.

The counter and the stack comparedwhich work the third way is for

thread 1 +1 thread 2 +1 thread 3 +1 n = 3 in every order one intended result, the same for every order: the third way's work thread 1 pushes a thread 2 pushes b b a or a b the pops show which came first no single intended result; linearizability suffices

The counter. Increments commute: applying them in any order gives the same total. So when each increment is atomic, under a lock or by one instruction, or is made in a slot of its own, every way gives the same final value.

The stack. Two pushes on a shared stack do not commute, and the pops show which came first: the result depends on the interleaving under every way; the only demand on it is linearizability.

Each way makes one operation atomic: are two atomic operations together atomic?

PART 6

Composition

whether two atomic operations are one

Compositionexample 4 (a), the transfer in two halves

JavaOCaml 5
Accounts.javastatic void transferA(Account from,
                      Account to, int x) {
  synchronized (from) { from.balance -= x; }
  synchronized (to)   { to.balance   += x; }
}
accounts.ml(* lock w a: take account a's mutex; w records
   who holds what, for the deadlock watchdog *)
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
Java     first wrong reading: A = 99, B = 100
OCaml 5  first wrong reading: A = 234, B = -35

The two balances add up to 200 between transfers. A reader holding both locks sees 199: it read between the two halves of a transfer. Two atomic steps are not one atomic step, under locks or under compare-and-set.

Two linearizable objects used together are a linearizable system, each operation at its own instant: Herlihy and Wing's locality. What is not given is one instant for two operations: the withdrawal and the deposit each have theirs.

appendixone instant for two operations: both locks, one reference, or a transaction

Every argument so far assumed that a run is an interleaving: who guarantees that?

PART 7

Memory models

the fourth assumption's condition

The memory model's guaranteethe fourth assumption, with its condition

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

There is one memory, and every read returns the value of the latest write before it in the interleaving (Lamport, 1979: sequential consistency). The language guarantees it for every program none of whose interleavings has a data race, with its atomics in the strongest mode.

Why a guarantee. Processor and compiler reorder reads and writes for speed. Adve and Hill, 1990: a race-free program still runs as one sequence; the language's memory model says so.

The memory model's guaranteethe session's programs

the spin lock release: atomic write of the flag acquire: test-and-set synchronizes the count per thread the thread's last step the join synchronizes Treiber's stack the node built, then top written top read, then the node synchronizes every access is ordered by one of these: no data race, so the guarantee applies every run behaved as an interleaving; the reasoning by interleavings was sound

What made the session's programs race-free. In the spin lock, the order test-and-set gives between one thread's release and the next's acquire; in the count per thread, the join; in the loop and Treiber's stack, every access to top atomic, the nodes published through it.

The guarantee applied to them: every run behaved as an interleaving; the reasoning by interleavings was sound.

What does the language guarantee for a program with a data race?

The cost of a data raceexample 4 (d) of block 1, the reader with no lock

JavaOCaml 5
Accounts.javastatic int[] readUnlocked() {   // no lock
  return new int[] { A.balance, B.balance };
}
accounts.ml(* the reader with no lock: a data race *)
let read_unlocked () = (a.balance, b.balance)
Java     138670249 readings, 20954124 wrong
OCaml 5  109518919 readings, 2611258 wrong

The transfers take their locks in a global order; the reader takes none. Its two reads are each a data race. What does the language guarantee for it?

  1. nothing: a racy program has no meaning in any language
  2. every run is some interleaving: the transfers are locked
  3. no guarantee of an interleaving; what remains is set by each language's memory model, and in Java and OCaml 5 a race is bounded
C and C++: undefined behaviour. Java: a read returns a value once written to that variable, bounded in space. OCaml 5: also bounded in time. Go: like Java for one word. Safe Rust: no data race can be written.

Three ways, four terms each: how do they read side by side?

PART 8

Summary

the table of the three ways

The ways compared

The wayContractObligationProgress riskWho checks
Mutual exclusion: forbid the interleavingatomic by exclusion; linearizable by constructionevery access under the lock; the invariant; a global order of the locksdeadlock, starvation; a stopped holder stops the threads that wait for its locknot the language (Java, C, C++, Go); a detector at run time (Go, ThreadSanitizer); the compiler (Rust, data races)
Atomic instruction with retry: detect it and retryatomic without exclusion; linearizable at a point of effectthe loop re-reads; the invariant; the point of effect namedlock-free, not wait-free: a thread may retry for ever; fetch-and-add wait-freethe programmer, by proof; the collector removes ABA when no node is reused; checkers of histories
Independence of the order: make it irrelevanta deterministic final resultindependent parts and an associative combine in order; or commuting atomic updates; or determinism by constructionnone from interleaving; the join waits for every workerthat nothing is shared, the type system can; associativity or commutativity, the programmer only
appendixnine languages: what the programmer expresses, who checks, what a race costs, what holds by construction

Conclusion of block 2

The session's question. Three questions of any program: which contract it chooses, how that contract is stated, and which obligation is left to the programmer.

The lab builds four structures in Java, each with its contract and a check: the counter in three versions, worker threads, the bounded buffer, and a barrier as the extension. Then it makes a small ray tracer multi-threaded with them, so that each mistake shows in the picture.

Workers. The thread that starts the workers owns them and joins them. Stopping is a request through a flag, which ends nothing by itself.

The mini-project builds the bounded buffer as a queue in three versions, with one lock, with two locks and without locks, behind one interface, with a checker of histories and a measurement of throughput.

  • Session 8: no sharing at all, by messages.
  • Session 9: transactions, snapshot isolation, and the structures that merge replicas.
  • Session 12: types for concurrency.
APPENDIX

Progress, universality and composition

wait-free; the ABA problem; the whole structure; consensus numbers; transactions; the languages compared

Progress conditionswait-free; the clause

thread A thread B thread C stopped, never scheduled again an operation returns if A may run, A finishes

Wait-free: every thread that keeps taking steps inside an operation completes it within a finite number of its own steps, whichever other threads are stopped and whenever. B and C both complete.

The clause "whichever threads are stopped" is what makes these conditions about progress: without it a lock would count as lock-free, since a holder that is allowed to run finishes.

back

Construction and progress

non-blocking blocking lock-free wait-free lock-based without locks spin lock; synchronized impossible impossible the Disruptor the loop; Treiber's stack fetch-and-add the Disruptor

Lock-based and without locks say how a structure is built; blocking, lock-free and wait-free say what progress it guarantees, and nothing else. A lock-based structure is never lock-free.

A structure built without locks is not thereby lock-free: the Disruptor, a queue over a ring buffer, has no lock on its path and still blocks.

back

The ABA problemthe hazard; on this stack

thread 1, in pop thread 2 the stack after the event reads top = a, next = b top a b c pops a, pops b top c pushes a again top a c compare-and-set a → b: succeeds top b c b was popped: corrupted pushes x top x a b c pops x top a b c same node a compare-and-set a → b: succeeds top b c right

The hazard. A thread reads a location as A; other threads change it to B and back to A; the thread's compare-and-set, expecting A, succeeds although the structure it reasoned about may have changed.

On this stack. A push and a pop between the read and the compare-and-set leave the very node read at the top again: harmless, since that node, never changed, heads the same chain.

back

The ABA problemwith a collector; without one

thread 1, in pop thread 2 the stack after the event reads top = a, next = b top a b c pops a and b; not freed top c a and b still held by thread 1 pushes 9: a fresh node top 9 c a new address compare-and-set a → b: fails top 9 c right: thread 1 re-reads pops a and b: both freed top c a and b freed pushes 9 at a's address top 9 c the address a again compare-and-set a → b: succeeds top b c top = b, freed: corrupted

The garbage collector. A node any thread still holds is never freed, so its address is never reused, and every push allocates a fresh node: a different node at the same address cannot arise.

Without a collector. In C or C++ a popped node may be freed and its memory reused. A stale pop may read next from freed memory, a use after free, or, as here, install a freed node as the top. Hazard pointers and epochs delay the freeing of a node until no thread can still hold it.

back

Lock-free against lock-basedthe whole structure; the progress guarantee

nodes changed in place top 7 4 9 5 size traverses while nodes change: no instant of the whole a persistent value behind one reference the read of the reference is a snapshot of the whole under a lock thread A thread B waits for A's lock, for ever without one thread A thread B nobody waits

Operations on the whole structure. Where nodes change in place there is no instant at which the whole is unchanged: Java's ConcurrentLinkedQueue.size traverses and may be inaccurate. A persistent value behind one reference has that instant, the read of the reference.

Progress guarantee. A stopped lock holder stops every waiter; a thread stopped in mid-push stops nobody. Where that must hold, only a non-blocking structure will do.

back

Universality of compare-and-setHerlihy, 1991

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

Every structure. With compare-and-set, every object with a sequential specification has a wait-free, linearizable version; with reads and writes alone, not even a stack that two threads share.

The construction. Every operation is appended to one shared list, which every thread applies in the same order to a copy of its own; a thread that appends also appends the operation of the thread whose turn it is. Nothing runs in parallel.

back

Ways to composelocks; one reference

lock A, lock B, in the global order withdraw from A deposit to B unlock B, unlock A one operation; the price: deadlock, and a global order of locks ref {A: 100, B: 100} {A: 90, B: 110} CAS the transfer: one compare-and-set every update of the dictionary competes for this one reference

Locks compose by hand. Both locks around both steps make the transfer one operation, at the cost of deadlock and a global order of the locks.

One compare-and-set covers one reference. Both accounts behind one reference to a persistent dictionary: the transfer is one compare-and-set, and every update of the dictionary competes for that reference, the cost of Clojure's atom.

back

Ways to composetransactions

atomically withdraw from A deposit to B both writes take effect here, or not at all on a conflict with another transaction, the runtime runs it again Clojure, eight threads, 800,000 transfers, the course's run a reader inside a transaction never wrong, in 4,352,597 reads a reader outside wrong 5,345 times Haskell: the counter under atomically exact, ten runs of ten

Transactions compose, lock-based operations do not (Harris et al., 2005). A transaction's writes take effect together, at one instant, or not at all; on a conflict the runtime reruns it.

In the course's runs, Haskell's counter under atomically was exact in ten runs of ten; in Clojure, with 800,000 transfers in one dosync each, a reader inside a transaction was never wrong and a reader outside one was wrong 5,345 times.

back

Languages with shared memoryJava, OCaml 5, Rust

LanguageWhat the programmer expressesWho checksWhat a race costsWhat holds by construction
Javalocks, atomics with four modes, volatile, join; all three waysnobody in the language or the JDKdefined; a value once written to that variable; bounded in space, not in timea correctly synchronized program runs as an interleaving
OCaml 5Mutex, Condition, Atomic, Domain.join; all three waysnothing in the compiler; a ThreadSanitizer build at run timedefined; bounded in space and in timea race-free program, and every race-free location, runs as an interleaving
Rustownership; a Mutex<T> owning its data; atomics with a mode per accessthe compiler, data races onlycannot be written in safe Rustshared or mutable, never both, unless a lock or an atomic is between
back

Languages with shared memory, continuedGo, C and C++, Haskell

LanguageWhat the programmer expressesWho checksWhat a race costsWhat holds by construction
Gosync.Mutex, atomics, channels; sharing allowed, the proverb advises against itthe race detector at run timeone word like Java; several words, memory corruptiona race-free program runs as an interleaving (2022)
C, C++std::mutex, std::atomic with a mode per accessnobody; ThreadSanitizer at run timeundefined behaviourrace-free, with mutexes and default atomics: an interleaving
Haskellpure functions; mutation in typed cells; atomicallythe types: a pure function cannot mutate; a transaction cannot do I/Oa read then a write on an IORef loses updates, as the racy counteran ordinary value cannot change; transactions compose
back

Languages that limit shared mutationErlang, Clojure, JavaScript

LanguageWhat the programmer expressesWho checksWhat a race costsWhat holds by construction
Erlangprocesses that share no heap, send copied messages; ETS tables are sharednothing between heaps; nobody on ETS tablesno data race between processes; a get then a set by messages still loses updatesa process's state is its own, one message at a time
Clojureimmutable values; an atom (swap!); refs with dosync; agentsnothing: the function of swap! should be pure, and nothing enforces itthe function of swap! runs once per attempt; its effects repeatan atom's value replaced as a whole; a transaction sees a snapshot
JavaScriptworkers that receive copies; SharedArrayBuffer and Atomics by choicenothinga plain ++ on a shared array loses updates; Atomics.add does notwithout a shared buffer nothing is shared; one thread per worker
back