هذا الكتاب غير متوفر بعد باللغة العربية. النسخ المتوفرة: English.
University Computer Science — Year 2 · السنة الجامعية 2
15Threads 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:
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;
}
$ 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
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 is. This chapter runs several threads 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, condition variables and semaphores, in C, C++ and Rust.
You already know
Book 2: two processes sharing a resource can produce a race condition, a result that depends on the order of their steps; a critical section uses the shared data, mutual exclusion lets one process at a time be in it, and a lock provides it; a deadlock is a set of processes each waiting for a resource another holds, and needs four conditions (mutual exclusion, hold and wait, no preemption, circular wait). Chapter 13: a process has its own memory. Chapter 6: an exclusive borrow excludes every other borrow, so two threads cannot both change one value.
15.1 Threads
Definition 15.1 (Thread)
A thread is one sequence of execution inside a process: it has its own registers, program counter and stack, and shares with the other threads of the process everything else, its memory, its open files, its signal handlers. pthread_create(&t, NULL, f, arg) starts a thread that runs f(arg); pthread_join(t, NULL) waits for it to end.
Two processes made by fork share nothing they do not arrange to share; two threads share all their global variables and the heap. That is what makes threads fast to communicate, and what made seats_left a single variable seen by both windows. On a machine with several cores the threads run at the same time; on one core the scheduler switches between them. Either way, a thread’s steps follow each other in its own order, and the steps of different threads mix in an order that nobody chooses.
Definition 15.2 (Interleaving)
An interleaving (or schedule) of threads is one sequence of all their steps that keeps the steps of each thread in that thread’s order.
Proposition 15.3 (Number of interleavings)
Two threads of and steps that never wait have interleavings.
Proof. An interleaving is a sequence of positions. Choosing which positions hold the first thread’s steps determines it entirely, since each thread’s steps fill their positions in their own order; every choice gives an interleaving. There are choices. ∎
Two threads of 10 steps have interleavings; of 20 steps, about . 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 loads and stores, defined below, so that the compiler keeps them and the program stays defined), runs threads that each add 1 a million times, and compares:
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;
}
$ 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
Alone, the thread loses nothing. With two threads, nearly half the increments vanish: whenever the two threads overlap, each overwrites the other’s work. The precise numbers change from run to run; the losses do not go away.
Remark 15.4 (Race condition, between threads)
Book 2’s race condition, between processes, is the same bug between threads: 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, at least one is a write, at least one is not 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 can observe it half done: it takes effect as one indivisible step of every interleaving. atomic_fetch_add(&x, 1) reads, adds and writes as one step.
Our loads and stores are atomic one by one, so race.c has no data race; it still loses updates, because the three steps together are not atomic. The hook’s seats_left, a plain int, does have a 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
Such a tool reports only the races of the interleaving that ran. To see them all, we can explore. A model of a program lists each thread’s steps; interleavings.py runs every interleaving of them, recursively, and counts those that end badly. Two states that are the same (same position in every thread, same variables) have the same future, so the count of each is computed once and remembered:
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]
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 becomes two steps per thread:
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
$ 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
Two threads of 3 and 4 steps give 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; between threads they mean the same. A critical section is a part of a thread’s code that must not run while another thread runs a critical section on the same data, and critical sections are in mutual exclusion when at most one thread at a time is inside any of them.
Remark 15.8 (Lock, between threads)
Book 2’s lock, which provides mutual exclusion, is for threads an object called a mutex, with two operations around critical sections, lock and unlock: at most one thread at a time is between the lock it called and its unlock, and a thread that calls lock while another holds it waits.
The naive lock, a shared flag tested and then set, fails for the hook’s reason: both threads can test the flag before either sets it. The explorer finds 24 bad schedules among 42 (Output 15.4). 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:
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);
}
A 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 of the two threads (sequential consistency). Then (1) the two threads are never both in their critical sections; (2) a thread that waits enters before the other thread has entered twice more.
Proof. (1) Suppose both are in their critical sections at some moment. Each has written turn on its way in; say thread 0 wrote last, turn = 1, so turn is still 1 (a thread writes turn only on its way in). Look at thread 0’s last test of the wait condition, which came after its write of turn. Thread 1 had already set flag[1] before writing turn, which happened before thread 0’s write, and has not cleared it since, being in its critical section. So the test found flag[1] true and turn == 1, and thread 0 kept waiting: contradiction. The case where thread 1 wrote last is symmetric.
(2) Let thread 0 wait. If thread 1 is not trying to enter, flag[1] is false, and thread 0’s next test lets it in. Otherwise 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 0’s wait condition, flag[1] and turn == 1, is false, so thread 0 enters at its next test; and thread 1 waits, since flag[0] stays true and turn stays 0 until thread 0 has entered and left. ∎
turn. Whoever writes turn last waits, if the other also wants to enter.For threads, Lamport’s bakery algorithm works like the ticket machine at a counter: each thread takes a number larger than every number it sees, and the smallest number is served first; ties, possible because two threads can read the same numbers, go to the smaller thread index.
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 */
}
}
Theorem 15.10 (Bakery algorithm)
Under sequential consistency, no two threads are ever in their critical sections at once. Moreover, if thread finishes taking its ticket before thread starts taking its own, then enters its critical section before (first come, first served).
Proof. Write for the order of pairs: , or and . We show: if is in its critical section while holds a ticket , then . Two such threads would then each be before the other, which is impossible.
When passed its loop for , it first saw choosing[k] false at some moment , then read number[k]. If it read a ticket with , that ticket is still ’s unless has left and taken a new one since; a new ticket is taken after was written, so it is larger than . If it read 0, had no ticket at that read; since was not choosing at , its present ticket was taken by a choosing that began after , after wrote , so read and took a larger number. In every case .
For the second claim: starts choosing after is written, so it reads and takes ; while waits, ’s loop for 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)
counter++ under each lock: nothing is lost.choosing looks unnecessary, and is not: without it, a thread could read number[k] as 0 while is still computing its ticket, enter, and then be overtaken by ’s small ticket (Exercise 15.11). Both algorithms spin, testing in a loop, and both rely on sequential consistency, which real processors give only to atomic operations of the strongest ordering; the Year 3 volume explains the weaker orders. In practice one uses the system’s lock, pthread_mutex_t, or a single atomic instruction when the critical section is one operation:
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;
}
Both are exact (Output 15.2), and both cost time: the racy loop is fast because the threads do not cooperate. The mutex costs most, because a thread that finds it held is put to sleep by the kernel and woken later.
15.4 Waiting for a condition
A lock keeps threads apart. Often a thread must also wait for something another 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 holding a lock wait for a condition on the data the lock protects. pthread_cond_wait(&c, &m) releases m and puts the thread to sleep, in one step; when another 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 items shared by producer threads, which add items, and consumer threads, 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 slots.
static void put(long x)
{
pthread_mutex_lock(&m);
while (count == SLOTS) /* while, not if: see exercise 6 */
pthread_cond_wait(¬_full, &m); /* unlocks m, sleeps, relocks m */
ring[(head + count) % SLOTS] = x;
count++;
if (count > most)
most = count;
pthread_cond_signal(¬_empty);
pthread_mutex_unlock(&m);
}
static long take(void)
{
pthread_mutex_lock(&m);
while (count == 0)
pthread_cond_wait(¬_empty, &m);
long x = ring[head];
head = (head + 1) % SLOTS;
count--;
pthread_cond_signal(¬_full);
pthread_mutex_unlock(&m);
return x;
}
$ 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
The condition is tested in a while, not an if: between the signal and the moment the woken thread takes the lock again, another thread may have taken the item. The explorer finds such a schedule (Exercise 15.6).
Definition 15.13 (Semaphore)
A semaphore is a non-negative integer with two atomic operations: (sem_wait) waits until the value is positive and decreases it by 1; (sem_post) increases it by 1, waking a waiter if there is one. A semaphore that starts at counts available resources.
With two semaphores the ring needs no condition at all: empty counts the free slots and full the filled ones, and the mutex only protects the indices.
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;
}
$ 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
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, ; so no slot is overwritten before it is read, and none is read before it is written.
Proof. A semaphore’s value is its initial value plus its s minus its completed s, and is never negative. Each item read was preceded by a completed on full, and each on full follows an item written: . Each item written was preceded by a on empty, and each on empty follows an item read: . With the indices advancing modulo , the writer is never more than slots ahead of the reader, nor behind it. ∎
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 threads has one operation, wait, which returns in none of them until all have called it; it is then ready for the next round.
A barrier separates work that proceeds in rounds; pthread_barrier_wait returns a special value to exactly one of the threads:
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;
}
$ gcc -std=c17 -O2 -Wall -Wextra -o barrier barrier.c -lm && ./barrier
round 1: total 10
round 2: total 20
round 3: total 30
Definition 15.16 (Readers–writers lock)
A readers–writers lock can be held in two modes: by any number of threads at once for reading, or by one thread alone for writing, never both.
It can be built as a lock that counts readers. If readers keep arriving, a writer may wait forever.
Definition 15.17 (Starvation)
A thread starves when it waits forever for a resource that other threads keep obtaining, although the program as a whole goes on.
A writer-preferring lock stops admitting readers as soon as a writer waits (Exercise 15.9); it can then starve readers instead. 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 the program reports it instead of hanging:
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;
}
$ 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
Proposition 15.18 (Lock order)
If the locks are numbered and every thread that holds several locks acquired them in increasing order, no set of threads can be waiting for each other in a circle.
The proof is Exercise 15.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
History
Edsger Dijkstra’s notes Cooperating sequential processes, written in the mid-1960s, present Th. J. Dekker’s solution to mutual exclusion for two processes, the first correct one, and introduce the semaphore with its operations and . 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 beyond reading and writing a number. Gary Peterson’s two-thread algorithm, far shorter than Dekker’s, appeared in 1981 in a two-page note titled Myths about the mutual exclusion problem.
15.5 The same programs in C++ and Rust
C++ wraps the same objects in classes. A std::lock_guard locks in its constructor and unlocks in its destructor, so no path out of the block, return or exception, can keep the lock (Chapter 1):
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);
std::threads, a guarded counter and an 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
std::counting_semaphore gives the semaphore ring as a class template:
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;
}
$ g++ -std=c++20 -O2 -Wall -Wextra -o pc_cpp pc_cpp.cpp && ./pc_cpp
sum taken: 10000100000, sum put: 10000100000
BoundedQueue<long, 8>.C and C++ accept a data race and leave its behaviour undefined. Rust refuses it at compile time. A thread started by thread::spawn may outlive the function that started it, so it may not borrow that function’s variables:
fn main() {
let mut count = 0;
let t = thread::spawn(|| {
for _ in 0..1000 {
count += 1;
}
});
t.join().unwrap();
println!("{count}");
}
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
count. Some lines are left out.The compiler suggests move; for an i32, that would give the thread its own copy, and main would print 0, which is safe and not what we meant. Sharing a counter takes shared ownership, Arc, of a value that can be changed only through a lock, Mutex:
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());
}
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
The data is inside the mutex, so it cannot be reached without the lock; the guard returned by lock() unlocks when dropped. Rust also offers channels, queues between threads; a sync_channel(8) is the bounded buffer, and its receiving end sees the end of the stream when every sender has been dropped, like a pipe’s reader (Chapter 14):
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}");
}
$ rustc --edition 2021 -O -o channel_pc channel_pc.rs && ./channel_pc
sum received: 10000100000
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), servers with locks or with one atomic operation such as “decrement if positive”. The working rules are short: protect every shared variable by one lock, always the same; hold it briefly; acquire several locks in one global order; wait for conditions in a while; and prefer a language or a tool that finds data races for you.
15.6 Exercises
Exercise 15.1 ★
Two threads 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
Solution of Exercise 15.1.
Each thread has 4 steps, so there are schedules (Proposition 15.3). 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’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’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.
static int withdraw(long amount)
{
pthread_mutex_lock(&m);
if (amount > balance)
return 0; /* refused */
balance -= amount;
pthread_mutex_unlock(&m);
return 1;
}
$ 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]
Solution
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, which nothing will ever wake. (Locking a default mutex again from the 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 unlocks on every path (Exercise 15.3).
Exercise 15.3 ★
Write a C++ class SafeCounter with add(d), take(d) (subtract only if the counter holds at least , and say whether it did) and get(), safe to call from many threads, using std::lock_guard.
Solution
Solution of Exercise 15.3.
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.hppEach member takes the lock for its whole body, so take’s test and subtraction form one critical section: two threads cannot both see 5 and both take 5. The early return false unlocks through the guard’s destructor. The mutex is mutable so that the const member get can lock it. The test runs 8 threads, each adding 2 and taking 1 ten thousand times, and finds 80 000.
Exercise 15.4 ★
How many interleavings do two threads of 5 steps have? Three threads of 2 steps each? Generalise the proposition to threads of steps.
Solution
Solution of Exercise 15.4.
Two threads of 5 steps: . Three threads of 2 steps: choose the positions of the first thread’s steps, then of the second’s among those left: . In general, threads of steps have the multinomial number of interleavings: each arrangement of the positions among the threads is one interleaving, and there are orders of distinct steps, of which only one in keeps every thread in its order. The test checks .
Exercise 15.5 ★★
s and t are semaphores starting at 0. What can this program print? List every output.
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;
}
Solution
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)
Order the five prints. Thread one prints A, C, E in that order and 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 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 and a condition, and let the explorer find a schedule in which a consumer takes from an empty buffer.
Solution
Solution of Exercise 15.6.
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()]
$ 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
if lets a consumer take from an empty buffer; while never does.wait releases the lock and records the thread as waiting; a signal moves one waiter to the woken set; a woken thread must win the lock again. In the bad schedule C1 waits; the producer adds an item and signals, waking C1; but C2 takes the lock first and takes the item. C1 then gets the 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 does not own the 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 for threads from a mutex and a condition variable, barrier2_wait(b), that can be used again and again, and returns 1 to exactly one thread per use. Why is the test while (waiting < n) wrong?
Solution
Solution of Exercise 15.7.
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;
}
The last thread to arrive resets the count and increments round, then wakes everyone. A waiting thread waits for round to change, not for the count to reach . With while (waiting < n), the count is reset to 0 by the last arrival, so a woken thread that tests it finds it below 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 through 2000 rounds of two uses each, checks that nobody is ever a round ahead, and that exactly one thread per round is told it was last.
Exercise 15.8 ★★
Prove part (1) of Theorem 15.9 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.
Solution
Solution of Exercise 15.8.
The proof fails, and the algorithm too. With the entry turn = j; flag[i] = true: thread 0 writes turn = 1; thread 1 writes turn = 0, sets flag[1], and tests: flag[0] is still false, so thread 1 enters. Thread 0 sets flag[0] and tests: flag[1] is true but turn is 0, its own number, so thread 0 enters too. The proof used that the 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 with writer preference, RwLockW, with read_lock, read_unlock, write_lock and write_unlock, from a Mutex and a Condvar. Which threads can starve?
Solution
Solution of Exercise 15.9.
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();
}
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 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 waits until flag == 0, then sets flag = 1. Exhibit, by hand, a schedule in which both threads are in their critical sections; then explain why the explorer finds 24 bad schedules out of 42, by counting the schedules in which each thread passes its wait before the other sets the flag.
Solution
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. Counting the explorer’s schedules: if one thread sets the flag before the other has passed its wait, the other waits until the flag is cleared, so the threads run one after the other: 2 schedules. Otherwise both waits come first, in 2 orders, followed by any interleaving of the two remaining chains of 3 steps (set, critical section, clear): schedules, . Among the 20 interleavings of the two chains, the critical sections overlap unless one thread has already entered (run its critical-section step) before the other sets its flag: that is 4 interleavings for each thread finishing first, 8 in all, so overlap, and schedules are bad.
Exercise 15.11 ★★★
Model the bakery for three threads, reading the other tickets one at a time, and check mutual exclusion over every schedule, for one and for two passes per thread. Then remove choosing and find a violation.
Solution
Solution of Exercise 15.11.
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
$ 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
choosing.The model reads the other tickets one at a time, as locks.c does, so a 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 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 comes after its own , 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 uses it at exactly that point.
Exercise 15.12 ★★★
Prove Proposition 15.18. Then show that the philosophers’ circle is broken as soon as one philosopher takes the forks in the other order, whoever it is.
Solution
Solution of Exercise 15.12.
Suppose threads wait in a circle: waits for a lock held by (indices modulo ). Let be the largest lock holds. acquires in increasing order, so the lock it asks for is larger than every lock it holds: . holds , so . Then , so : impossible.
For the philosophers, let philosopher alone take fork first and fork second, the others taking fork then . Renumber the forks going round the table from fork : it gets label 0, fork label 1, and so on to fork , label 4. Every other philosopher then takes the fork labelled one less than the other one first, and philosopher 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 , 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, using office_model.py:
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
$ 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
Part I — The race.
- In Listing 15.1, which lines form the check and which the sale? What does
pause_ms(50)stand for? - Window B’s customer arrives 10 ms after A’s. Explain the output of Output 15.1 step by step. Why is
seats_left0 and not ? - What would the program print if B arrived 60 ms after A?
- The model
naivehas 3 steps per customer. Check that two windows with one customer each have 20 schedules. - Of these 20, 12 sell seat 1 twice. Count the 8 good ones directly.
- Why does ThreadSanitizer report the race even in a run that happens to sell the seat once?
Part II — Locks.
- In
locked, the lock step has a guard. What does it model, and why is it one step? - Explain why the locked version with one customer per window has only 2 schedules.
- With 4 customers per window and 6 seats, it has 70 schedules: explain .
- Rewrite
selloflast_seat.cwith apthread_mutex_t. Which lines go inside? - With three windows, could Peterson’s lock be used? What would you use instead?
- A clerk holds the lock while printing the ticket (50 ms). What does that cost three windows, and how would you shorten the critical section?
Part III — A bounded queue.
- The customers now queue in a hall that holds 8 people; a door lets someone in only if there is room. Which semaphore is the door, and what is its initial value?
- The three windows take customers from the hall. Which semaphore do they wait on?
- Use Proposition 15.14 to show the hall never holds more than 8 people.
- Why is a mutex still needed around the ring’s indices when two windows take at once?
- A window must call two clerks’ supervisors, holding lock then , while another holds then . What can happen, and how does Proposition 15.18 prevent it?
- In
semaphores.c, what would happen ifputtook the mutex beforesem_wait(&empty)?
Part IV — Every interleaving checked.
- In the protocol
atomic, the seat is taken by one indivisible step. Which C function would implement it? - Each window serves 4 customers in 2 steps each. Why does no guard reduce the number of schedules?
- How many schedules are there, by Proposition 15.3?
- What does the check
correctrequire, and why is it enough for the company? - Why may the explorer remember a state’s result and reuse it? Does that change the count?
- State the result of the last line of Output 15.17.
Solution
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 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 and sells seat 1; B, at 60 ms, writes its own 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: .
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 with no lock or atomic between them form a 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: it tests and sets as one atomic step, which is exactly what the naive flag lock could not do.
8. The whole purchase is inside the lock, and nothing else happens outside it. The first window to 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: .
10. 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. 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, release it, and print the ticket outside: the critical section shrinks to a few instructions.
13. A semaphore room starting at 8: entering is , leaving the hall for a window is .
14. On waiting, starting at 0: a person who enters does , a window does before calling the next customer.
15. With produced = people who entered and consumed = people called to a window, the proposition gives : never more than 8 in the hall.
16. The semaphores count, but do not say which slot: two windows passing at once would both read out and take the same slot. The mutex makes reading and advancing the index one critical section.
17. A deadlock: the first holds and waits for , the second holds and waits for . With one global order, say before , both take first; whoever gets it also gets , 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 first, then lock.
19. atomic_fetch_sub(&seats, 1) returns the old value and decrements; the window sells seat if , else refuses. The counter may go below 0, which changes nothing, as the decisions depend only on .
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. .
22. That the seats sold are exactly , 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 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 interleavings checked: no violation.