本书暂未推出简体中文版。现有版本:English。
University Computer Science — Year 3 · 本科三年级
13Concurrency: Deadlock, Monitors and Lock-Free Structures
Two threads that share memory can do together what neither can do alone, and they can also wait for each other for ever, take the same item twice, or see each other’s writes in an order neither of them wrote. This chapter states precisely what a concurrent program must guarantee, then studies the three ways it most often fails. Deadlock is characterised, prevented and detected, and five philosophers at a round table are explored state by state until every interleaving has been seen. Monitors package a lock and its conditions, and a scripted scheduler shows why the condition must be tested in a loop. Finally the processor itself is questioned: a two-line test, run 100,000 times on the laptop, catches it reordering a write and a read, and a stack built without locks is broken and repaired.
You already know
In the Year 2 volume the threads of a process share its memory and run interleaved, in an order nobody controls. A race condition makes a result depend on that order; a lock, or mutex, gives one thread at a time a critical section; a thread holding a lock can sleep on a condition variable until another signals it; a semaphore counts permits. An atomic operation happens as one indivisible step, and Peterson’s algorithm gives mutual exclusion to two threads with ordinary loads and stores. A thread that waits for ever while others keep running is starving. The Year 1 volume found cycles in directed graphs by depth-first search.
13.1 Safety and liveness
An execution of a concurrent program is a sequence of steps, each taken by one thread, as an interleaving of the threads’ own sequences. A property of the program is a property of all its executions.
Definition 13.1 (Safety property, liveness property)
A safety property says that something bad never happens: if an execution violates it, some finite prefix of the execution already shows the violation, and no continuation can repair it. A liveness property says that something good eventually happens: no finite prefix can violate it, since the good thing may still come.
Mutual exclusion is a safety property: two threads inside the critical section at once is a bad step, seen in a finite prefix. “Every thread that wants the lock eventually gets it” is a liveness property: at any finite moment the waiting thread might still get it later. A program that does nothing is perfectly safe; liveness is what forces it to make progress, and the two are proved differently, safety by an invariant that every step preserves, liveness by a measure that every step brings closer to the goal.
Definition 13.2 (Deadlock, livelock, Coffman conditions)
A set of threads is in deadlock when each of them waits for something that only another thread of the set can provide, so that none of them will ever move again. In a livelock the threads keep taking steps, but none of the steps makes progress. The Coffman conditions for a deadlock over resources are: mutual exclusion (a resource is held by one thread at a time), hold and wait (a thread holds resources while it waits for others), no preemption (a resource is released only by its holder), and circular wait (a cycle of threads, each waiting for a resource the next one holds).
The four conditions are named after the first to describe them, E. G. Coffman, M. Elphick and A. Shoshani, in a survey of 1971. They are all necessary, so breaking any one of them prevents deadlock: a resource that can be shared, a thread that requests everything at once, a resource that can be taken back, or an order on the requests. Deadlock is a safety failure, since a finite prefix reaches a state with no way out. Livelock and starvation are liveness failures: steps go on, and the good thing never happens.
13.2 Deadlock
Definition 13.3 (Resource-allocation graph, lock ordering)
A resource-allocation graph has a node for each thread and each resource, an edge when thread waits for resource , and an edge when is held by . Lock ordering fixes a total order on the locks and requires every thread to acquire the locks it holds together in increasing order.
rag_cycle.py finds the cycle by depth-first search; with P3’s request withdrawn, it finds none.Theorem 13.4 (Cycles and deadlock)
When every resource has a single instance and a waiting thread waits for one resource, the threads of a cycle in the resource-allocation graph are deadlocked; and if some threads are deadlocked, the graph has a cycle.
Proof. Facts used: each resource node has at most one outgoing edge (one holder), each waiting thread exactly one (one request), and a waiting thread does not move until its resource is released.
A cycle alternates threads and resources: . waits for , held by , which releases it only after it moves, and waits for , and so on round the cycle: no thread of the cycle can be the first to move, so none ever moves.
Conversely, let be a set of deadlocked threads. Start at any : it waits for a resource, whose holder is in (only a thread of can provide it), and that thread waits in turn. Following these edges from never leaves the graph’s finitely many nodes and never stops, since each node on the way has an outgoing edge; so it returns to a node already visited, and that loop is a cycle. ∎
With several instances of a resource, a cycle is necessary but no longer sufficient: another instance may be freed by a thread outside the cycle (exercise 13.6 detects deadlock in that case).
Theorem 13.5 (Lock ordering prevents deadlock)
If every thread acquires its locks in increasing order of one total order, no set of threads waiting for locks can be deadlocked.
Proof. Facts used: theorem 13.4; a thread waiting for lock holds only locks smaller than , since it acquires in increasing order.
Suppose a deadlock. By theorem 13.4 there is a cycle . holds and waits for , so ; likewise , …, , since holds and waits for . Then , impossible. ∎
Five philosophers sit round a table, each with a plate, and one fork lies between each pair of plates. A philosopher thinks, gets hungry, takes the fork on the left, then the fork on the right, eats, and puts both down. Edsger Dijkstra posed the problem with five philosophers and rejected this naive protocol, one lock per fork, because of the deadlock it allows: if all of them take their left fork at once, each waits for ever for the right one. The deadlock is easy to state; it is more instructive to find it, together with every other state, by trying all interleavings (Listing 13.1).
def moves(state, n, ordered):
"""Every step one philosopher can take: (philosopher, next state)."""
pcs, owner = state
for i, pc in enumerate(pcs):
first, second = forks(i, n, ordered)
if pc == THINK and owner[first] is None: # take the first fork
yield i, step(state, i, HOLD1, {first: i})
elif pc == HOLD1 and owner[second] is None: # take the second: eat
yield i, step(state, i, EAT, {second: i})
elif pc == EAT: # put both down
yield i, step(state, i, THINK, {first: None, second: None})
def step(state, i, pc, changes):
pcs, owner = state
pcs, owner = list(pcs), list(owner)
pcs[i] = pc
for f, who in changes.items():
owner[f] = who
return tuple(pcs), tuple(owner)
def explore(n, ordered=False):
start = ((THINK,) * n, (None,) * n)
seen, todo, dead = {start}, deque([start]), []
while todo:
state = todo.popleft()
nexts = [s for _, s in moves(state, n, ordered)]
if not nexts:
dead.append(state)
for s in nexts:
if s not in seen:
seen.add(s)
todo.append(s)
return seen, dead
ordered, each philosopher takes the lower-numbered of its forks first. code/bachelor-3/13-concurrency/listings/philosophers.py$ python philosophers.py
n naive: states deadlocked ordered: states deadlocked
2 6 1 5 0
3 14 1 12 0
4 34 1 29 0
5 82 1 70 0
6 198 1 169 0
7 478 1 408 0
the deadlocked state for n = 5: ((1, 1, 1, 1, 1), (0, 1, 2, 3, 4))
There is exactly one deadlocked state for every , and ordered acquisition removes it, as theorem 13.5 promised: only the last philosopher’s order changes, since its forks are and . The number of states grows by a factor of about 2.4 per philosopher; the weekend problem explains the numbers exactly.
Prevention constrains every program in advance. Dijkstra’s banker does better when each thread declares in advance the most it will ever need of each kind of resource: it grants a request only if the state after it is safe.
Definition 13.6 (Safe state, banker’s algorithm, deadlock detection)
Each thread declares a maximum claim; it holds and may still ask for , the claim minus what it holds; is what nobody holds. A state is a safe state if there is an order of the threads in which each can be given its whole from what is available plus what the threads before it have returned, then finish and return everything. The banker’s algorithm grants a request only if the state after granting it is safe, and otherwise makes the thread wait. Deadlock detection lets threads request freely, and from time to time searches for a set of threads deadlocked in the current state, to break the deadlock by killing or rolling back one of them.
def safe_order(available, alloc, need):
"""An order in which all processes can finish, or None if the state is unsafe."""
work, done, order = list(available), [False] * len(alloc), []
while len(order) < len(alloc):
for i in range(len(alloc)):
if not done[i] and all(n <= w for n, w in zip(need[i], work)):
work = [w + a for w, a in zip(work, alloc[i])] # i finishes, frees all
done[i] = True
order.append(i)
break
else:
return None # nobody can finish with what is left
return order
def request(i, req, available, alloc, need):
"""Grant req to process i if the resulting state is safe; returns the new state."""
if any(r > n for r, n in zip(req, need[i])):
raise ValueError("more than its declared maximum")
if any(r > a for r, a in zip(req, available)):
return None # must wait: not enough free now
available = [a - r for a, r in zip(available, req)]
alloc = [row[:] for row in alloc]
need = [row[:] for row in need]
alloc[i] = [a + r for a, r in zip(alloc[i], req)]
need[i] = [n - r for n, r in zip(need[i], req)]
if safe_order(available, alloc, need) is None:
return None # granting it could lead to deadlock: wait
return available, alloc, need
$ python banker.py
available [2, 1, 2] need [[3, 1, 2], [1, 2, 1], [2, 2, 2], [1, 1, 1], [3, 1, 1]]
safe order: [3, 0, 1, 2, 4]
P1 asks for [1, 0, 0]: refused: unsafe
P4 asks for [1, 0, 1]: granted; safe order [3, 4, 0, 1, 2]
Theorem 13.7 (The greedy safety test)
safe_order returns an order if and only if the state is safe.
Proof. Facts used: a thread that finishes returns everything it holds, so never decreases; a thread that can finish with some can finish with any larger one.
If it returns an order, each thread in it had its covered by when chosen, which is the definition of a safe order. Conversely, suppose the state has a safe order , and suppose the greedy loop stops early with a set of threads left over. Let be the first thread of in . The threads before in are all finished by the greedy loop, so the greedy is at least what offers , which covers : the loop could still choose , and does not stop. So it never stops early. ∎
A safe state is not deadlocked, and an unsafe state is not necessarily deadlocked either: threads may finish without ever asking for their whole claim. The banker refuses whenever deadlock becomes possible, not only when it is certain, and the price is throughput and a maximum claim known in advance. Exercise 13.10 proves that it keeps its promise.
13.3 Monitors
Definition 13.8 (Monitor, Hoare semantics, Mesa semantics)
A monitor is a module whose data are reached only through its procedures, which run under one lock, one thread at a time; a thread inside may wait on a condition variable, which releases the lock, until another thread signals it. Under Hoare semantics the signaller hands the monitor at once to the woken thread, which therefore finds the condition true. Under Mesa semantics the woken thread only becomes ready; it runs later, after reacquiring the lock, when another thread may have entered first and made the condition false again.
C. A. R. Hoare’s Monitors appeared in the Communications of the ACM in October 1974, and Lampson and Redell’s account of monitors in the Mesa language in February 1980. POSIX condition variables follow Mesa, and add that a wait may return with no signal at all, a spurious wake-up: the standard asks the caller to test its condition again on every return. So the wait goes inside a while, as in the bounded buffer of Listing 13.3.
static struct {
pthread_mutex_t lock;
pthread_cond_t not_full, not_empty;
long items[CAP];
int head, count;
} buf = {.lock = PTHREAD_MUTEX_INITIALIZER, .not_full = PTHREAD_COND_INITIALIZER,
.not_empty = PTHREAD_COND_INITIALIZER};
void put(long x) {
pthread_mutex_lock(&buf.lock);
while (buf.count == CAP) /* while, not if: recheck after waking */
pthread_cond_wait(&buf.not_full, &buf.lock);
buf.items[(buf.head + buf.count) % CAP] = x;
buf.count++;
pthread_cond_signal(&buf.not_empty);
pthread_mutex_unlock(&buf.lock);
}
long take(void) {
pthread_mutex_lock(&buf.lock);
while (buf.count == 0)
pthread_cond_wait(&buf.not_empty, &buf.lock);
long x = buf.items[buf.head];
buf.head = (buf.head + 1) % CAP;
buf.count--;
pthread_cond_signal(&buf.not_full);
pthread_mutex_unlock(&buf.lock);
return x;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o monitor_buffer monitor_buffer.c -lm && ./monitor_buffer
items taken: 40000 of 40000
sum taken: 800020000, expected 800020000
left in the buffer: 0
Nothing in C stops a thread from touching buf.count without the lock. In Rust the mutex owns the data: the only way to the buffer is the guard that lock returns, and wait consumes the guard and gives a new one back (Listing 13.4).
impl Buffer {
fn put(&self, x: u64) {
let mut items = self.items.lock().unwrap();
while items.len() == CAP {
items = self.not_full.wait(items).unwrap(); // gives the lock back, retakes it
}
items.push_back(x);
self.not_empty.notify_one();
} // the guard is dropped here: unlocked
fn take(&self) -> u64 {
let mut items = self.items.lock().unwrap();
while items.is_empty() {
items = self.not_empty.wait(items).unwrap();
}
let x = items.pop_front().unwrap();
self.not_full.notify_one();
x
}
}
$ rustc --edition 2021 -O -o monitor_rust monitor_rust.rs && ./monitor_rust
items taken: 40000 of 40000
sum taken: 800020000, expected 800020000
left in the buffer: 0
Why the while? A bug that needs a particular interleaving rarely shows in a test run, so monitor_sim.py runs a monitor under a script: each thread is a Python generator that stops at every wait, and the script decides who runs next (Listing 13.5).
def consumer(buf, use_while):
if use_while:
while not buf:
yield "wait" # releases the monitor; resumes holding it
elif not buf:
yield "wait"
return f"takes {buf.pop(0)}" if buf else "takes from an empty buffer!"
def producer(buf):
buf.append("item")
yield "signal" # wake one waiting consumer
return "leaves"
yield is where a thread leaves the monitor to wait; run, in the same file, resumes the threads in the order the script gives, wakes a waiter on a signal under either semantics, and treats ~C1 as a spurious wake-up of C1. code/bachelor-3/13-concurrency/listings/monitor_sim.py$ python monitor_sim.py
Hoare if | C1 waits, P puts an item and signals, C1 takes item, P leaves, C2 waits
Hoare while | C1 waits, P puts an item and signals, C1 takes item, P leaves, C2 waits
Mesa if | C1 waits, P puts an item and signals, P leaves, C2 takes item, C1 takes from an empty buffer!
Mesa while | C1 waits, P puts an item and signals, P leaves, C2 takes item, C1 waits
if lets C1 take from an empty buffer.Under Hoare semantics the woken C1 runs at once and finds the item; under Mesa semantics C2 barges in first, and only the while sends C1 back to sleep. With spurious wake-ups even Hoare’s guarantee is gone (exercise 13.5). The rule costs one test per wake-up and removes a whole class of bugs.
13.4 Memory models and atomic operations
Every argument so far assumed that the threads’ steps interleave: that a write by one thread is seen by the others at once, in program order. Lamport gave that assumption its name in 1979: a multiprocessor is sequentially consistent if every execution gives the same result as some sequential order of all the processors’ operations, each processor’s in the order of its program.
Definition 13.9 (Memory model, sequential consistency)
A memory model specifies which values each read of a shared location may return in a concurrent program. Under sequential consistency every execution behaves as some interleaving of the threads’ operations, each thread’s in its program order, every read returning the latest write before it in that interleaving.
Take two variables x and y, both 0. Thread 1 writes and then reads y into ; thread 2 writes and then reads x into . Under sequential consistency is impossible: in the interleaving, consider whichever of the two reads comes last; both writes came before it, since each write precedes its own thread’s read, so that read returns 1. Three outcomes remain. Listing 13.6 runs the test.
static void meet(int i, int delay) {
atomic_fetch_add(&arrived, 1);
while (atomic_load(&arrived) < 2 * (i + 1)) { /* spin until the other one is here */ }
for (volatile int k = 0; k < delay; k++) { }
}
/* The order must be a constant: given a variable, the compiler takes the strongest. */
#define THREAD(name, mine, other, r, delay, order) \
static void *name(void *arg) { \
(void)arg; \
for (int i = 0; i < TRIALS; i++) { \
meet(i, delay[i]); \
atomic_store_explicit(&mine[i], 1, order); \
r[i] = atomic_load_explicit(&other[i], order); \
} \
return NULL; \
}
THREAD(relaxed1, x, y, r1, delay1, memory_order_relaxed)
THREAD(relaxed2, y, x, r2, delay2, memory_order_relaxed)
THREAD(seqcst1, x, y, r1, delay1, memory_order_seq_cst)
THREAD(seqcst2, y, x, r2, delay2, memory_order_seq_cst)
$ gcc -std=c17 -O2 -Wall -Wextra -o sb_litmus sb_litmus.c -lm && ./sb_litmus
100000 trials each
relaxed r1=0 r2=0: 10796 r1=0 r2=1: 47396 r1=1 r2=0: 41745 r1=1 r2=1: 63
seq_cst r1=0 r2=0: 0 r1=0 r2=1: 32377 r1=1 r2=0: 63003 r1=1 r2=1: 4620
The first version of this listing passed the order to the threads in a variable, and found the forbidden outcome zero times out of 100,000 for both orders. The compiler’s assembly showed why: given a memory order it cannot see at compile time, gcc compiled the store as for memory_order_seq_cst, which is what the macro’s comment now warns about.
The processor allows it. Picture each core of an x86 processor with a store buffer, a first-in first-out queue of its pending writes, drained to memory later so that the core need not wait for each write: thread 1’s read of y can complete while still sits in its buffer, invisible to thread 2, as drawn below. The x86-TSO model of Peter Sewell and colleagues explains the store-buffering outcome exactly this way, and gives the processor’s behaviour a precise definition. Peterson’s algorithm, which writes its own flag and then reads the other’s, is exactly this pattern, and fails on such a machine unless its operations are made sequentially consistent.
Definition 13.10 (Read-modify-write operation, compare-and-swap, acquire and release ordering)
A read-modify-write operation reads a location and writes it in one atomic operation, as atomic_fetch_add does. Compare-and-swap (CAS) is the read-modify-write that, given a location, an expected value and a new value, writes the new value only if the location holds the expected one, and reports whether it did. A load with acquire ordering keeps every later read and write of its thread after it; a store with release ordering keeps every earlier read and write of its thread before it. A thread whose acquire load reads the value of another thread’s release store sees all the writes that thread made before the store.
C11’s <stdatomic.h> gives every atomic operation sequentially consistent ordering by default, and an _explicit form takes one of the weaker orders: relaxed, acquire, release, acquire-release, or the default. Acquire and release are the pattern of a lock and of a message: write the data, then set a flag with a release store; the reader that sees the flag with an acquire load sees the data. On x86 they cost no extra instruction, only constraints on the compiler; the sequentially consistent store of the litmus test is the one that costs a barrier. The order that the release and acquire pairs build between threads is often called a happens-before order, and it is all they promise: what a thread wrote before a release is seen by the thread whose acquire reads that release’s value. It is not sequential consistency. The store-buffering test written with release stores and acquire loads still allows , since nothing keeps a thread’s store before its own later load of another location; on x86 that code compiles to the same plain moves as the relaxed run above, which shows the outcome 10,796 times. The guarantee that does hold is for programs without data races: if every shared location is either accessed under a lock or only through sequentially consistent atomic operations, the program behaves as if the memory were sequentially consistent.
13.5 Lock-free structures
A lock serialises; if its holder is preempted, everybody waits. A structure built from CAS alone guarantees progress differently.
Definition 13.11 (Lock-free, wait-free, ABA problem)
An implementation of a shared object is lock-free if, whenever threads are running its operations, some operation completes after a finite number of steps of the system, whatever the scheduling. It is wait-free if every operation completes in a finite number of its own thread’s steps. The ABA problem arises when a thread reads a value A, then between its read and its CAS other threads change A to B and back to A: the CAS succeeds when it should not.
R. K. Treiber’s stack, in an IBM report of April 1986, is the simplest lock-free structure: a linked list whose head is changed only by CAS. A push links its node to the head it read and swings the head to the node if the head has not changed; a pop swings the head to the successor of the node it read. A failed CAS means another operation succeeded, which is why the structure is lock-free. Listing 13.7 keeps its nodes in an array and names them by index, so that a node is never freed while another thread may read it, a separate problem; the head packs the index of the top node with a tag.
static _Atomic uint32_t next[NODES]; /* node i's successor on the stack */
static _Atomic uint64_t head; /* tag << 32 | index of the top node */
static uint64_t pack(uint32_t tag, uint32_t index) { return (uint64_t)tag << 32 | index; }
void push(uint32_t n) {
uint64_t old = atomic_load(&head), new;
do {
atomic_store_explicit(&next[n], (uint32_t)old, memory_order_relaxed);
new = pack((uint32_t)(old >> 32) + TAG_STEP, n);
} while (!atomic_compare_exchange_weak(&head, &old, new)); /* failed: old is reloaded */
}
uint32_t pop(void) {
uint64_t old = atomic_load(&head), new;
do {
if ((uint32_t)old == NIL) return NIL; /* empty */
uint32_t second = atomic_load_explicit(&next[(uint32_t)old], memory_order_relaxed);
new = pack((uint32_t)(old >> 32) + TAG_STEP, second);
} while (!atomic_compare_exchange_weak(&head, &old, new));
return (uint32_t)old;
}
atomic_compare_exchange_weak writes the current head into old, and the loop retries with it. code/bachelor-3/13-concurrency/listings/treiber.c$ gcc -std=c17 -O2 -Wall -Wextra -o treiber treiber.c -lm && ./treiber
4 threads, 200000 rounds each, pops that found a node: 800000
nodes reachable from the head: 64 of 64, then the end of the list
What is the tag for? Listing 13.8 replays the bad interleaving by hand on a simulated stack, and the figure after its output draws it.
if __name__ == "__main__":
for tagged in (False, True):
s = Stack(["A", "B", "C"], tagged)
print("tagged head" if tagged else "bare head", "| start:", s.contents())
seen = s.read() # thread 1 begins a pop: it reads the head A ...
second = s.next[seen[0]] # ... and A's successor B; then it is preempted
a, b = s.pop(), s.pop() # thread 2 pops A and B ...
s.push(a) # ... and pushes A back
print(f" thread 2 popped {a}, {b}, pushed {a} back:", s.contents())
ok = s.cas(seen, second) # thread 1 resumes: is the head still what it read?
verdict = "succeeds" if ok else "fails"
print(f" thread 1's compare-and-swap {verdict}:", s.contents())
if ok:
print(f" thread 1 returns {seen[0]}, and {second} is on the stack"
" while thread 2 still holds it")
else:
print(f" thread 1 retries and pops {s.pop()}:", s.contents())
Stack, in the same file, has read, cas, pop and push as in Listing 13.7; a tagged head is compared with its tag. code/bachelor-3/13-concurrency/listings/aba_replay.py$ python aba_replay.py
bare head | start: A -> B -> C
thread 2 popped A, B, pushed A back: A -> C
thread 1's compare-and-swap succeeds: B -> C
thread 1 returns A, and B is on the stack while thread 2 still holds it
tagged head | start: A -> B -> C
thread 2 popped A, B, pushed A back: A -> C
thread 1's compare-and-swap fails: A -> C
thread 1 retries and pops A: C
The tag counts the changes of the head, so a head that went from A to something else and back is no longer equal to what thread 1 read. Maged Michael and Michael Scott describe the same modification counter, and note that it makes the ABA problem extremely unlikely, not impossible: a 32-bit tag can wrap round. Without the tag, the real stack breaks too (Listing 13.9).
/* treiber_notag.c -- the same stack, with a tag that never changes. */
#define TAG_STEP 0
#include "treiber.c"
$ gcc -std=c17 -O2 -Wall -Wextra -o treiber_notag treiber_notag.c -lm && ./treiber_notag
4 threads, 200000 rounds each, pops that found a node: 800000
nodes reachable from the head: 1 of 64, then node 61 again: a cycle
It failed the same way in every run on the laptop. A lock-free FIFO queue is harder, since it has two ends. Michael and Scott’s queue of 1996 is a linked list whose head always points to a dummy node, with a tail pointer to the last or the second-to-last node, both changed by CAS with modification counters. An enqueuer that finds the tail lagging behind first tries to move it on, then retries: a thread helps the operation it is blocked by instead of waiting for it.
Definition 13.12 (Linearisability, linearisation point)
A history of a concurrent object records, for each operation, its thread, its argument, its result and the interval between its call and its return. The history is linearisable if there is an order of all its operations that is a correct sequential history of the object and keeps every operation that returned before another one was called before that one. An implementation is linearisable if all its histories are; it is usually proved so by choosing for each operation a linearisation point, one step between its call and its return at which it appears to take effect at once.
Maurice Herlihy and Jeannette Wing defined linearisability in 1990. For Treiber’s stack the linearisation point of a push or pop is its successful CAS, and of a pop on an empty stack the load that read the empty head (exercise 13.11). A history can also be checked by brute force, by trying every order allowed (Listing 13.10).
def linearise(history):
"""history: (thread, op, arg, result, start, end) tuples. An order, or None."""
def search(left, queue, order):
if not left:
return order
first_end = min(h[5] for h in left)
for h in left:
if h[4] > first_end: # h began after another op ended: that one comes first
continue
_, op, arg, result, _, _ = h
q = deque(queue)
if op == "enq":
q.append(arg)
elif (q.popleft() if q else None) != result:
continue # the sequential queue would not return this result here
found = search([g for g in left if g is not h], q, order + [h])
if found:
return found
return None
return search(list(history), deque(), [])
$ python linearizable.py
overlapping enqueues B.enq(2), A.enq(1), A.deq()->2, B.deq()->1
dequeue during enqueue A.enq(1), B.deq()->1, B.deq()->empty
order reversed none exists
The search may try every order of the operations, a number exponential in the history’s length; on the short histories of a test, it finds bugs that a sequential test cannot see.
History — Concurrency
Dijkstra’s Eindhoven notes Cooperating sequential processes treat “the problem of the deadly embrace” and give the banker’s algorithm, and his Hierarchical ordering of sequential processes, published in Acta Informatica in 1971, seats the five philosophers at their table. Coffman, Elphick and Shoshani’s survey System deadlocks appeared in June 1971, Hoare’s monitors in 1974 and Lampson and Redell’s Mesa experience in 1980; Lamport’s definition of sequential consistency was published in the IEEE Transactions on Computers in September 1979, Herlihy and Wing’s linearisability in July 1990, and the x86-TSO model in the Communications of the ACM in July 2010.
13.6 Exercises
Exercise 13.1 ★
A system has 12 units of one resource and three threads with maximum claims 10, 4 and 9, holding 5, 2 and 2. Is the state safe? If the second thread asks for one more unit, should the banker grant it? And if the third one does?
Solution
Solution of Exercise 13.1.
9 units are held, so 3 are available; the needs are , and . The second thread can finish (2 of 3), leaving 5; then the first (5 of 5), leaving 10; then the third (7 of 10): the state is safe. One more unit to the second thread leaves 2 available and needs 5, 1, 7: the order second, first, third still works, so the banker grants it. One more unit to the third leaves 2 available and needs 5, 2, 6: the second finishes, leaving 4, and then neither 5 nor 6 fits. The state would be unsafe, so the third thread waits, although nothing is deadlocked yet (test_banker_example_and_exercise_1).
Exercise 13.2 ★
P1 waits for R1, held by P2; P2 waits for R2, held by P3; P3 waits for R3, held by P1; P4 waits for R1. Draw the resource-allocation graph and find the deadlocked threads. What changes if R3 is released?
Solution
Solution of Exercise 13.2.
Edges P1 R1 P2 R2 P3 R3 P1, and P4 R1. The cycle makes P1, P2 and P3 deadlocked; P4 is not in the cycle but waits behind it for ever. If P1 releases R3, the cycle is broken: P3 takes R3, finishes and releases R2, then P2 finishes and releases R1, which P1 or P4 obtains, and the other one after it (test_rag_cycle_and_exercise_2).
Exercise 13.3 ★
In the store-buffering test, give for each of the three outcomes that sequential consistency allows an interleaving that produces it.
Solution
Solution of Exercise 13.3.
: thread 1 runs entirely first (, ), then thread 2 (, ). : thread 2 first. : , , then both reads, in either order.
Exercise 13.4 ★
Without running it, predict what explore(3) of Listing 13.1 returns: how many states, and which deadlocked state. Check against Output 13.1.
Solution
Solution of Exercise 13.4.
14 states, and one deadlocked, ((1, 1, 1), (0, 1, 2)): everyone holds the left fork. By hand, a state is a tuple of positions in which no eater’s right neighbour holds a fork (weekend problem, question 8): with no eater, tuples of T and H; with one eater, 3 places for it, its right neighbour thinking and the third guest T or H, 6 tuples; two eaters at a table of three are neighbours, which is impossible. .
Exercise 13.5 ★★
Run the script ["C1", "~C1", "C1"] through monitor_sim.run with Hoare semantics and an if: what does C1 do? Explain why Hoare’s guarantee does not help, and fix the consumer. (test_concurrency.py checks both semantics.)
Solution
Solution of Exercise 13.5.
C1 waits on the empty buffer; the spurious wake-up takes it off the waiting list with no signal; C1 resumes after its wait, does not test again, and takes from an empty buffer. Hoare’s guarantee is about signals: a thread woken by a signal finds the condition true. A spurious wake-up is no signal, so it guarantees nothing. With while, C1 tests again, finds the buffer empty and waits again, under both semantics (test_monitor_semantics_and_exercise_5).
Exercise 13.6 ★★
Write deadlocked(available, alloc, request), which returns the threads that can never finish when each resource has several instances: thread holds and waits for . Give an example in which the resource-allocation graph has a cycle but no thread is deadlocked.
Solution
Solution of Exercise 13.6.
exercises/ex6_detect.py simulates the most favourable future: any thread whose request fits in may receive it, finish and return what it holds, so only grows, and the order in which they are tried does not matter (the argument of theorem 13.7). The threads never marked finished cannot finish in any future: they are deadlocked. Example: resource A has two instances and B one. P1 holds one A and waits for B; P2 holds B and waits for an A; P3 holds the other A and waits for nothing. P1 B P2 A P1 is a cycle, but P3 finishes and frees its A, P2 takes it and finishes, and then P1 (test_exercise_6_detection).
Exercise 13.7 ★★
Philosophers try another protocol: take the left fork; if the right one is taken, put the left one down and start again. Show that it cannot deadlock, and find a schedule for two philosophers in which neither ever eats. Which kind of failure is it?
Solution
Solution of Exercise 13.7.
A philosopher never waits while holding a fork: when the right fork is taken, it puts the left one down instead of waiting. So no thread is ever blocked holding a resource, hold and wait fails, and there is no deadlock. With two philosophers, run them in lockstep: both take their left fork, both find their right fork taken, both put their left fork down, and again for ever. Steps are taken but nobody eats: a livelock. A random wait before trying again makes the lockstep unlikely to last.
Exercise 13.8 ★★
With the waiter of the weekend problem, a philosopher thinks, is hungry, or eats, and two neighbours never eat together. Count by hand the states of three philosophers, and check the 20 printed by waiter.py.
Solution
Solution of Exercise 13.8.
At a table of three every two guests are neighbours, so at most one eats. With nobody eating, tuples of T and H; with one eater, 3 choices for it and for the others, 12. In all 20, and every one is reachable: the eater, if any, eats first, then the hungry ones become hungry.
Exercise 13.9 ★★
Linearise each history of a FIFO queue, or show that no linearisation exists. (a) A enqueues 1 during ; B dequeues 1 during and then 2 during ; C enqueues 2 during . (b) A enqueues 1 during , B enqueues 2 during , C dequeues 2 during , D dequeues 1 during .
Solution
Solution of Exercise 13.9.
(a) A.enq(1), B.deq() 1, C.enq(2), B.deq() 2. The only constraint of real time is B’s first dequeue (ending at 3) before its second (starting at 4); A’s enqueue overlaps B’s first dequeue and can take effect before it, and C’s enqueue overlaps both. (b) All four intervals are disjoint, so the order is forced: 1 and then 2 are enqueued, and a FIFO queue must return 1 first; C’s dequeue returned 2. No linearisation exists (test_linearizable_histories_and_exercise_9).
Exercise 13.10 ★★★
Each thread declares its maximum claim, never exceeds it, and returns everything when it finishes, which it does once it has received its claim. Prove that if the initial state is safe and the banker grants only requests that leave a safe state, every thread eventually finishes.
Solution
Solution of Exercise 13.10.
Facts used: a granted request leaves a safe state (the banker’s rule); a finishing thread returns everything; the scheduler keeps running every thread that is not waiting.
Releases keep a state safe: the same order still works, with at least as much available at each step. So every state is safe. Take a state with unfinished threads and a safe order . Every request of is granted: , so after the grant , and can still finish first, after which is the same as before; the rest of the order is unchanged and still works. So never waits, receives its whole claim after finitely many of its own steps, and finishes. The number of unfinished threads drops by one, the state is still safe, and by induction on that number every thread finishes.
Exercise 13.11 ★★★
Prove that Treiber’s stack (Listing 13.7), with tags that never wrap round, is linearisable, with the linearisation points of the text.
Solution
Solution of Exercise 13.11.
Facts used: CAS is atomic and every successful CAS increments the tag, which never wraps round; a node’s next is written only by a push of that node, by the thread that holds it, before the push’s CAS.
Linearisation points: the successful CAS of a push or of a pop that returns a node, and, for a pop that returns empty, its last load of the head, which saw NIL. Each lies within its operation.
Invariant: at every moment the list from the head, following next, is the stack obtained by applying, in the order of their points, the operations whose points have passed. Only successful CASes change the head. A push of read the head old, then set next[n] to its index; its CAS succeeds only if the head, tag included, still equals old, so no CAS succeeded in between and the list below old is as it was. After the CAS the list is followed by the old list: a push. A pop read top , then next[t]; its CAS succeeds only if no CAS succeeded since the read, so stayed on top, nobody held it, and next[t] was not written: it read the true successor, and after the CAS the list is the old one without , returned: a pop. A pop that saw NIL saw an empty list, so the empty stack at its point. Points inside the intervals respect real time, so the history is linearisable.
Exercise 13.12 ★★★
exercises/ex12_counter.c increments a counter by CAS in a loop. Prove it lock-free; is it wait-free? Compare with atomic_fetch_add.
Solution
Solution of Exercise 13.12.
A CAS fails only if the counter changed between the thread’s load and its CAS, that is, only if another thread’s CAS succeeded in between: every failure is someone else’s completed increment, so the system as a whole progresses, and the counter is lock-free. It is not wait-free: a scheduler can let another thread increment between each load and CAS of one thread, which then retries for ever while the others progress. atomic_fetch_add is a single atomic operation: each increment takes one step of its own thread, whatever the others do, so a counter built on it is wait-free as far as the program can see. Both lose no update (counter_test.c).
13.7 Weekend problem
Problem 13.1
Weekend problem — Dinner at the Brenmoor inn
The Brenmoor inn has a round table for guests and one fork between each pair of plates. This problem explains the numbers of Output 13.1, proves that the naive protocol has exactly one deadlocked state, compares two fixes, and finds a guest who starves although nothing is deadlocked.
def can_eat(pcs, i, n): # both neighbours are not eating: both forks are free
return pcs[(i - 1) % n] != EAT and pcs[(i + 1) % n] != EAT
def moves(pcs, n):
for i, pc in enumerate(pcs):
if pc == THINK:
yield i, pcs[:i] + (HUNGRY,) + pcs[i + 1:]
elif pc == HUNGRY and can_eat(pcs, i, n):
yield i, pcs[:i] + (EAT,) + pcs[i + 1:]
elif pc == EAT:
yield i, pcs[:i] + (THINK,) + pcs[i + 1:]
starving_cycle in the same file searches the reachable states for a closed walk in which guest 0 stays hungry while every other guest moves. code/bachelor-3/13-concurrency/listings/waiter.py$ python waiter.py
n = 3: 20 states, 0 deadlocked
n = 4: 56 states, 0 deadlocked
n = 5: 152 states, 0 deadlocked
n = 6: 416 states, 0 deadlocked
n = 7: 1136 states, 0 deadlocked
a schedule that starves philosopher 0 (T thinks, H hungry, E eats):
from H T T T E
philosopher 1 moves: H H T T E
philosopher 1 moves: H E T T E
philosopher 1 moves: H T T T E
philosopher 2 moves: H T H T E
philosopher 2 moves: H T E T E
philosopher 2 moves: H T T T E
philosopher 3 moves: H T T H E
philosopher 1 moves: H H T H E
philosopher 1 moves: H E T H E
philosopher 4 moves: H E T H T
philosopher 3 moves: H E T E T
philosopher 3 moves: H E T T T
philosopher 4 moves: H E T T H
philosopher 4 moves: H E T T E
philosopher 1 moves: H T T T E
Part I — The naive protocol’s deadlock. Each guest takes the left fork, then the right one (fork is guest ’s left, fork the right).
- For , give a schedule that reaches deadlock in five steps.
- Show that a state with no move has nobody eating, and then that every guest holds a fork: it is the state of Output 13.1.
- Which Coffman conditions hold in that state? Draw its resource-allocation graph.
- Show that the deadlocked state can be reached from every reachable state.
- Under a scheduler that picks a guest who can move at random, does the system deadlock with probability 1? Use question 4.
- Why does testing a philosopher program a few hundred times often miss this deadlock, when it is always a few steps away?
Part II — Counting the states. Position T thinks, H holds the left fork, E eats.
- Show that a state is determined by the guests’ positions alone: the owner of every fork follows.
- Show that a tuple of positions is possible if and only if no guest in E has a right neighbour in H or E.
- Count such cyclic tuples as the trace of for a matrix indexed by T, H, E. Give .
- Find the eigenvalues of , and deduce . Check it against the output for to .
- Show that every possible tuple is reachable from the start, where everyone thinks.
- Conclude: exactly one deadlocked state among reachable states. Show that .
Part III — Two fixes.
- With ordered acquisition, which guest’s order changes? Why does theorem 13.5 apply?
- The ordered counts are 5, 12, 29, 70, 169 and 408. How many states does ordering remove for each ? Do these numbers satisfy the recurrence of question 12?
- In the waiter’s protocol, which tuples of T, H, E are possible? Count them as in question 9 and check 20, 56, 152, 416 and 1,136.
- Prove that the waiter’s protocol never deadlocks.
- Write the waiter as a monitor in C: one mutex, and one condition variable per guest. What does a hungry guest wait for, whom does a guest who stops eating signal, and where must the
whilebe? - Which of the two fixes lets more guests eat at once?
Part IV — Starvation under the waiter.
- Check three steps of the schedule in Output 13.11: each is a legal move, and guest 0 stays hungry with a neighbour eating.
- The schedule is a closed walk in which every other guest moves. Why is this starvation, and neither deadlock nor livelock?
- Can the ordered protocol starve a guest? Find a schedule for .
- Propose a rule for the waiter that bounds every guest’s wait, and say what it costs.
- A real scheduler is not an adversary. Why does the starving schedule still matter?
- Sum up: the deadlocked states, the state counts and their formulas, and what each fix guarantees and does not.
Solution
Solution of Problem 13.1.
1. Guests 0, 1, 2, 3, 4 each take their left fork, in turn: every fork is held and everyone waits for the right one.
2. An eater can always put its forks down, so in a state with no move nobody eats. A thinking guest cannot move only if fork is held, by guest itself (impossible, it thinks) or by guest as a right fork (impossible, nobody eats). So nobody thinks: everyone holds its left fork, the state of the output.
3. All four: a fork has one holder; each guest holds one fork and waits for another; nobody takes a fork back; guest waits for fork , held by guest , round the table. The graph is the cycle G0 F1 G1 F2 G4 F0 G0.
4. From any reachable state, let every eater put its forks down; then nobody eats, so fork is free unless guest holds it. Let every thinking guest take its left fork: all hold their left fork, the deadlock.
5. Yes. From any state, the schedule of question 4 has at most steps, and the random scheduler follows it with probability at least . The probability of avoiding deadlock over such stretches is at most , which tends to 0.
6. is tiny: the deadlock needs every guest to take its left fork before any of them takes a right one, and a real thread usually takes its two forks within a few instructions. A few hundred runs explore a few hundred interleavings among an astronomical number.
7. Fork is held by guest if guest is in H or E (its left fork), by guest if that guest is in E (its right fork), and is free otherwise.
8. By question 7, a fork can be claimed twice only as fork by an eating guest and by guest in H or E. If no eater has such a right neighbour, every fork has at most one holder, and the tuple is a state.
9. With rows the guest’s position and columns its right neighbour’s, in the order T, H, E: . A cyclic tuple is a closed walk of length in the graph of , and their number is .
10. , so the eigenvalues are 0 and , and is the sum of their -th powers: . It gives 6, 14, 34, 82, 198, 478, as printed.
11. From everyone thinking, let the future eaters take their two forks, one eater after another. When eater does, fork is free, since its other user, guest , thinks (question 8); and fork is free, since its other user, guest , could hold it only by eating, and an eater is never followed by an eater. Then the guests in H take their left fork, which no eater holds, since an eater is never followed by H.
12. Every state is reachable and exactly one has no move, so there is one deadlocked state among . Both are roots of , so : .
13. Only guest , whose forks are and : it takes fork 0 first. Every guest now takes its lower-numbered fork first, so the locks are acquired in increasing order and the theorem applies.
14. , , then 5, 12, 29 and 70: they satisfy the recurrence (), and so do the ordered counts ().
15. Any tuple in which no two neighbours eat. has eigenvalues 0 and , so the count is : 20, 56, 152, 416, 1,136. Each tuple is reachable: its eaters eat first, then its hungry guests get hungry.
16. In any state, an eater can stop; if nobody eats, a thinking guest can get hungry; if everybody is hungry, nobody eats, and any of them can eat.
17. Under the mutex, a hungry guest marks itself hungry, and while a neighbour is eating, waits on its own condition; then it marks itself eating. A guest who stops eating marks itself thinking and signals both neighbours, who test again: under Mesa semantics a neighbour’s other neighbour may have started eating in the meantime, hence the while.
18. The waiter. With ordered acquisition a guest holding one fork while it waits blocks a neighbour who could eat; the waiter never lets a fork be held by someone not eating.
19. From H T T T E: guest 1 gets hungry (H H T T E), and can eat since guests 0 and 2 do not eat (H E T T E); guest 1 stops (H T T T E). Guest 0 is hungry throughout, and guest 4 eats throughout.
20. Every other guest eats in each round of the walk, so the system makes progress: no deadlock, and no livelock either. Guest 0 alone never eats, and it is never even able to: a neighbour is eating at every moment. Repeating the walk for ever starves it.
21. Yes. With , guests 0 and 2 both take fork 0 first. Let guest 2 take fork 0, then fork 2, eat and put both down, again and again, and let the scheduler run guest 0 only while fork 0 is held. Here guest 0 is able to move between guest 2’s meals, so a scheduler that runs every guest able to move infinitely often would save it; under the waiter’s walk, no scheduler can.
22. For instance, let a hungry guest whose neighbour has been hungry longer not start eating. Every guest then waits for at most a bounded number of meals of its neighbours; the cost is that forks may lie unused while a guest waits for its turn, so fewer guests eat at once.
23. A guarantee must hold for every schedule. Timings that repeat, two neighbours with the same rhythm, can reproduce the walk for a long time, and a waiting time that no rule bounds cannot be promised to anyone.
24. The naive protocol has exactly one deadlocked state, everyone holding its left fork, among reachable states, and can reach it from every state. Ordered acquisition removes it, as lock ordering always does. The waiter, a monitor, also never deadlocks and lets more guests eat at once, among states; but neither fix rules out starvation, which needs a rule about whose turn it is.
本章定义的术语
- Deadlock, livelock, Coffman conditions
- Linearisability, linearisation point
- Lock-free, wait-free, ABA problem
- Memory model, sequential consistency
- Monitor, Hoare semantics, Mesa semantics
- Read-modify-write operation, compare-and-swap, acquire and release ordering
- Resource-allocation graph, lock ordering
- Safe state, banker’s algorithm, deadlock detection
- Safety property, liveness property