计算机科学 · 第 5 册 · 本科三年级

University Computer Science — Year 3

本书暂未推出简体中文版。现有版本: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 P→RP \to R when thread PP waits for resource RR, and an edge R→PR \to P when RR is held by PP. Lock ordering fixes a total order on the locks and requires every thread to acquire the locks it holds together in increasing order.

A resource-allocation graph with one instance of each resource. The cycle P1, R2, P2, R3, P3, R1 is a deadlock; P4 is not in it, but waits behind it for ever. The chapter’s rag_cycle.py finds the cycle by depth-first search; with P3’s request withdrawn, it finds none.
A resource-allocation graph with one instance of each resource. The cycle P1, R2, P2, R3, P3, R1 is a deadlock; P4 is not in it, but waits behind it for ever. The chapter’s 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: P1→R1→P2→⋯→Pk→Rk→P1P_1 \to R_1 \to P_2 \to \dots \to P_k \to R_k \to P_1. P1P_1 waits for R1R_1, held by P2P_2, which releases it only after it moves, and P2P_2 waits for R2R_2, and so on round the cycle: no thread of the cycle can be the first to move, so none ever moves.

Conversely, let DD be a set of deadlocked threads. Start at any P∈DP \in D: it waits for a resource, whose holder is in DD (only a thread of DD can provide it), and that thread waits in turn. Following these edges from PP 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 LL holds only locks smaller than LL, since it acquires in increasing order.

Suppose a deadlock. By theorem 13.4 there is a cycle P1→L1→P2→L2→⋯→Pk→Lk→P1P_1 \to L_1 \to P_2 \to L_2 \to \dots \to P_k \to L_k \to P_1. P2P_2 holds L1L_1 and waits for L2L_2, so L1<L2L_1 < L_2; likewise L2<L3L_2 < L_3, …, Lk<L1L_k < L_1, since P1P_1 holds LkL_k and waits for L1L_1. Then L1<L1L_1 < L_1, 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
Listing 13.1. The philosophers as a state machine. A state is each philosopher’s position in its loop and each fork’s owner; a breadth-first search visits every state that some interleaving reaches. With 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))
Output 13.1. Every reachable state of nn philosophers, and the states with no move. Position 1 means “holds the first fork”; the deadlocked state for n=5n = 5 has everyone holding a fork, philosopher ii holding fork ii.
The whole state graph for two philosophers, the 6 states of . T thinks, H holds the left fork, E eats; an edge is labelled with the philosopher who moves. Every state can reach the deadlock.
The whole state graph for two philosophers, the 6 states of Output 13.1. T thinks, H holds the left fork, E eats; an edge is labelled with the philosopher who moves. Every state can reach the deadlock.

There is exactly one deadlocked state for every nn, and ordered acquisition removes it, as theorem 13.5 promised: only the last philosopher’s order changes, since its forks are n−1n - 1 and 00. 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 ii declares a maximum claim; it holds alloci\mathit{alloc}_i and may still ask for needi\mathit{need}_i, the claim minus what it holds; available\mathit{available} 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 need\mathit{need} 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
Listing 13.2. The safety test, greedily, and a request. code/bachelor-3/13-concurrency/listings/banker.py
$ 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]
Output 13.2. Five threads, three kinds of resource. P1’s small request is refused: it would leave no safe order. P4’s is granted.

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 work\mathit{work} never decreases; a thread that can finish with some work\mathit{work} can finish with any larger one.

If it returns an order, each thread in it had its need\mathit{need} covered by work\mathit{work} when chosen, which is the definition of a safe order. Conversely, suppose the state has a safe order QQ, and suppose the greedy loop stops early with a set UU of threads left over. Let uu be the first thread of QQ in UU. The threads before uu in QQ are all finished by the greedy loop, so the greedy work\mathit{work} is at least what QQ offers uu, which covers needu\mathit{need}_u: the loop could still choose uu, 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;
}
Listing 13.3. A bounded buffer as a monitor: one mutex, two conditions. code/bachelor-3/13-concurrency/listings/monitor_buffer.c
$ 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
Output 13.3. Two producers and two consumer threads through a buffer of 8 slots. The output prints only what the program guarantees: the totals after every thread has joined.

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
    }
}
Listing 13.4. The same monitor in Rust. A guard is the lock: forgetting to unlock is impossible, and so is forgetting to lock. code/bachelor-3/13-concurrency/listings/monitor_rust.rs
$ 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
Output 13.4. The Rust buffer, with the same totals.

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"
Listing 13.5. The consumer and the producer. 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
Output 13.5. The script: C1 waits on an empty buffer; P puts an item and signals; then C2 runs, and then C1. Under Mesa semantics C2 enters before C1 and takes the item, and an 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 x=1x = 1 and then reads y into r1r_1; thread 2 writes y=1y = 1 and then reads x into r2r_2. Under sequential consistency r1=r2=0r_1 = r_2 = 0 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)
Listing 13.6. The store-buffering test. A fresh pair of variables per trial; the threads meet before each one, then wait a few random steps so that their operations overlap. code/bachelor-3/13-concurrency/listings/sb_litmus.c
$ 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
Output 13.6. One run on the author’s laptop (the counts change from run to run). With relaxed atomics, thousands of trials give r1=r2=0r_1 = r_2 = 0, the outcome that no interleaving produces; with sequentially consistent ones, none does.

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 x=1x = 1 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.

Store buffering. Each write waits in its core’s buffer while the read that follows it goes to memory, where the other write has not arrived: both reads return 0.
Store buffering. Each write waits in its core’s buffer while the read that follows it goes to memory, where the other write has not arrived: both reads return 0.

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 r1=r2=0r_1 = r_2 = 0, 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;
}
Listing 13.7. Treiber’s stack. On failure, 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
Output 13.7. Four threads each pop a node and push it back, 200,000 times, on a stack of 64 nodes. At the end, the stack is a list of all 64.

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())
Listing 13.8. The interleaving, scripted. 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
Output 13.8. With a bare head, thread 1’s CAS sees A again and succeeds: the head becomes B, a node that thread 2 holds, and C is the only other node left. With a tag, the CAS sees that the head has changed twice, fails, and retries correctly.
The ABA problem in three snapshots. Thread 1’s CAS compares only the head, A, and swings it to the successor it read in snapshot 1. B is now on the stack and in thread 2’s hands at once.
The ABA problem in three snapshots. Thread 1’s CAS compares only the head, A, and swings it to the successor it read in snapshot 1. B is now on the stack and in thread 2’s hands at once.

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"
Listing 13.9. The same stack, with a tag that never changes. code/bachelor-3/13-concurrency/listings/treiber_notag.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
Output 13.9. One run on the author’s laptop. Every pop found a node, yet at the end the head leads to one node whose successor is itself: 63 nodes are lost.

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(), [])
Listing 13.10. A linearisability checker for a FIFO queue: at each step, try every operation that no remaining operation finished before, if the sequential queue gives the recorded result. code/bachelor-3/13-concurrency/listings/linearizable.py
$ 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
Output 13.10. Three histories. Overlapping operations can take effect in either order; in the third, 1 was enqueued and returned before 2 was enqueued, and a dequeue returning 2 matches no order.

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 10−5=510 - 5 = 5, 4−2=24 - 2 = 2 and 9−2=79 - 2 = 7. 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 →\to R1 →\to P2 →\to R2 →\to P3 →\to R3 →\to P1, and P4 →\to 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.

r1=0,r2=1r_1 = 0, r_2 = 1: thread 1 runs entirely first (x=1x = 1, r1=y=0r_1 = y = 0), then thread 2 (y=1y = 1, r2=x=1r_2 = x = 1). r1=1,r2=0r_1 = 1, r_2 = 0: thread 2 first. r1=r2=1r_1 = r_2 = 1: x=1x = 1, y=1y = 1, 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, 23=82^3 = 8 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. 8+6=148 + 6 = 14.

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 ii holds alloci\mathit{alloc}_i and waits for requesti\mathit{request}_i. 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 work\mathit{work} may receive it, finish and return what it holds, so work\mathit{work} 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 →\to B →\to P2 →\to A →\to 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, 23=82^3 = 8 tuples of T and H; with one eater, 3 choices for it and 222^2 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 [0,10][0, 10]; B dequeues 1 during [1,3][1, 3] and then 2 during [4,6][4, 6]; C enqueues 2 during [2,5][2, 5]. (b) A enqueues 1 during [0,1][0, 1], B enqueues 2 during [2,3][2, 3], C dequeues 2 during [4,5][4, 5], D dequeues 1 during [6,7][6, 7].

Solution

Solution of Exercise 13.9.

(a) A.enq(1), B.deq() →\to 1, C.enq(2), B.deq() →\to 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 q1,…,qkq_1, \dots, q_k. Every request rr of q1q_1 is granted: needq1≤available\mathit{need}_{q_1} \le \mathit{available}, so after the grant needq1−r≤available−r\mathit{need}_{q_1} - r \le \mathit{available} - r, and q1q_1 can still finish first, after which work\mathit{work} is the same as before; the rest of the order is unchanged and still works. So q1q_1 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 nn 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 nn followed by the old list: a push. A pop read top tt, then next[t]; its CAS succeeds only if no CAS succeeded since the read, so tt 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 tt, 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 nn 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:]
Listing 13.11. The waiter’s protocol: a hungry guest is given both forks at once, when neither neighbour is eating. The function 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
Output 13.11. The waiter’s states, and a schedule, repeatable for ever, that starves guest 0.

Part I — The naive protocol’s deadlock. Each guest takes the left fork, then the right one (fork ii is guest ii’s left, fork i+1 mod ni + 1 \bmod n the right).

  1. For n=5n = 5, give a schedule that reaches deadlock in five steps.
  2. 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.
  3. Which Coffman conditions hold in that state? Draw its resource-allocation graph.
  4. Show that the deadlocked state can be reached from every reachable state.
  5. Under a scheduler that picks a guest who can move at random, does the system deadlock with probability 1? Use question 4.
  6. 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.

  1. Show that a state is determined by the guests’ positions alone: the owner of every fork follows.
  2. Show that a tuple of positions is possible if and only if no guest in E has a right neighbour in H or E.
  3. Count such cyclic tuples as the trace of MnM^n for a 3×33 \times 3 matrix MM indexed by T, H, E. Give MM.
  4. Find the eigenvalues of MM, and deduce S(n)=(1+2)n+(1−2)nS(n) = (1 + \sqrt{2})^n + (1 - \sqrt{2})^n. Check it against the output for n=2n = 2 to 77.
  5. Show that every possible tuple is reachable from the start, where everyone thinks.
  6. Conclude: exactly one deadlocked state among S(n)S(n) reachable states. Show that S(n)=2S(n−1)+S(n−2)S(n) = 2S(n - 1) + S(n - 2).

Part III — Two fixes.

  1. With ordered acquisition, which guest’s order changes? Why does theorem 13.5 apply?
  2. The ordered counts are 5, 12, 29, 70, 169 and 408. How many states does ordering remove for each nn? Do these numbers satisfy the recurrence of question 12?
  3. 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.
  4. Prove that the waiter’s protocol never deadlocks.
  5. 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 while be?
  6. Which of the two fixes lets more guests eat at once?

Part IV — Starvation under the waiter.

  1. Check three steps of the schedule in Output 13.11: each is a legal move, and guest 0 stays hungry with a neighbour eating.
  2. The schedule is a closed walk in which every other guest moves. Why is this starvation, and neither deadlock nor livelock?
  3. Can the ordered protocol starve a guest? Find a schedule for n=3n = 3.
  4. Propose a rule for the waiter that bounds every guest’s wait, and say what it costs.
  5. A real scheduler is not an adversary. Why does the starving schedule still matter?
  6. 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 ii cannot move only if fork ii is held, by guest ii itself (impossible, it thinks) or by guest i−1i - 1 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 ii waits for fork i+1i + 1, held by guest i+1i + 1, round the table. The graph is the cycle G0 →\to F1 →\to G1 →\to F2 →⋯→\to \dots \to G4 →\to F0 →\to G0.

4. From any reachable state, let every eater put its forks down; then nobody eats, so fork ii is free unless guest ii 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 2n2n steps, and the random scheduler follows it with probability at least p=n−2n>0p = n^{-2n} > 0. The probability of avoiding deadlock over kk such stretches is at most (1−p)k(1 - p)^k, which tends to 0.

6. pp 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 ii is held by guest ii if guest ii is in H or E (its left fork), by guest i−1i - 1 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 i+1i + 1 by an eating guest ii and by guest i+1i + 1 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: M=(111111100)M = \left(\begin{smallmatrix} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 0 & 0 \end{smallmatrix}\right). A cyclic tuple is a closed walk of length nn in the graph of MM, and their number is tr⁡Mn\operatorname{tr} M^n.

10. det⁡(M−λI)=−λ(λ2−2λ−1)\det(M - \lambda I) = -\lambda(\lambda^2 - 2\lambda - 1), so the eigenvalues are 0 and 1±21 \pm \sqrt{2}, and tr⁡Mn\operatorname{tr} M^n is the sum of their nn-th powers: S(n)=(1+2)n+(1−2)nS(n) = (1 + \sqrt{2})^n + (1 - \sqrt{2})^n. 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 ii does, fork i+1i + 1 is free, since its other user, guest i+1i + 1, thinks (question 8); and fork ii is free, since its other user, guest i−1i - 1, 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 S(n)S(n). Both 1±21 \pm \sqrt{2} are roots of λ2=2λ+1\lambda^2 = 2\lambda + 1, so S(n)=2S(n−1)+S(n−2)S(n) = 2S(n - 1) + S(n - 2): 2×14+6=342 \times 14 + 6 = 34.

13. Only guest n−1n - 1, whose forks are n−1n - 1 and 00: 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. 6−5=16 - 5 = 1, 14−12=214 - 12 = 2, then 5, 12, 29 and 70: they satisfy the recurrence (2×12+5=292 \times 12 + 5 = 29), and so do the ordered counts (2×70+29=1692 \times 70 + 29 = 169).

15. Any tuple in which no two neighbours eat. M′=(111111110)M' = \left(\begin{smallmatrix} 1 & 1 & 1 \\ 1 & 1 & 1 \\ 1 & 1 & 0 \end{smallmatrix}\right) has eigenvalues 0 and 1±31 \pm \sqrt{3}, so the count is (1+3)n+(1−3)n(1 + \sqrt{3})^n + (1 - \sqrt{3})^n: 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 n=3n = 3, 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 S(n)=(1+2)n+(1−2)nS(n) = (1 + \sqrt{2})^n + (1 - \sqrt{2})^n 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 (1+3)n+(1−3)n(1 + \sqrt{3})^n + (1 - \sqrt{3})^n states; but neither fix rules out starvation, which needs a rule about whose turn it is.

本章定义的术语

在术语表中查看全部 1050 个术语