---
title: "Threads and Synchronisation"
book: "University Computer Science — Year 2"
subject: computer-science
language: en
chapter: 15
exercises: 12
source: https://one-course.com/books/computer-science/4/en/chapter/15-threads-and-synchronisation
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 15 — Threads and Synchronisation

A bus has one seat left. A customer arrives at window A, and ten milliseconds later another at window B. Both clerks run the same program:

```c
static void *sell(void *arg)
{
    struct window *w = arg;
    pause_ms(w->delay_ms);
    if (seats_left > 0) {                        /* check ... */
        int seat = seats_left;
        pause_ms(50);                            /* the clerk prints the ticket */
        seats_left = seat - 1;                   /* ... then sell */
        w->sold = seat;
    }
    return NULL;
}
```

***Listing 15.1.** One window’s sale code/bachelor-2/15-threads-and-synchronisation/listings/last_seat.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o last_seat last_seat.c -lm && ./last_seat
window A sold seat 1
window B sold seat 1
seats left: 0
```

***Output 15.1.** Two tickets for seat 1.*

Each window checked that a seat was left, and one was, at the moment it checked. Between the check and the sale the other window checked too. Neither line of the program is wrong; their [interleaving](#def-b2-threads-and-synchronisation-interleaving) is. This chapter runs several [threads](#def-b2-threads-and-synchronisation-thread) in one program, counts the ways their steps can interleave, explores all of them with a small checker, and builds the tools that rule the bad ones out: [locks](#def-b2-threads-and-synchronisation-lock), [condition variables](#def-b2-threads-and-synchronisation-condvar) and [semaphores](#def-b2-threads-and-synchronisation-semaphore), in C, C++ and Rust.

**You already know.**

Book 2: two [processes](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process) sharing a resource can produce a *[race condition](#def-b2-threads-and-synchronisation-race)*, a result that depends on the order of their steps; a *[critical section](#def-b2-threads-and-synchronisation-mutex-property)* uses the shared data, *[mutual exclusion](#def-b2-threads-and-synchronisation-mutex-property)* lets one [process](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process) at a time be in it, and a *[lock](#def-b2-threads-and-synchronisation-lock)* provides it; a *deadlock* is a set of [processes](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process) each waiting for a resource another holds, and needs four conditions ([mutual exclusion](#def-b2-threads-and-synchronisation-mutex-property), hold and wait, no preemption, circular wait). [Chapter 13](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#ch-b2-processes-and-system-calls): a [process](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process) has its own memory. [Chapter 6](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#ch-b2-rust-ownership): an exclusive [borrow](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#def-b2-rust-ownership-borrow) excludes every other [borrow](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#def-b2-rust-ownership-borrow), so two [threads](#def-b2-threads-and-synchronisation-thread) cannot both change one value.

## 15.1 Threads

**Definition 15.1 (Thread).**

A *thread* is one sequence of execution inside a [process](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process): it has its own registers, program counter and stack, and shares with the other threads of the [process](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process) everything else, its memory, its open files, its [signal handlers](https://one-course.com/books/computer-science/4/en/chapter/14-files-pipes-and-signals#def-b2-files-pipes-signals-signal). `pthread_create(&t, NULL, f, arg)` starts a thread that runs `f(arg)`; `pthread_join(t, NULL)` waits for it to end.

Two [processes](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process) made by `fork` share nothing they do not arrange to share; two [threads](#def-b2-threads-and-synchronisation-thread) share all their global variables and the heap. That is what makes [threads](#def-b2-threads-and-synchronisation-thread) fast to communicate, and what made `seats_left` a single variable seen by both windows. On a machine with several cores the [threads](#def-b2-threads-and-synchronisation-thread) run at the same time; on one core the scheduler switches between them. Either way, a [thread](#def-b2-threads-and-synchronisation-thread)’s steps follow each other in its own order, and the steps of different [threads](#def-b2-threads-and-synchronisation-thread) mix in an order that nobody chooses.

**Definition 15.2 (Interleaving).**

An *interleaving* (or *schedule*) of [threads](#def-b2-threads-and-synchronisation-thread) is one sequence of all their steps that keeps the steps of each [thread](#def-b2-threads-and-synchronisation-thread) in that [thread](#def-b2-threads-and-synchronisation-thread)’s order.

**Proposition 15.3 (Number of interleavings).**

Two [threads](#def-b2-threads-and-synchronisation-thread) of $m$ and $n$ steps that never wait have $\binom{m+n}{m}$ [interleavings](#def-b2-threads-and-synchronisation-interleaving).

**Proof.** An [interleaving](#def-b2-threads-and-synchronisation-interleaving) is a sequence of $m + n$ positions. Choosing which $m$ positions hold the first [thread](#def-b2-threads-and-synchronisation-thread)’s steps determines it entirely, since each [thread](#def-b2-threads-and-synchronisation-thread)’s steps fill their positions in their own order; every choice gives an [interleaving](#def-b2-threads-and-synchronisation-interleaving). There are $\binom{m+n}{m}$ choices. ∎

Two [threads](#def-b2-threads-and-synchronisation-thread) of 10 steps have $\binom{20}{10} = 184\,756$ [interleavings](#def-b2-threads-and-synchronisation-interleaving); of 20 steps, about $1.4 \times 10^{11}$. A program can be run thousands of times and meet only a few of them: testing cannot show that a concurrent program is correct, and the hook’s bug may appear once a year. For a small model of a program, though, all of them can be tried.

## 15.2 Data races

`counter++` is not one step. The processor loads the counter into a register, adds 1, and stores it back. `race.c` writes the three steps out explicitly (with C11 [atomic](#def-b2-threads-and-synchronisation-atomic) loads and stores, defined below, so that the compiler keeps them and the program stays defined), runs $k$ [threads](#def-b2-threads-and-synchronisation-thread) that each add 1 a million times, and compares:

```c
static void *racy(void *arg)                     /* load, add, store: three steps */
{
    (void)arg;
    for (long k = 0; k < N; k++) {
        long r = atomic_load_explicit(&counter, memory_order_relaxed);
        atomic_store_explicit(&counter, r + 1, memory_order_relaxed);
    }
    return NULL;
}
```

***Listing 15.2.** Load, add, store: an increment that can lose updates code/bachelor-2/15-threads-and-synchronisation/listings/race.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o race race.c -lm && ./race
threads   expected     racy result   lost    racy ms  mutex ms  atomic ms
      1    1000000       1000000   0.0 %       2.3      12.3       4.1
      2    2000000       1092229  45.4 %       2.0     116.1      20.6
      4    4000000       1075620  73.1 %       2.2     196.4      47.0
      8    8000000       1356989  83.0 %       4.0     446.6     118.8
```

***Output 15.2.** One run on the author’s laptop: the racy result, the share of increments lost, and the time of three versions.*

![A lost update. Both threads read the old value before either writes; the second write overwrites the first.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-threads-and-synchronisation/fig-e7ef2d4d91d2.svg)

*A lost update. Both [threads](#def-b2-threads-and-synchronisation-thread) read the old value before either writes; the second write overwrites the first.*

Alone, the [thread](#def-b2-threads-and-synchronisation-thread) loses nothing. With two [threads](#def-b2-threads-and-synchronisation-thread), nearly half the increments vanish: whenever the two [threads](#def-b2-threads-and-synchronisation-thread) overlap, each overwrites the other’s work. The precise numbers change from run to run; the losses do not go away.

![The lost increments of . The more threads overlap, the larger the share of increments that one thread overwrites.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-threads-and-synchronisation/fig-bb75b57eade4.svg)

*The lost increments of [Output 15.2](#out-b2-threads-and-synchronisation-race). The more [threads](#def-b2-threads-and-synchronisation-thread) overlap, the larger the share of increments that one [thread](#def-b2-threads-and-synchronisation-thread) overwrites.*

**Remark 15.4 (Race condition, between threads).**

Book 2’s [race condition](#def-b2-threads-and-synchronisation-race), between [processes](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process), is the same bug between [threads](#def-b2-threads-and-synchronisation-thread): the result depends on the order in which their steps interleave, and some of those orders give a wrong result. The lost increments of `race.c` are one.

**Definition 15.5 (Data race).**

Two accesses to the same memory location form a *data race* when they come from different [threads](#def-b2-threads-and-synchronisation-thread), at least one is a write, at least one is not [atomic](#def-b2-threads-and-synchronisation-atomic), and nothing orders one before the other. In C and C++ a program with a data race has undefined behaviour.

**Definition 15.6 (Atomic operation).**

An operation is *atomic* when no other [thread](#def-b2-threads-and-synchronisation-thread) can observe it half done: it takes effect as one indivisible step of every [interleaving](#def-b2-threads-and-synchronisation-interleaving). `atomic_fetch_add(&x, 1)` reads, adds and writes as one step.

Our loads and stores are [atomic](#def-b2-threads-and-synchronisation-atomic) one by one, so `race.c` has no [data race](#def-b2-threads-and-synchronisation-data-race); it still loses updates, because the three steps together are not [atomic](#def-b2-threads-and-synchronisation-atomic). The hook’s `seats_left`, a plain `int`, does have a [data race](#def-b2-threads-and-synchronisation-data-race), and a tool can see it: compiled with ThreadSanitizer, the program reports each pair of unordered accesses it witnesses. (On this machine the tool needs address randomisation turned off, which `setarch -R` does; `trim.sh` keeps the lines that name the race.)

```
$ gcc -std=c17 -O1 -g -fsanitize=thread -o last_seat last_seat.c
$ setarch -R ./last_seat 2>&1 | bash trim.sh
WARNING: ThreadSanitizer: data race
  Write of size 4 at 0x... by thread T1:
    #0 sell ~/session/last_seat.c:28
  Previous read of size 4 at 0x... by thread T2:
    #0 sell ~/session/last_seat.c:25
  Location is global 'seats_left' of size 4 at 0x...
SUMMARY: ThreadSanitizer: data race ~/session/last_seat.c:28 in sell
window A sold seat 1
window B sold seat 1
seats left: 0
```

***Output 15.3.** The race found while it happens.*

Such a tool reports only the races of the [interleaving](#def-b2-threads-and-synchronisation-interleaving) that ran. To see them all, we can explore. A *model* of a program lists each [thread](#def-b2-threads-and-synchronisation-thread)’s steps; `interleavings.py` runs every [interleaving](#def-b2-threads-and-synchronisation-interleaving) of them, recursively, and counts those that end badly. Two states that are the same (same position in every [thread](#def-b2-threads-and-synchronisation-thread), same variables) have the same future, so the count of each is computed once and remembered:

```python
    def go(pcs, sh, los):
        key = (pcs, sh, los)
        if key in memo:
            return memo[key]
        s = dict(sh)
        inside = sum(pc < len(p) and p[pc][0] == "critical section"
                     for pc, p in zip(pcs, progs))
        total, bad, stuck, example, outs = 0, 0, 0, None, Counter()
        for i, (pc, prog) in enumerate(zip(pcs, progs)):
            if pc == len(prog):
                continue
            label, guard, action = prog[pc]
            if guard and not guard(s, dict(los[i])):
                continue
            s2, l2 = dict(s), dict(los[i])
            jump = action(s2, l2) if action else None
            new_pcs = pcs[:i] + (pc + 1 if jump is None else jump,) + pcs[i + 1:]
            new_los = los[:i] + (freeze(l2),) + los[i + 1:]
            t, b, k, ex, o = go(new_pcs, freeze(s2), new_los)
            total, bad, stuck, outs = total + t, bad + b, stuck + k, outs + o
            if b and example is None:
                example = [f"{names[i]}: {label}"] + ex
        if total == 0:                               # nobody can move: an end
            done = all(pc == len(p) for pc, p in zip(pcs, progs))
            total, stuck = 1, 0 if done else 1
            bad = int(done and model.final is not None and not model.final(s))
            example = [] if bad else None
            if model.outcome:
                outs = Counter([model.outcome(s)])
        if inside > 1:                               # mutual exclusion violated here
            bad, example = total, []
        memo[key] = (total, bad, stuck, example, outs)
        return memo[key]
```

***Listing 15.3.** Exploring every schedule from one state code/bachelor-2/15-threads-and-synchronisation/listings/interleavings.py*

A step is a label, a *guard* (the step may run only when it holds, as for a wait) and an action. The counter of [Output 15.2](#out-b2-threads-and-synchronisation-race) becomes two steps per [thread](#def-b2-threads-and-synchronisation-thread):

```python
def counter_thread(increments):
    steps = []
    for _ in range(increments):
        steps.append(("r = x", None, lambda s, me: me.update(r=s["x"])))
        steps.append(("x = r + 1", None, lambda s, me: s.update(x=me["r"] + 1)))
    return steps
```

***Listing 15.4.** The counter’s model code/bachelor-2/15-threads-and-synchronisation/listings/interleavings.py*

```
$ python interleavings.py
two threads, 3 and 4 steps: 35 schedules, 0 bad
   binomial(7, 3) = 35
counter, one increment each: 6 schedules, 4 bad; outcomes 1 (4), 2 (2)
   e.g. A: r = x | B: r = x | A: x = r + 1 | B: x = r + 1
naive flag lock: 42 schedules, 24 bad
   e.g. A: wait until flag == 0 | B: wait until flag == 0 | A: flag = 1 | B: flag = 1
Peterson: 18 schedules, 0 bad
```

***Output 15.4.** Every schedule of four small models.*

Two [threads](#def-b2-threads-and-synchronisation-thread) of 3 and 4 steps give $\binom{7}{3} = 35$ schedules, as the proposition says. Of the counter’s 6 schedules, 4 lose an update, and the explorer prints one. The two other models are the subject of the next section.

## 15.3 Mutual exclusion

**Remark 15.7 (Critical section, mutual exclusion, between threads).**

Book 2 defined these words between [processes](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process); between [threads](#def-b2-threads-and-synchronisation-thread) they mean the same. A [critical section](#def-b2-threads-and-synchronisation-mutex-property) is a part of a [thread](#def-b2-threads-and-synchronisation-thread)’s code that must not run while another [thread](#def-b2-threads-and-synchronisation-thread) runs a [critical section](#def-b2-threads-and-synchronisation-mutex-property) on the same data, and [critical sections](#def-b2-threads-and-synchronisation-mutex-property) are in [mutual exclusion](#def-b2-threads-and-synchronisation-mutex-property) when at most one [thread](#def-b2-threads-and-synchronisation-thread) at a time is inside any of them.

**Remark 15.8 (Lock, between threads).**

Book 2’s [lock](#def-b2-threads-and-synchronisation-lock), which provides [mutual exclusion](#def-b2-threads-and-synchronisation-mutex-property), is for [threads](#def-b2-threads-and-synchronisation-thread) an object called a *mutex*, with two operations around [critical sections](#def-b2-threads-and-synchronisation-mutex-property), *[lock](#def-b2-threads-and-synchronisation-lock)* and *unlock*: at most one [thread](#def-b2-threads-and-synchronisation-thread) at a time is between the [lock](#def-b2-threads-and-synchronisation-lock) it called and its unlock, and a [thread](#def-b2-threads-and-synchronisation-thread) that calls [lock](#def-b2-threads-and-synchronisation-lock) while another holds it waits.

The naive [lock](#def-b2-threads-and-synchronisation-lock), a shared flag tested and then set, fails for the hook’s reason: both [threads](#def-b2-threads-and-synchronisation-thread) can test the flag before either sets it. The explorer finds 24 bad schedules among 42 ([Output 15.4](#out-b2-threads-and-synchronisation-explorer)). Testing and setting must not be separable, or something else must break the tie. Peterson’s algorithm breaks it with one more variable, `turn`, and only loads and stores:

```c
static atomic_bool flag[2];                      /* flag[i]: thread i wants to enter */
static atomic_int turn;                          /* who yields if both want to */

void peterson_lock(int i)
{
    int j = 1 - i;
    atomic_store(&flag[i], true);
    atomic_store(&turn, j);                      /* after you */
    while (atomic_load(&flag[j]) && atomic_load(&turn) == j)
        ;                                        /* wait */
}

void peterson_unlock(int i)
{
    atomic_store(&flag[i], false);
}
```

***Listing 15.5.** Peterson’s [lock](#def-b2-threads-and-synchronisation-lock) for [threads](#def-b2-threads-and-synchronisation-thread) 0 and 1 code/bachelor-2/15-threads-and-synchronisation/listings/locks.c*

A [thread](#def-b2-threads-and-synchronisation-thread) announces that it wants to enter, then gives the turn to the other, and waits while the other wants to enter and has the turn. The explorer’s model of it has no bad schedule. The proof holds for any number of passes:

**Theorem 15.9 (Peterson’s algorithm).**

Assume that every load and store of `flag` and `turn` is one step of a single [interleaving](#def-b2-threads-and-synchronisation-interleaving) of the two [threads](#def-b2-threads-and-synchronisation-thread) (sequential consistency). Then (1) the two [threads](#def-b2-threads-and-synchronisation-thread) are never both in their [critical sections](#def-b2-threads-and-synchronisation-mutex-property); (2) a [thread](#def-b2-threads-and-synchronisation-thread) that waits enters before the other [thread](#def-b2-threads-and-synchronisation-thread) has entered twice more.

**Proof.** (1) Suppose both are in their [critical sections](#def-b2-threads-and-synchronisation-mutex-property) at some moment. Each has written `turn` on its way in; say [thread](#def-b2-threads-and-synchronisation-thread) 0 wrote last, `turn = 1`, so `turn` is still 1 (a [thread](#def-b2-threads-and-synchronisation-thread) writes `turn` only on its way in). Look at [thread](#def-b2-threads-and-synchronisation-thread) 0’s last test of the wait condition, which came after its write of `turn`. [Thread](#def-b2-threads-and-synchronisation-thread) 1 had already set `flag[1]` before writing `turn`, which happened before [thread](#def-b2-threads-and-synchronisation-thread) 0’s write, and has not cleared it since, being in its [critical section](#def-b2-threads-and-synchronisation-mutex-property). So the test found `flag[1]` true and `turn == 1`, and [thread](#def-b2-threads-and-synchronisation-thread) 0 kept waiting: contradiction. The case where [thread](#def-b2-threads-and-synchronisation-thread) 1 wrote last is symmetric.

(2) Let [thread](#def-b2-threads-and-synchronisation-thread) 0 wait. If [thread](#def-b2-threads-and-synchronisation-thread) 1 is not trying to enter, `flag[1]` is false, and [thread](#def-b2-threads-and-synchronisation-thread) 0’s next test lets it in. Otherwise [thread](#def-b2-threads-and-synchronisation-thread) 1 enters at most once more, and leaves by clearing `flag[1]`; to enter again it must write `turn = 0`. From that write on, [thread](#def-b2-threads-and-synchronisation-thread) 0’s wait condition, `flag[1]` and `turn == 1`, is false, so [thread](#def-b2-threads-and-synchronisation-thread) 0 enters at its next test; and [thread](#def-b2-threads-and-synchronisation-thread) 1 waits, since `flag[0]` stays true and `turn` stays 0 until [thread](#def-b2-threads-and-synchronisation-thread) 0 has entered and left. ∎

![Peterson’s protocol. Each thread writes its own flag, reads the other’s, and both write and read the shared turn. Whoever writes turn last waits, if the other also wants to enter.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-threads-and-synchronisation/fig-6a22fe4f72d3.svg)

*Peterson’s protocol. Each [thread](#def-b2-threads-and-synchronisation-thread) writes its own flag, reads the other’s, and both write and read the shared `turn`. Whoever writes `turn` last waits, if the other also wants to enter.*

For $n$ [threads](#def-b2-threads-and-synchronisation-thread), Lamport’s bakery algorithm works like the ticket machine at a counter: each [thread](#def-b2-threads-and-synchronisation-thread) takes a number larger than every number it sees, and the smallest number is served first; ties, possible because two [threads](#def-b2-threads-and-synchronisation-thread) can read the same numbers, go to the smaller [thread](#def-b2-threads-and-synchronisation-thread) index.

```c
void bakery_lock(int i)
{
    atomic_store(&choosing[i], true);
    long max = 0;
    for (int j = 0; j < nthreads; j++) {         /* take a ticket larger than all */
        long nj = atomic_load(&number[j]);
        if (nj > max)
            max = nj;
    }
    atomic_store(&number[i], max + 1);
    atomic_store(&choosing[i], false);
    for (int j = 0; j < nthreads; j++) {
        while (atomic_load(&choosing[j]))
            ;                                    /* j is taking a ticket: wait */
        long nj;
        while ((nj = atomic_load(&number[j])) != 0
               && (nj < number[i] || (nj == number[i] && j < i)))
            ;                                    /* j is served first: wait */
    }
}
```

***Listing 15.6.** The bakery: take a ticket, then wait for every smaller one code/bachelor-2/15-threads-and-synchronisation/listings/locks.c*

**Theorem 15.10 (Bakery algorithm).**

Under sequential consistency, no two [threads](#def-b2-threads-and-synchronisation-thread) are ever in their [critical sections](#def-b2-threads-and-synchronisation-mutex-property) at once. Moreover, if [thread](#def-b2-threads-and-synchronisation-thread) $i$ finishes taking its ticket before [thread](#def-b2-threads-and-synchronisation-thread) $k$ starts taking its own, then $i$ enters its [critical section](#def-b2-threads-and-synchronisation-mutex-property) before $k$ (first come, first served).

**Proof.** Write $(a, i) < (b, k)$ for the order of pairs: $a < b$, or $a = b$ and $i < k$. We show: if $i$ is in its [critical section](#def-b2-threads-and-synchronisation-mutex-property) while $k$ holds a ticket $n_k \ne 0$, then $(n_i, i) < (n_k, k)$. Two such [threads](#def-b2-threads-and-synchronisation-thread) would then each be before the other, which is impossible.

When $i$ passed its loop for $k$, it first saw `choosing[k]` false at some moment $t$, then read `number[k]`. If it read a ticket with $(n_k, k) > (n_i, i)$, that ticket is still $k$’s unless $k$ has left and taken a new one since; a new ticket is taken after $n_i$ was written, so it is larger than $n_i$. If it read 0, $k$ had no ticket at that read; since $k$ was not choosing at $t$, its present ticket was taken by a choosing that began after $t$, after $i$ wrote $n_i$, so $k$ read $n_i$ and took a larger number. In every case $(n_i, i) < (n_k, k)$.

For the second claim: $k$ starts choosing after $n_i$ is written, so it reads $n_i$ and takes $n_k > n_i$; while $i$ waits, $k$’s loop for $i$ waits too, since `number[i]` is nonzero and smaller. ∎

```
$ gcc -std=c17 -O2 -Wall -Wextra -o locks_demo locks_demo.c locks.c -lm && ./locks_demo
Peterson, 2 threads: 400000 (expected 400000)
bakery, 4 threads:   800000 (expected 800000)
```

***Output 15.5.** A plain `counter++` under each [lock](#def-b2-threads-and-synchronisation-lock): nothing is lost.*

`choosing` looks unnecessary, and is not: without it, a [thread](#def-b2-threads-and-synchronisation-thread) could read `number[k]` as 0 while $k$ is still computing its ticket, enter, and then be overtaken by $k$’s small ticket ([Exercise 15.11](#exo-b2-threads-and-synchronisation-11)). Both algorithms spin, testing in a loop, and both rely on sequential consistency, which real processors give only to [atomic operations](#def-b2-threads-and-synchronisation-atomic) of the strongest ordering; the Year 3 volume explains the weaker orders. In practice one uses the system’s [lock](#def-b2-threads-and-synchronisation-lock), `pthread_mutex_t`, or a single [atomic](#def-b2-threads-and-synchronisation-atomic) instruction when the [critical section](#def-b2-threads-and-synchronisation-mutex-property) is one operation:

```c
static void *locked(void *arg)                   /* the three steps under a mutex */
{
    (void)arg;
    for (long k = 0; k < N; k++) {
        pthread_mutex_lock(&m);
        plain = plain + 1;
        pthread_mutex_unlock(&m);
    }
    return NULL;
}

static void *atomic_add(void *arg)               /* one indivisible instruction */
{
    (void)arg;
    for (long k = 0; k < N; k++)
        atomic_fetch_add(&counter, 1);
    return NULL;
}
```

***Listing 15.7.** The counter under a mutex, and as one [atomic](#def-b2-threads-and-synchronisation-atomic) instruction code/bachelor-2/15-threads-and-synchronisation/listings/race.c*

Both are exact ([Output 15.2](#out-b2-threads-and-synchronisation-race)), and both cost time: the racy loop is fast because the [threads](#def-b2-threads-and-synchronisation-thread) do not cooperate. The mutex costs most, because a [thread](#def-b2-threads-and-synchronisation-thread) that finds it held is put to sleep by the kernel and woken later.

## 15.4 Waiting for a condition

A [lock](#def-b2-threads-and-synchronisation-lock) keeps [threads](#def-b2-threads-and-synchronisation-thread) apart. Often a [thread](#def-b2-threads-and-synchronisation-thread) must also wait for something another [thread](#def-b2-threads-and-synchronisation-thread) will do: a consumer for an item, a producer for a free slot.

**Definition 15.11 (Condition variable).**

A *condition variable* lets a [thread](#def-b2-threads-and-synchronisation-thread) holding a [lock](#def-b2-threads-and-synchronisation-lock) wait for a condition on the data the [lock](#def-b2-threads-and-synchronisation-lock) protects. `pthread_cond_wait(&c, &m)` releases `m` and puts the [thread](#def-b2-threads-and-synchronisation-thread) to sleep, in one step; when another [thread](#def-b2-threads-and-synchronisation-thread) calls `pthread_cond_signal(&c)` (wake one waiter) or `pthread_cond_broadcast(&c)` (wake all), the sleeper wakes and takes `m` again before returning.

**Definition 15.12 (Bounded buffer).**

A *bounded buffer* is a queue of at most $N$ items shared by *producer* [threads](#def-b2-threads-and-synchronisation-thread), which add items, and *consumer* [threads](#def-b2-threads-and-synchronisation-thread), which remove them; a producer waits while the buffer is full, and a consumer while it is empty.

It is the standard case of waiting for a condition. Here the buffer is a ring of $N$ slots.

```c
static void put(long x)
{
    pthread_mutex_lock(&m);
    while (count == SLOTS)                       /* while, not if: see exercise 6 */
        pthread_cond_wait(&not_full, &m);        /* unlocks m, sleeps, relocks m */
    ring[(head + count) % SLOTS] = x;
    count++;
    if (count > most)
        most = count;
    pthread_cond_signal(&not_empty);
    pthread_mutex_unlock(&m);
}

static long take(void)
{
    pthread_mutex_lock(&m);
    while (count == 0)
        pthread_cond_wait(&not_empty, &m);
    long x = ring[head];
    head = (head + 1) % SLOTS;
    count--;
    pthread_cond_signal(&not_full);
    pthread_mutex_unlock(&m);
    return x;
}
```

***Listing 15.8.** Putting and taking under one [lock](#def-b2-threads-and-synchronisation-lock), with two conditions code/bachelor-2/15-threads-and-synchronisation/listings/bounded_buffer.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o bounded_buffer bounded_buffer.c -lm && ./bounded_buffer
sum taken: 10000100000, sum put: 10000100000
never more than 8 items held: yes
```

***Output 15.6.** Two producers, two consumers, 200 000 items through 8 slots.*

The condition is tested in a `while`, not an `if`: between the signal and the moment the woken [thread](#def-b2-threads-and-synchronisation-thread) takes the [lock](#def-b2-threads-and-synchronisation-lock) again, another [thread](#def-b2-threads-and-synchronisation-thread) may have taken the item. The explorer finds such a schedule ([Exercise 15.6](#exo-b2-threads-and-synchronisation-6)).

**Definition 15.13 (Semaphore).**

A *semaphore* is a non-negative integer with two [atomic operations](#def-b2-threads-and-synchronisation-atomic): $P$ (`sem_wait`) waits until the value is positive and decreases it by 1; $V$ (`sem_post`) increases it by 1, waking a waiter if there is one. A semaphore that starts at $N$ counts $N$ available resources.

With two [semaphores](#def-b2-threads-and-synchronisation-semaphore) the ring needs no condition at all: `empty` counts the free slots and `full` the filled ones, and the mutex only protects the indices.

```c
static void put(long x)
{
    sem_wait(&empty);                            /* P: wait for a free slot */
    pthread_mutex_lock(&m);
    ring[in] = x;
    in = (in + 1) % SLOTS;
    pthread_mutex_unlock(&m);
    sem_post(&full);                             /* V: one more filled slot */
}

static long take(void)
{
    sem_wait(&full);
    pthread_mutex_lock(&m);
    long x = ring[out];
    out = (out + 1) % SLOTS;
    pthread_mutex_unlock(&m);
    sem_post(&empty);
    return x;
}
```

***Listing 15.9.** The ring with [semaphores](#def-b2-threads-and-synchronisation-semaphore): wait for a slot, fill it, announce it code/bachelor-2/15-threads-and-synchronisation/listings/semaphores.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o semaphores semaphores.c -lm && ./semaphores
sum taken: 10000100000, sum put: 10000100000
at the end: empty = 8, full = 0
```

***Output 15.7.** Every item arrives, and the [semaphores](#def-b2-threads-and-synchronisation-semaphore) end as they started.*

**Proposition 15.14 (The buffer’s invariant).**

Let *produced* be the number of items written into the ring and *consumed* the number read from it. At every moment, $0 \le \text{produced} - \text{consumed} \le N$; so no slot is overwritten before it is read, and none is read before it is written.

**Proof.** A [semaphore](#def-b2-threads-and-synchronisation-semaphore)’s value is its initial value plus its $V$s minus its completed $P$s, and is never negative. Each item read was preceded by a completed $P$ on `full`, and each $V$ on `full` follows an item written: $\text{consumed} \le P(\text{full}) \le V(\text{full}) \le \text{produced}$. Each item written was preceded by a $P$ on `empty`, and each $V$ on `empty` follows an item read: $\text{produced} \le P(\text{empty}) \le N +
V(\text{empty}) \le N + \text{consumed}$. With the indices advancing modulo $N$, the writer is never more than $N$ slots ahead of the reader, nor behind it. ∎

![The ring of 8 slots. A producer takes a free slot (P on empty), fills slot in, and announces it (V on full); a consumer does the reverse from out.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-threads-and-synchronisation/fig-ca10ddf10161.svg)

*The ring of 8 slots. A producer takes a free slot (P on `empty`), fills slot `in`, and announces it (V on `full`); a consumer does the reverse from `out`.*

Two more patterns use the same tools.

**Definition 15.15 (Barrier).**

A *barrier* for $k$ [threads](#def-b2-threads-and-synchronisation-thread) has one operation, *wait*, which returns in none of them until all $k$ have called it; it is then ready for the next round.

A [barrier](#def-b2-threads-and-synchronisation-barrier) separates work that proceeds in rounds; `pthread_barrier_wait` returns a special value to exactly one of the $k$ [threads](#def-b2-threads-and-synchronisation-thread):

```c
static void *work(void *arg)
{
    int i = *(int *)arg;
    for (int r = 1; r <= ROUNDS; r++) {
        part[i] = (long)r * (i + 1);             /* this round's work */
        int last = pthread_barrier_wait(&bar);   /* all four parts are written */
        if (last == PTHREAD_BARRIER_SERIAL_THREAD) {
            long total = 0;                      /* exactly one thread reports */
            for (int j = 0; j < T; j++)
                total += part[j];
            printf("round %d: total %ld\n", r, total);
        }
        pthread_barrier_wait(&bar);              /* nobody overwrites before the report */
    }
    return NULL;
}
```

***Listing 15.10.** Rounds separated by two [barriers](#def-b2-threads-and-synchronisation-barrier) code/bachelor-2/15-threads-and-synchronisation/listings/barrier.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o barrier barrier.c -lm && ./barrier
round 1: total 10
round 2: total 20
round 3: total 30
```

***Output 15.8.** Each round’s report sees the four parts of that round.*

**Definition 15.16 (Readers–writers lock).**

A *readers–writers lock* can be held in two modes: by any number of [threads](#def-b2-threads-and-synchronisation-thread) at once for reading, or by one [thread](#def-b2-threads-and-synchronisation-thread) alone for writing, never both.

It can be built as a [lock](#def-b2-threads-and-synchronisation-lock) that counts readers. If readers keep arriving, a writer may wait forever.

**Definition 15.17 (Starvation).**

A [thread](#def-b2-threads-and-synchronisation-thread) *starves* when it waits forever for a resource that other [threads](#def-b2-threads-and-synchronisation-thread) keep obtaining, although the program as a whole goes on.

A writer-preferring [lock](#def-b2-threads-and-synchronisation-lock) stops admitting readers as soon as a writer waits ([Exercise 15.9](#exo-b2-threads-and-synchronisation-9)); it can then starve readers instead. [Starvation](#def-b2-threads-and-synchronisation-starvation) differs from deadlock, where nobody goes on.

Five philosophers sit at a round table with a fork between each pair of plates; to eat, a philosopher needs both neighbouring forks. If each takes the left fork and then the right, and all five sit down together, each holds one fork and waits for the next: a deadlock. With timed [locks](#def-b2-threads-and-synchronisation-lock) the program reports it instead of hanging:

```c
static void *dine(void *arg)
{
    int i = *(int *)arg, left = i, right = (i + 1) % P;
    pthread_mutex_lock(&fork_[left]);
    pause_ms(100);                               /* everyone is now holding a fork */
    struct timespec limit;
    clock_gettime(CLOCK_REALTIME, &limit);
    limit.tv_sec += 1;                           /* wait at most one second */
    if (pthread_mutex_timedlock(&fork_[right], &limit) == ETIMEDOUT) {
        stuck[i] = right;
    } else {
        stuck[i] = -1;                           /* eats */
        pthread_mutex_unlock(&fork_[right]);
    }
    pthread_barrier_wait(&done);                 /* all five have tried */
    pthread_mutex_unlock(&fork_[left]);
    return NULL;
}
```

***Listing 15.11.** Left fork, then right, with a time limit code/bachelor-2/15-threads-and-synchronisation/listings/philosophers.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o philosophers philosophers.c -lm && ./philosophers
philosopher 0 held fork 0, waited 1 s for fork 1
philosopher 1 held fork 1, waited 1 s for fork 2
philosopher 2 held fork 2, waited 1 s for fork 3
philosopher 3 held fork 3, waited 1 s for fork 4
philosopher 4 held fork 4, waited 1 s for fork 0
```

***Output 15.9.** The circle of waits.*

**Proposition 15.18 (Lock order).**

If the [locks](#def-b2-threads-and-synchronisation-lock) are numbered and every [thread](#def-b2-threads-and-synchronisation-thread) that holds several [locks](#def-b2-threads-and-synchronisation-lock) acquired them in increasing order, no set of [threads](#def-b2-threads-and-synchronisation-thread) can be waiting for each other in a circle.

The proof is [Exercise 15.12](#exo-b2-threads-and-synchronisation-12). For the table, number the forks 0 to 4: every philosopher takes the lower-numbered of their two forks first. Only philosopher 4, between forks 4 and 0, changes: fork 0 first.

```
$ gcc -std=c17 -O2 -Wall -Wextra -o philosophers_ordered philosophers_ordered.c -lm && ./philosophers_ordered
philosopher 0 ate 100000 times
philosopher 1 ate 100000 times
philosopher 2 ate 100000 times
philosopher 3 ate 100000 times
philosopher 4 ate 100000 times
```

***Output 15.10.** Ordered: every philosopher eats, 100 000 times.*

![The philosophers’ table, forks numbered between the plates. The order of needs only one philosopher to change hands.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-threads-and-synchronisation/fig-83a2463f9dd8.svg)

*The philosophers’ table, forks numbered between the plates. The order of [Proposition 15.18](#prop-b2-threads-and-synchronisation-order) needs only one philosopher to change hands.*

**History.**

Edsger Dijkstra’s notes *Cooperating sequential processes*, written in the mid-1960s, present Th. J. Dekker’s solution to [mutual exclusion](#def-b2-threads-and-synchronisation-mutex-property) for two [processes](https://one-course.com/books/computer-science/4/en/chapter/13-processes-and-system-calls#def-b2-processes-and-system-calls-process), the first correct one, and introduce the [semaphore](#def-b2-threads-and-synchronisation-semaphore) with its operations $P$ and $V$. A few years later, his notes *Hierarchical ordering of sequential processes* posed the five dining philosophers. Leslie Lamport published the bakery algorithm in 1974; it needs no [atomic operation](#def-b2-threads-and-synchronisation-atomic) beyond reading and writing a number. Gary Peterson’s [two-thread](#def-b2-threads-and-synchronisation-thread) algorithm, far shorter than Dekker’s, appeared in 1981 in a two-page note titled *Myths about the [mutual exclusion](#def-b2-threads-and-synchronisation-mutex-property) problem*.

## 15.5 The same programs in C++ and Rust

C++ wraps the same objects in classes. A `std::lock_guard` [locks](#def-b2-threads-and-synchronisation-lock) in its [constructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) and unlocks in its [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor), so no path out of the block, `return` or [exception](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-exception), can keep the [lock](#def-b2-threads-and-synchronisation-lock) ([Chapter 1](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#ch-b2-cpp-classes-raii)):

```cpp
    std::vector<std::thread> threads;
    for (int i = 0; i < 4; i++)
        threads.emplace_back([&] {                    // captures by reference: shared
            for (long k = 0; k < n; k++) {
                {
                    std::lock_guard<std::mutex> guard(m);   // locks here ...
                    plain++;
                }                                           // ... unlocks here, always
                atom.fetch_add(1);
            }
        });
    for (auto &t : threads)
        t.join();
    std::printf("mutex: %ld, atomic: %ld, expected %ld\n", plain, atom.load(), 4 * n);
```

***Listing 15.12.** Four `std::thread`s, a guarded counter and an [atomic](#def-b2-threads-and-synchronisation-atomic) one code/bachelor-2/15-threads-and-synchronisation/listings/counter_threads.cpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o counter_threads counter_threads.cpp && ./counter_threads
mutex: 4000000, atomic: 4000000, expected 4000000
```

***Output 15.11.** Both exact.*

`std::counting_semaphore` gives the [semaphore](#def-b2-threads-and-synchronisation-semaphore) ring as a [class template](https://one-course.com/books/computer-science/4/en/chapter/4-templates-and-generic-programming#def-b2-cpp-templates-template):

```cpp
    void put(T x)
    {
        free_.acquire();                         // a free slot, or wait
        {
            std::lock_guard<std::mutex> g(m_);
            ring_[in_] = std::move(x);
            in_ = (in_ + 1) % N;
        }
        filled_.release();
    }

    T take()
    {
        filled_.acquire();                       // a filled slot, or wait
        T x;
        {
            std::lock_guard<std::mutex> g(m_);
            x = std::move(ring_[out_]);
            out_ = (out_ + 1) % N;
        }
        free_.release();
        return x;
    }
```

***Listing 15.13.** A bounded queue in C++20 code/bachelor-2/15-threads-and-synchronisation/listings/bounded_queue.hpp*

```
$ g++ -std=c++20 -O2 -Wall -Wextra -o pc_cpp pc_cpp.cpp && ./pc_cpp
sum taken: 10000100000, sum put: 10000100000
```

***Output 15.12.** Two producers and two consumers on a `BoundedQueue<long, 8>`.*

C and C++ accept a [data race](#def-b2-threads-and-synchronisation-data-race) and leave its behaviour undefined. Rust refuses it at compile time. A [thread](#def-b2-threads-and-synchronisation-thread) started by `thread::spawn` may outlive the function that started it, so it may not [borrow](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#def-b2-rust-ownership-borrow) that function’s variables:

```rust
fn main() {
    let mut count = 0;
    let t = thread::spawn(|| {
        for _ in 0..1000 {
            count += 1;
        }
    });
    t.join().unwrap();
    println!("{count}");
}
```

***Listing 15.14.** A [thread](#def-b2-threads-and-synchronisation-thread) that [borrows](https://one-course.com/books/computer-science/4/en/chapter/6-rust-ownership-and-borrowing#def-b2-rust-ownership-borrow) `count` code/bachelor-2/15-threads-and-synchronisation/listings/race_refused.rs*

```
$ rustc --edition 2021 -O -o race_refused race_refused.rs && ./race_refused
error[E0373]: closure may outlive the current function, but it borrows `count`, which is owned by the current function
  --> race_refused.rs:7:27
   |
 7 |     let t = thread::spawn(|| {
   |                           ^^ may outlive borrowed value `count`
 8 |         for _ in 0..1000 {
 9 |             count += 1;
   |             ----- `count` is borrowed here
   |
note: function requires argument type to outlive `'static`
  --> race_refused.rs:7:13
```

***Output 15.13.** The first of two errors: the [thread](#def-b2-threads-and-synchronisation-thread) could outlive `count`. Some lines are left out.*

The compiler suggests `move`; for an `i32`, that would give the [thread](#def-b2-threads-and-synchronisation-thread) its own copy, and `main` would print 0, which is safe and not what we meant. Sharing a counter takes [shared ownership](https://one-course.com/books/computer-science/4/en/chapter/2-copying-moving-and-smart-pointers#def-b2-cpp-copy-move-shared-ptr), `Arc`, of a value that can be changed only through a [lock](#def-b2-threads-and-synchronisation-lock), `Mutex`:

```rust
fn main() {
    let count = Arc::new(Mutex::new(0_u64));     // shared ownership of a locked value
    let mut handles = Vec::new();
    for _ in 0..4 {
        let count = Arc::clone(&count);          // one owner more per thread
        handles.push(thread::spawn(move || {
            for _ in 0..1_000_000 {
                *count.lock().unwrap() += 1;     // the guard unlocks at the end of the line
            }
        }));
    }
    for h in handles {
        h.join().unwrap();
    }
    println!("count = {}", *count.lock().unwrap());
}
```

***Listing 15.15.** `Arc<Mutex<u64>>`: the only way in is `lock()` code/bachelor-2/15-threads-and-synchronisation/listings/arc_mutex.rs*

```
$ rustc --edition 2021 -O -o arc_mutex arc_mutex.rs && ./arc_mutex
count = 4000000
```

***Output 15.14.** Exact.*

The data is inside the mutex, so it cannot be reached without the [lock](#def-b2-threads-and-synchronisation-lock); the guard returned by `lock()` unlocks when dropped. Rust also offers channels, queues between [threads](#def-b2-threads-and-synchronisation-thread); a `sync_channel(8)` is the [bounded buffer](#def-b2-threads-and-synchronisation-bounded-buffer), and its receiving end sees the end of the stream when every sender has been dropped, like a [pipe](https://one-course.com/books/computer-science/4/en/chapter/14-files-pipes-and-signals#def-b2-files-pipes-signals-pipe)’s reader ([Chapter 14](https://one-course.com/books/computer-science/4/en/chapter/14-files-pipes-and-signals#ch-b2-files-pipes-signals)):

```rust
fn main() {
    let (tx, rx) = mpsc::sync_channel::<u64>(8); // at most 8 messages in flight
    for _ in 0..2 {
        let tx = tx.clone();
        thread::spawn(move || {
            for k in 1..=100_000 {
                tx.send(k).unwrap();             // waits while the channel is full
            }
        });                                      // tx dropped: one sender fewer
    }
    drop(tx);                                    // keep no sender here, or recv never ends
    let sum: u64 = rx.iter().sum();              // ends when every sender is dropped
    println!("sum received: {sum}");
}
```

***Listing 15.16.** Producers and a consumer joined by a channel code/bachelor-2/15-threads-and-synchronisation/listings/channel_pc.rs*

```
$ rustc --edition 2021 -O -o channel_pc channel_pc.rs && ./channel_pc
sum received: 10000100000
```

***Output 15.15.** All 200 000 items.*

**In practice — Ticket offices, banks and shared counters.**

Every booking system meets the hook’s race: two agents, one seat. Databases settle it with transactions ([Chapter 30](https://one-course.com/books/computer-science/4/en/chapter/30-database-design-dependencies-normal-forms-and-transactions#ch-b2-database-design)), servers with [locks](#def-b2-threads-and-synchronisation-lock) or with one [atomic operation](#def-b2-threads-and-synchronisation-atomic) such as “decrement if positive”. The working rules are short: protect every shared variable by one [lock](#def-b2-threads-and-synchronisation-lock), always the same; hold it briefly; acquire several [locks](#def-b2-threads-and-synchronisation-lock) in one global order; wait for conditions in a `while`; and prefer a language or a tool that finds [data races](#def-b2-threads-and-synchronisation-data-race) for you.

![A ticket office with three windows: three clerks selling from one stock of seats.](https://one-course.com/images/onecourse/chapters/computer-science-4/b2-threads-and-synchronisation/img-73cd739f4783.jpg)

*A ticket office with three windows: three clerks selling from one stock of seats.*

## 15.6 Exercises

**Exercise 15.1 ★.**

Two [threads](#def-b2-threads-and-synchronisation-thread) each run `r = x; x = r + 1;` twice, with `x` shared and starting at 0. Which final values of `x` are possible? Give a schedule for each, and say how many schedules there are.

**Solution of Exercise 15.1.**

Each [thread](#def-b2-threads-and-synchronisation-thread) has 4 steps, so there are $\binom{8}{4} = 70$ schedules ([Proposition 15.3](#prop-b2-threads-and-synchronisation-interleavings)). The final value is 4, 3 or 2. It is 4 when no load is overwritten, as when A runs its four steps and then B its four. It is 3 when exactly one update is lost: A loads 0, B loads 0, A stores 1, B stores 1, then A loads 1 and stores 2, B loads 2 and stores 3. It is 2 when A loads 0, B runs both its increments (`x` becomes 2), A stores 1, then A loads 1 and stores 2. It cannot be 1: every store writes at least 1, so a [thread](#def-b2-threads-and-synchronisation-thread)’s second load, which follows its own first store, reads at least 1, and its last store writes at least 2; the final value is some [thread](#def-b2-threads-and-synchronisation-thread)’s last store. The explorer, on `counter(2)`, counts 6 schedules giving 4, 32 giving 3 and 32 giving 2.

**Exercise 15.2 ★.**

This program stops after its second line. Find the bug and fix it in two ways.

```c
static int withdraw(long amount)
{
    pthread_mutex_lock(&m);
    if (amount > balance)
        return 0;                                /* refused */
    balance -= amount;
    pthread_mutex_unlock(&m);
    return 1;
}
```

***Listing 15.17.** A withdrawal that may be refused code/bachelor-2/15-threads-and-synchronisation/listings/exo_early_return.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o exo_early_return exo_early_return.c -lm && ./exo_early_return
withdraw 30: 1
withdraw 500: 0

[killed after 3 s]
[exit status -9]
```

***Output 15.16.** The third call never returns.*

**Solution of Exercise 15.2.**

The refusal returns with the mutex still locked: the next call to `withdraw` waits for it forever on this system, in the same [thread](#def-b2-threads-and-synchronisation-thread), which nothing will ever wake. (Locking a default mutex again from the [thread](#def-b2-threads-and-synchronisation-thread) that holds it is undefined in POSIX; the glibc mutex deadlocks, which is what the run shows.) First fix: unlock before every `return`, here with an `pthread_mutex_unlock(&m)` before `return 0`. Second fix: a single exit, `int ok = amount <= balance; if (ok) balance -= amount;` and one unlock before `return ok`. In C++ a `std::lock_guard` makes the bug impossible, since its [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor) unlocks on every path ([Exercise 15.3](#exo-b2-threads-and-synchronisation-3)).

**Exercise 15.3 ★.**

Write a C++ class `SafeCounter` with `add(d)`, `take(d)` (subtract $d$ only if the counter holds at least $d$, and say whether it did) and `get()`, safe to call from many [threads](#def-b2-threads-and-synchronisation-thread), using `std::lock_guard`.

**Solution of Exercise 15.3.**

```cpp
class SafeCounter {
public:
    void add(long d)
    {
        std::lock_guard<std::mutex> g(m_);       // unlocked by g's destructor
        value_ += d;
    }

    bool take(long d)                            // subtract d if the counter holds d
    {
        std::lock_guard<std::mutex> g(m_);
        if (value_ < d)
            return false;                        // early return: still unlocked
        value_ -= d;
        return true;
    }

    long get() const
    {
        std::lock_guard<std::mutex> g(m_);
        return value_;
    }

private:
    mutable std::mutex m_;                       // get() is const, yet locks
    long value_ = 0;
};
```

*`SafeCounter` code/bachelor-2/15-threads-and-synchronisation/exercises/safe_counter.hpp*

Each member takes the [lock](#def-b2-threads-and-synchronisation-lock) for its whole body, so `take`’s test and subtraction form one [critical section](#def-b2-threads-and-synchronisation-mutex-property): two [threads](#def-b2-threads-and-synchronisation-thread) cannot both see 5 and both take 5. The early `return false` unlocks through the guard’s [destructor](https://one-course.com/books/computer-science/4/en/chapter/1-from-c-to-c-classes-and-resource-management#def-b2-cpp-classes-raii-constructor). The mutex is `mutable` so that the `const` member `get` can [lock](#def-b2-threads-and-synchronisation-lock) it. The test runs 8 [threads](#def-b2-threads-and-synchronisation-thread), each adding 2 and taking 1 ten thousand times, and finds 80 000.

**Exercise 15.4 ★.**

How many [interleavings](#def-b2-threads-and-synchronisation-interleaving) do two [threads](#def-b2-threads-and-synchronisation-thread) of 5 steps have? Three [threads](#def-b2-threads-and-synchronisation-thread) of 2 steps each? Generalise the proposition to $k$ [threads](#def-b2-threads-and-synchronisation-thread) of $n_1, \dots, n_k$ steps.

**Solution of Exercise 15.4.**

Two [threads](#def-b2-threads-and-synchronisation-thread) of 5 steps: $\binom{10}{5} = 252$. Three [threads](#def-b2-threads-and-synchronisation-thread) of 2 steps: choose the positions of the first [thread](#def-b2-threads-and-synchronisation-thread)’s steps, then of the second’s among those left: $\binom{6}{2}\binom{4}{2} = 15 \times 6 = 90$. In general, $k$ [threads](#def-b2-threads-and-synchronisation-thread) of $n_1, \dots, n_k$ steps have the multinomial number $\frac{(n_1 + \dots + n_k)!}{n_1! \cdots n_k!}$ of [interleavings](#def-b2-threads-and-synchronisation-interleaving): each arrangement of the $n = \sum n_i$ positions among the [threads](#def-b2-threads-and-synchronisation-thread) is one [interleaving](#def-b2-threads-and-synchronisation-interleaving), and there are $n!$ orders of $n$ distinct steps, of which only one in $n_1! \cdots n_k!$ keeps every [thread](#def-b2-threads-and-synchronisation-thread) in its order. The test checks $9!/(3!\,3!\,3!) = 1680$.

**Exercise 15.5 ★★.**

`s` and `t` are [semaphores](#def-b2-threads-and-synchronisation-semaphore) starting at 0. What can this program print? List every output.

```c
static void *one(void *arg)
{
    (void)arg;
    printf("A");
    sem_post(&s);
    printf("C");
    sem_wait(&t);
    printf("E\n");
    return NULL;
}

static void *two(void *arg)
{
    (void)arg;
    printf("B");
    sem_wait(&s);
    printf("D");
    sem_post(&t);
    return NULL;
}
```

***Listing 15.18.** Two [threads](#def-b2-threads-and-synchronisation-thread), two [semaphores](#def-b2-threads-and-synchronisation-semaphore) code/bachelor-2/15-threads-and-synchronisation/listings/exo_sem.c*

**Solution of Exercise 15.5.**

```
$ python sem_outcomes.py
13 schedules, 0 stuck, 5 different outputs:
   ABCDE  (4 schedules)
   ABDCE  (4 schedules)
   ACBDE  (1 schedules)
   BACDE  (2 schedules)
   BADCE  (2 schedules)
```

***Output 15.18.** The explorer on the program’s model.*

Order the five prints. [Thread](#def-b2-threads-and-synchronisation-thread) one prints A, C, E in that order and [thread](#def-b2-threads-and-synchronisation-thread) two B then D. `D` comes after `post(s)`, so after A; `E` comes after `wait(t)`, which needs `post(t)`, so after D. Hence E is last, and A, B, C, D appear in any order with A before C, B before D and A before D. The orders of four letters with A before C and B before D are 6; the one with D before A, BDAC, is excluded. Five outputs remain. Each `printf` is treated as one step: the library [locks](#def-b2-threads-and-synchronisation-lock) the stream for each call, so letters never mix inside a call.

**Exercise 15.6 ★★.**

In `bounded_buffer.c`, replace `while (count == 0)` by `if (count == 0)`. Model one producer of two items and two consumers of one item each, with a [lock](#def-b2-threads-and-synchronisation-lock) and a condition, and let the explorer find a schedule in which a consumer takes from an empty buffer.

**Solution of Exercise 15.6.**

```python
def consumer(name, loop):
    def check(s, me):                             # step 1: test the condition
        return 4 if s["count"] > 0 else None      # jump to take, or go on to wait

    def wait(s, me):                              # step 2: release and sleep
        s.update(owner=0, waiting=s["waiting"] + (name,))

    def take(s, me):
        s.update(count=s["count"] - 1, bad=s["bad"] or s["count"] == 0)

    woken = ("wake, lock again",
             lambda s, me: name in s["woken"] and s["owner"] == 0,
             lambda s, me: s.update(owner=1, woken=tuple(w for w in s["woken"]
                                                         if w != name))
             or (1 if loop else 4))
    return [lock(), ("count > 0?", None, check), ("wait", None, wait), woken,
            ("take an item", None, take), unlock()]
```

*A consumer: test, wait, wake, take code/bachelor-2/15-threads-and-synchronisation/listings/cond_model.py*

```
$ python cond_model.py
if around the wait: 24 schedules, 2 bad
   e.g. C1: lock | C1: count > 0? | C1: wait | P: lock | P: count += 1 | P: signal | P:
        unlock | C2: lock | C2: count > 0? | C2: take an item | C2: unlock | C1: wake,
        lock again | C1: take an item | C1: unlock | P: lock | P: count += 1 | P: signal
        | P: unlock
while around the wait: 24 schedules, 0 bad
```

***Output 15.19.** `if` lets a consumer take from an empty buffer; `while` never does.*

`wait` releases the [lock](#def-b2-threads-and-synchronisation-lock) and records the [thread](#def-b2-threads-and-synchronisation-thread) as waiting; a signal moves one waiter to the woken set; a woken [thread](#def-b2-threads-and-synchronisation-thread) must win the [lock](#def-b2-threads-and-synchronisation-lock) again. In the bad schedule C1 waits; the producer adds an item and signals, waking C1; but C2 takes the [lock](#def-b2-threads-and-synchronisation-lock) first and takes the item. C1 then gets the [lock](#def-b2-threads-and-synchronisation-lock), and with `if` goes straight on to take from an empty buffer. With `while`, C1 tests again, finds 0 and waits again, until the second item. The cause is that a woken [thread](#def-b2-threads-and-synchronisation-thread) does not own the [lock](#def-b2-threads-and-synchronisation-lock) between the signal and its return from `wait`: what was true at the signal may be false by then. POSIX also allows spurious wake-ups, with no signal at all, another reason for the loop.

**Exercise 15.7 ★★.**

Write a [barrier](#def-b2-threads-and-synchronisation-barrier) for $n$ [threads](#def-b2-threads-and-synchronisation-thread) from a mutex and a [condition variable](#def-b2-threads-and-synchronisation-condvar), `barrier2_wait(b)`, that can be used again and again, and returns 1 to exactly one [thread](#def-b2-threads-and-synchronisation-thread) per use. Why is the test `while (waiting < n)` wrong?

**Solution of Exercise 15.7.**

```c
int barrier2_wait(struct barrier2 *b)
{
    pthread_mutex_lock(&b->m);
    unsigned long my_round = b->round;
    int last = ++b->waiting == b->n;
    if (last) {
        b->waiting = 0;                          /* ready for the next use at once */
        b->round++;
        pthread_cond_broadcast(&b->all_here);
    } else {
        while (b->round == my_round)             /* not "waiting < n": that is reset */
            pthread_cond_wait(&b->all_here, &b->m);
    }
    pthread_mutex_unlock(&b->m);
    return last;
}
```

*A reusable [barrier](#def-b2-threads-and-synchronisation-barrier): the last to arrive opens a new round code/bachelor-2/15-threads-and-synchronisation/exercises/barrier2.c*

The last [thread](#def-b2-threads-and-synchronisation-thread) to arrive resets the count and increments `round`, then wakes everyone. A waiting [thread](#def-b2-threads-and-synchronisation-thread) waits for `round` to change, not for the count to reach $n$. With `while (waiting < n)`, the count is reset to 0 by the last arrival, so a woken [thread](#def-b2-threads-and-synchronisation-thread) that tests it finds it below $n$ and sleeps again, forever; and if it were not reset, the next use could not start. Keeping the round number in a local variable also protects against spurious wake-ups. The test runs 1, 2, 4 and 8 [threads](#def-b2-threads-and-synchronisation-thread) through 2000 rounds of two uses each, checks that nobody is ever a round ahead, and that exactly one [thread](#def-b2-threads-and-synchronisation-thread) per round is told it was last.

**Exercise 15.8 ★★.**

Prove part (1) of [Theorem 15.9](#thm-b2-threads-and-synchronisation-peterson) again, this time when the two lines of the entry are swapped: `turn = j` first, then `flag[i] = true`. If the proof fails, give a schedule that breaks [mutual exclusion](#def-b2-threads-and-synchronisation-mutex-property).

**Solution of Exercise 15.8.**

The proof fails, and the algorithm too. With the entry `turn = j; flag[i] = true`: [thread](#def-b2-threads-and-synchronisation-thread) 0 writes `turn = 1`; [thread](#def-b2-threads-and-synchronisation-thread) 1 writes `turn = 0`, sets `flag[1]`, and tests: `flag[0]` is still false, so [thread](#def-b2-threads-and-synchronisation-thread) 1 enters. [Thread](#def-b2-threads-and-synchronisation-thread) 0 sets `flag[0]` and tests: `flag[1]` is true but `turn` is 0, its own number, so [thread](#def-b2-threads-and-synchronisation-thread) 0 enters too. The proof used that the [thread](#def-b2-threads-and-synchronisation-thread) writing `turn` last had the other’s flag already set, which the swap destroys. The explorer, on the swapped model, finds 12 bad schedules out of 60.

**Exercise 15.9 ★★.**

Write in Rust a [readers–writers lock](#def-b2-threads-and-synchronisation-rwlock) with writer preference, `RwLockW`, with `read_lock`, `read_unlock`, `write_lock` and `write_unlock`, from a `Mutex` and a `Condvar`. Which [threads](#def-b2-threads-and-synchronisation-thread) can starve?

**Solution of Exercise 15.9.**

```rust
    pub fn read_lock(&self) {
        let mut s = self.state.lock().unwrap();
        while s.writer || s.writers_waiting > 0 {   // a waiting writer goes first
            s = self.changed.wait(s).unwrap();
        }
        s.readers += 1;
    }

    pub fn read_unlock(&self) {
        let mut s = self.state.lock().unwrap();
        s.readers -= 1;
        if s.readers == 0 {
            self.changed.notify_all();
        }
    }

    pub fn write_lock(&self) {
        let mut s = self.state.lock().unwrap();
        s.writers_waiting += 1;
        while s.writer || s.readers > 0 {
            s = self.changed.wait(s).unwrap();
        }
        s.writers_waiting -= 1;
        s.writer = true;
    }

    pub fn write_unlock(&self) {
        let mut s = self.state.lock().unwrap();
        s.writer = false;
        self.changed.notify_all();
    }
```

*Readers wait while a writer is inside or waiting code/bachelor-2/15-threads-and-synchronisation/exercises/rwlock.rs*

The state, behind one `Mutex`, counts the readers inside, says whether a writer is inside, and counts the waiting writers. A reader waits while a writer is inside or waiting: that is the preference. A writer waits while anyone is inside. Every unlock that may let someone in notifies all waiters, which test their condition again in a `while`. Readers can starve, if writers keep arriving; writers cannot, since once one waits no new reader enters. The test checks with an [atomic](#def-b2-threads-and-synchronisation-atomic) counter that a writer is always alone, and that a reader arriving after a waiting writer enters after it.

**Exercise 15.10 ★★★.**

The naive flag [lock](#def-b2-threads-and-synchronisation-lock) waits until `flag == 0`, then sets `flag = 1`. Exhibit, by hand, a schedule in which both [threads](#def-b2-threads-and-synchronisation-thread) are in their [critical sections](#def-b2-threads-and-synchronisation-mutex-property); then explain why the explorer finds 24 bad schedules out of 42, by counting the schedules in which each [thread](#def-b2-threads-and-synchronisation-thread) passes its wait before the other sets the flag.

**Solution of Exercise 15.10.**

A schedule: A passes its wait (`flag` is 0), B passes its wait (`flag` is still 0), A sets `flag = 1`, B sets `flag = 1`; both are in their [critical sections](#def-b2-threads-and-synchronisation-mutex-property). Counting the explorer’s schedules: if one [thread](#def-b2-threads-and-synchronisation-thread) sets the flag before the other has passed its wait, the other waits until the flag is cleared, so the [threads](#def-b2-threads-and-synchronisation-thread) run one after the other: 2 schedules. Otherwise both waits come first, in 2 orders, followed by any [interleaving](#def-b2-threads-and-synchronisation-interleaving) of the two remaining chains of 3 steps (set, [critical section](#def-b2-threads-and-synchronisation-mutex-property), clear): $2 \times \binom{6}{3} = 40$ schedules, $40 + 2 = 42$. Among the 20 [interleavings](#def-b2-threads-and-synchronisation-interleaving) of the two chains, the [critical sections](#def-b2-threads-and-synchronisation-mutex-property) overlap unless one [thread](#def-b2-threads-and-synchronisation-thread) has already entered (run its critical-section step) before the other sets its flag: that is 4 [interleavings](#def-b2-threads-and-synchronisation-interleaving) for each [thread](#def-b2-threads-and-synchronisation-thread) finishing first, 8 in all, so $20 - 8 = 12$ overlap, and $2 \times 12 = 24$ schedules are bad.

**Exercise 15.11 ★★★.**

Model the bakery for three [threads](#def-b2-threads-and-synchronisation-thread), reading the other tickets one at a time, and check [mutual exclusion](#def-b2-threads-and-synchronisation-mutex-property) over every schedule, for one and for two passes per [thread](#def-b2-threads-and-synchronisation-thread). Then remove `choosing` and find a violation.

**Solution of Exercise 15.11.**

```python
def bakery_thread(i, rounds=1):
    steps = []
    for _ in range(rounds):
        steps.append((f"choosing{i} = 1", None,
                      lambda s, me: s.update({f"choosing{i}": 1}) or me.update(mx=0)))
        for j in range(N):                        # read the tickets one at a time
            steps.append((f"read number{j}", None,
                          lambda s, me, j=j: me.update(mx=max(me["mx"], s[f"n{j}"]))))
        steps.append((f"number{i} = max + 1", None,
                      lambda s, me: s.update({f"n{i}": me["mx"] + 1})))
        steps.append((f"choosing{i} = 0", None,
                      lambda s, me: s.update({f"choosing{i}": 0})))
        for j in range(N):
            if j == i:
                continue
            steps.append((f"wait until choosing{j} == 0",
                          lambda s, me, j=j: s[f"choosing{j}"] == 0, None))
            steps.append((f"wait until thread {j} is served after {i}",
                          lambda s, me, j=j: s[f"n{j}"] == 0
                          or (s[f"n{j}"], j) > (s[f"n{i}"], i), None))
        steps.append(("critical section", None, None))
        steps.append((f"number{i} = 0", None, lambda s, me: s.update({f"n{i}": 0})))
    return steps
```

*The bakery’s steps for [thread](#def-b2-threads-and-synchronisation-thread) $i$ code/bachelor-2/15-threads-and-synchronisation/listings/bakery_model.py*

```
$ python bakery_model.py
bakery, 3 threads, one pass each: 105181158026 schedules, 0 bad
bakery, 3 threads, two passes each: 6740295413970784199360021 schedules, 0 bad
bakery without choosing, 3 threads: 3401432126 schedules, 1288310155 bad
   e.g. A: start | A: read number0 | A: read number1 | A: read number2 | A: number0 =
        max + 1 | A: wait until thread 1 is served after 0 | A: wait until thread 2 is
        served after 0 | A: critical section | A: number0 = 0 | B: start | B: read
        number0 | B: read number1 | B: read number2 | C: start | C: read number0 | C:
        read number1 | C: read number2 | C: number2 = max + 1 | C: wait until thread 0
        is served after 2 | C: wait until thread 1 is served after 2 | B: number1 = max
        + 1 | B: wait until thread 0 is served after 1 | B: wait until thread 2 is
        served after 1
```

***Output 15.20.** [Mutual exclusion](#def-b2-threads-and-synchronisation-mutex-property) over every schedule; and its loss without `choosing`.*

The model reads the other tickets one at a time, as `locks.c` does, so a [thread](#def-b2-threads-and-synchronisation-thread) can read a ticket while another is changing. The explorer counts the schedules without listing them: they pass through the same states, and one pass of three [threads](#def-b2-threads-and-synchronisation-thread) has only 4579 states. With `choosing` removed it finds the violation: B and C read every ticket as 0; C writes ticket 1 and checks B, whose ticket is still 0, and enters; B then writes ticket 1 and checks C, whose ticket $(1, 2)$ comes after its own $(1, 1)$, and enters as well. `choosing` makes B’s check of C wait while C computes, and C’s check of B wait while B computes; the proof of [Theorem 15.10](#thm-b2-threads-and-synchronisation-bakery) uses it at exactly that point.

**Exercise 15.12 ★★★.**

Prove [Proposition 15.18](#prop-b2-threads-and-synchronisation-order). Then show that the philosophers’ circle is broken as soon as one philosopher takes the forks in the other order, whoever it is.

**Solution of Exercise 15.12.**

Suppose [threads](#def-b2-threads-and-synchronisation-thread) $T_1, \dots, T_m$ wait in a circle: $T_i$ waits for a [lock](#def-b2-threads-and-synchronisation-lock) $b_i$ held by $T_{i+1}$ (indices modulo $m$). Let $a_i$ be the largest [lock](#def-b2-threads-and-synchronisation-lock) $T_i$ holds. $T_i$ acquires in increasing order, so the [lock](#def-b2-threads-and-synchronisation-lock) it asks for is larger than every [lock](#def-b2-threads-and-synchronisation-lock) it holds: $a_i < b_i$. $T_{i+1}$ holds $b_i$, so $b_i \le a_{i+1}$. Then $a_1 < b_1 \le a_2 < b_2 \le \dots \le a_m < b_m \le a_1$, so $a_1 < a_1$: impossible.

For the philosophers, let philosopher $k$ alone take fork $k + 1$ first and fork $k$ second, the others taking fork $i$ then $i + 1$. Renumber the forks going round the table from fork $k + 1$: it gets label 0, fork $k + 2$ label 1, and so on to fork $k$, label 4. Every other philosopher $i$ then takes the fork labelled one less than the other one first, and philosopher $k$ takes label 0 before label 4: everyone acquires in increasing label order, and the proposition rules out a circle. Philosopher 4 of `philosophers_ordered.c` is the case $k = 4$, with the labels equal to the fork numbers.

## 15.7 Problem: The bus-ticket office with three windows

**Problem 15.1.**

Weekend problem — The bus-ticket office with three windows

A bus company sells seats from three windows that share one count of seats left. The problem follows the hook’s race from its cause to a protocol checked under every [interleaving](#def-b2-threads-and-synchronisation-interleaving), using `office_model.py`:

```python
def naive(customers):                             # check, then sell: three steps
    steps = []
    for _ in range(customers):
        steps += [("n = seats", None, lambda s, me: me.update(n=s["seats"])),
                  ("if n > 0: seats = n - 1", None,
                   lambda s, me: s.update(seats=me["n"] - 1) if me["n"] > 0 else None),
                  ("sell seat n", None, sell)]
    return steps


def locked(customers):                            # the same three steps under a lock
    steps = []
    for _ in range(customers):
        steps += [("lock", lambda s, me: s["lock"] == 0,
                   lambda s, me: s.update(lock=1))]
        steps += naive(1)
        steps += [("unlock", None, lambda s, me: s.update(lock=0))]
    return steps


def take(s, me):                                   # one indivisible step
    me["n"] = s["seats"]
    s["seats"] = max(s["seats"] - 1, 0)


def atomic(customers):
    steps = []
    for _ in range(customers):
        steps += [("n = take a seat", None, take), ("sell seat n", None, sell)]
    return steps

```

***Listing 15.19.** Three protocols for one customer’s purchase code/bachelor-2/15-threads-and-synchronisation/listings/office_model.py*

```
$ python office_model.py
check then sell, 1 seat, 1 customer per window: 20 schedules, 12 bad
   e.g. A: n = seats | B: n = seats | A: if n > 0: seats = n - 1 | A: sell seat n | B:
        if n > 0: seats = n - 1 | B: sell seat n
locked, 1 seat, 1 customer per window: 2 schedules, 0 bad
locked, 6 seats, 4 customers per window: 70 schedules, 0 bad
atomic take, 6 seats, 4 customers per window: 12870 schedules, 0 bad
```

***Output 15.17.** Every schedule of each protocol, for two windows.*

**Part I — The race.**

1. In [Listing 15.1](#lst-b2-threads-and-synchronisation-sell) , which lines form the check and which the sale? What does `pause_ms(50)` stand for?
2. Window B’s customer arrives 10 ms after A’s. Explain the output of [Output 15.1](#out-b2-threads-and-synchronisation-hook) step by step. Why is `seats_left` 0 and not $-1$ ?
3. What would the program print if B arrived 60 ms after A?
4. The model `naive` has 3 steps per customer. Check that two windows with one customer each have 20 schedules.
5. Of these 20, 12 sell seat 1 twice. Count the 8 good ones directly.
6. Why does ThreadSanitizer report the race even in a run that happens to sell the seat once?

**Part II — Locks.**

7. In `locked` , the [lock](#def-b2-threads-and-synchronisation-lock) step has a guard. What does it model, and why is it one step?
8. Explain why the locked version with one customer per window has only 2 schedules.
9. With 4 customers per window and 6 seats, it has 70 schedules: explain $\binom{8}{4}$ .
10. Rewrite `sell` of `last_seat.c` with a `pthread_mutex_t` . Which lines go inside?
11. With three windows, could Peterson’s [lock](#def-b2-threads-and-synchronisation-lock) be used? What would you use instead?
12. A clerk holds the [lock](#def-b2-threads-and-synchronisation-lock) while printing the ticket (50 ms). What does that cost three windows, and how would you shorten the [critical section](#def-b2-threads-and-synchronisation-mutex-property) ?

**Part III — A bounded queue.**

13. The customers now queue in a hall that holds 8 people; a door lets someone in only if there is room. Which [semaphore](#def-b2-threads-and-synchronisation-semaphore) is the door, and what is its initial value?
14. The three windows take customers from the hall. Which [semaphore](#def-b2-threads-and-synchronisation-semaphore) do they wait on?
15. Use [Proposition 15.14](#prop-b2-threads-and-synchronisation-semaphore) to show the hall never holds more than 8 people.
16. Why is a mutex still needed around the ring’s indices when two windows take at once?
17. A window must call two clerks’ supervisors, holding [lock](#def-b2-threads-and-synchronisation-lock) $a$ then $b$ , while another holds $b$ then $a$ . What can happen, and how does [Proposition 15.18](#prop-b2-threads-and-synchronisation-order) prevent it?
18. In `semaphores.c` , what would happen if `put` took the mutex before `sem_wait(&empty)` ?

**Part IV — Every interleaving checked.**

19. In the protocol `atomic` , the seat is taken by one indivisible step. Which C function would implement it?
20. Each window serves 4 customers in 2 steps each. Why does no guard reduce the number of schedules?
21. How many schedules are there, by [Proposition 15.3](#prop-b2-threads-and-synchronisation-interleavings) ?
22. What does the check `correct` require, and why is it enough for the company?
23. Why may the explorer remember a state’s result and reuse it? Does that change the count?
24. State the result of the last line of [Output 15.17](#out-b2-threads-and-synchronisation-office) .

**Solution of Problem 15.1.**

**1.** The check is `if (seats_left > 0)` with `int seat = seats_left`; the sale is `seats_left = seat - 1` and `w->sold = seat`. `pause_ms(50)` is the work between them, the clerk printing, which leaves time for the other [thread](#def-b2-threads-and-synchronisation-thread) to run.

**2.** A checks at 0 ms: 1 seat; it remembers `seat = 1` and pauses. B checks at 10 ms: `seats_left` is still 1; it remembers 1 and pauses. A, at 50 ms, writes $1 - 1 = 0$ and sells seat 1; B, at 60 ms, writes its own $1 - 1 = 0$ and sells seat 1. Each computes from the value it read, so the second write repeats the first instead of going below 0.

**3.** At 60 ms A has already written 0, so B’s check fails: A sells seat 1, B sells nothing (`sold = 0`), and 0 seats are left.

**4.** Two chains of 3 steps: $\binom{6}{3} = 20$.

**5.** A schedule is good when one window’s write comes before the other’s read. Then B finds 0 and sells nothing; that requires A’s read and decrement before B’s read, and A’s sale step can then be anywhere after its decrement: it interleaves with B’s 3 steps in 4 ways. So 4 good schedules with A first, 4 with B first: 8.

**6.** ThreadSanitizer records which accesses are ordered by synchronisation, not which happened to collide. A write and a read of `seats_left` from two [threads](#def-b2-threads-and-synchronisation-thread) with no [lock](#def-b2-threads-and-synchronisation-lock) or [atomic](#def-b2-threads-and-synchronisation-atomic) between them form a [data race](#def-b2-threads-and-synchronisation-data-race) in every run, and it reports it whether or not the outcome was wrong.

**7.** The guard `lock == 0` and the action `lock = 1` together model a mutex’s [lock](#def-b2-threads-and-synchronisation-lock): it tests and sets as one [atomic](#def-b2-threads-and-synchronisation-atomic) step, which is exactly what the naive flag [lock](#def-b2-threads-and-synchronisation-lock) could not do.

**8.** The whole purchase is inside the [lock](#def-b2-threads-and-synchronisation-lock), and nothing else happens outside it. The first window to [lock](#def-b2-threads-and-synchronisation-lock) runs its purchase entirely, the other waits; the two schedules are A then B and B then A.

**9.** Each customer’s purchase is a block that no other step can enter. The schedule is the order of the 8 blocks, 4 from each window, each window’s in its own order: $\binom{8}{4} = 70$.

**10.** [Lock](#def-b2-threads-and-synchronisation-lock) before `if (seats_left > 0)`, unlock after `seats_left = seat - 1`: the check, the decrement and the record go inside. B then waits until A’s sale is complete, finds 0 seats, and sells nothing.

**11.** Peterson’s algorithm is for two [threads](#def-b2-threads-and-synchronisation-thread). For three, the bakery would do; a system mutex, `pthread_mutex_t`, is simpler and does not spin.

**12.** The three windows sell one after another: 50 ms per sale, whatever the number of windows. Take the seat under the [lock](#def-b2-threads-and-synchronisation-lock), release it, and print the ticket outside: the [critical section](#def-b2-threads-and-synchronisation-mutex-property) shrinks to a few instructions.

**13.** A [semaphore](#def-b2-threads-and-synchronisation-semaphore) `room` starting at 8: entering is $P$, leaving the hall for a window is $V$.

**14.** On `waiting`, starting at 0: a person who enters does $V$, a window does $P$ before calling the next customer.

**15.** With produced = people who entered and consumed = people called to a window, the proposition gives $\text{produced} - \text{consumed} \le 8$: never more than 8 in the hall.

**16.** The [semaphores](#def-b2-threads-and-synchronisation-semaphore) count, but do not say which slot: two windows passing $P$ at once would both read `out` and take the same slot. The mutex makes reading and advancing the index one [critical section](#def-b2-threads-and-synchronisation-mutex-property).

**17.** A deadlock: the first holds $a$ and waits for $b$, the second holds $b$ and waits for $a$. With one global order, say $a$ before $b$, both take $a$ first; whoever gets it also gets $b$, and the circle cannot form.

**18.** With the ring full, a producer would hold the mutex while waiting for a free slot; consumers would need the mutex to free one; nobody moves: a deadlock. Wait on the [semaphore](#def-b2-threads-and-synchronisation-semaphore) first, then [lock](#def-b2-threads-and-synchronisation-lock).

**19.** `atomic_fetch_sub(&seats, 1)` returns the old value $n$ and decrements; the window sells seat $n$ if $n > 0$, else refuses. The counter may go below 0, which changes nothing, as the decisions depend only on $n$.

**20.** Neither step has a guard: no step ever waits, so every order of the 16 steps that keeps each window’s order is possible.

**21.** $\binom{16}{8} = 12\,870$.

**22.** That the seats sold are exactly $1, \dots, \min(6, 8) = 6$, each once: no seat sold twice, none invented, none left unsold while a customer was refused. Those are the company’s three failures.

**23.** The future of a state depends only on the state, the positions in each [thread](#def-b2-threads-and-synchronisation-thread) and the variables, not on the path that led there; so its counts are the same each time it is reached. Reusing them changes the time taken, not the counts: each schedule is still counted once, through the states it passes.

**24.** All $\binom{16}{8} = 12\,870$ [interleavings](#def-b2-threads-and-synchronisation-interleaving) checked: no violation.
