Notes
All notes

Concurrency and Synchronization (OS Core #4)

Threads share memory, so two of them can read and write the same variable at the same time. When that happens, the result depends on timing, and timing is not something a program can rely on. Synchronization is the set of tools that turn “depends on timing” back into “has one defined answer”.

Race conditions

A data race is two accesses to the same memory, at least one of them a write, with no ordering between them. In C++ that is undefined behaviour, not just a wrong value.

#include <thread>
#include <cstdio>

int counter = 0;                       // shared

void bump() {
    for (int i = 0; i < 100000; ++i) ++counter;   // read-modify-write
}

int main() {
    std::thread a(bump), b(bump);
    a.join(); b.join();
    std::printf("%d\n", counter);      // often less than 200000
}

++counter is three steps: load, add, store. Two threads can load the same value before either stores, so one increment is lost. The final number is whatever the interleaving produced.

A race condition is broader: a bug where correctness depends on timing. A data race is one cause; check-then-act (TOCTOU) is another:

if (!file_exists(path)) {          // another process may create it here
    create_file(path);             // fails or overwrites
}

The fix is to make the check and the action atomic, not to add a delay.

QQuestionIs a data race the same as a race condition?
ASolution

No. A data race is a specific, defined term (conflicting unsynchronized accesses). A race condition is any timing-dependent correctness bug, which may involve no shared memory at all (for example two processes and a file).

Critical sections and mutual exclusion

A critical section is the part of the code that touches shared state. The requirements for a correct solution:

  1. Mutual exclusion: at most one thread inside the critical section.
  2. Progress: if the section is free and someone wants in, one of them gets in. No thread outside the section may block others.
  3. Bounded waiting: a thread cannot be overtaken forever; there is a bound on how long it waits.

These three are the checklist for evaluating any lock algorithm. Peterson’s algorithm satisfies all three for two threads using only loads and stores; real hardware uses atomic instructions because compilers and CPUs reorder plain accesses.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=2.6cm, minimum height=0.6cm, font=\scriptsize},
  a/.style={->, thick}]
  \node[b, fill=gray!8] (e) at (0,1.4) {entry protocol};
  \node[b, fill=red!15] (c) at (0,0.5) {critical section};
  \node[b, fill=gray!8] (x) at (0,-0.4) {exit protocol};
  \node[b, fill=green!18] (r) at (3.4,0.5) {remainder};
  \draw[a] (e) -- (c); \draw[a] (c) -- (x);
  \draw[a] (x) -- (0,-1.2) -- (3.4,-1.2) -- (r);
  \draw[a] (r) |- (e);
  \node[font=\scriptsize, anchor=west] at (1.9,0.5) {only one thread};
  \node[font=\scriptsize, anchor=west] at (1.9,1.4) {acquire};
  \node[font=\scriptsize, anchor=west] at (1.9,-0.4) {release};
\end{tikzpicture}
QQuestionWhich requirement does a simple “if (busy) wait;” loop violate?
ASolution

Progress and bounded waiting, depending on the implementation: threads can all see the lock free and race in, or a thread can lose the race forever.

Atomic operations

An atomic operation completes as a single indivisible step. Hardware provides two primitives that make locks possible:

#include <atomic>

std::atomic<int> counter{0};

void bump() {
    for (int i = 0; i < 100000; ++i)
        counter.fetch_add(1, std::memory_order_relaxed);   // atomic RMW
}

fetch_add compiles to a locked instruction (lock xadd on x86), which is a full memory barrier in practice. Atomic operations are not free: a contended atomic increment costs tens of nanoseconds and serializes the cache line between cores.

An atomic counter is enough for statistics. It is not enough for a data structure: “check then update” over several variables needs a lock or a carefully designed lock-free algorithm.

QQuestionWhy does std::atomic<int> fix the lost-update bug?
ASolution

The increment becomes one indivisible read-modify-write. Two increments cannot both read the same old value; one sees the other’s result.

Mutexes and spinlocks

A mutex is a sleeping lock. A thread that cannot acquire it blocks, and the scheduler runs something else. A spinlock busy-waits until the lock is free.

#include <mutex>
std::mutex m;

void safe_increment(int& x) {
    std::lock_guard<std::mutex> lock(m);   // acquire
    ++x;
}                                          // release

A spinlock is a few lines with an atomic flag:

class Spinlock {
    std::atomic_flag flag = ATOMIC_FLAG_INIT;
public:
    void lock() {
        while (flag.test_and_set(std::memory_order_acquire)) {
            // spin; optionally pause/yield
        }
    }
    void unlock() { flag.clear(std::memory_order_release); }
};
Mutex Spinlock
Waiting sleeps (syscall) burns CPU
Best for long or contended sections very short sections, no contention
Cost when free ~20 ns ~10 ns
Cost when contended context switch, µs wasted CPU, worse under oversubscription

A spinlock on a single-core machine is dangerous: if the holder is preempted, the spinner wastes its whole quantum. Spinlocks are for kernel code that disables preemption, or for very short sections on multicore.

Real mutexes are hybrid: spin briefly, then sleep (futex on Linux). That gives the best of both for typical workloads.

QQuestionWhen is a spinlock a bad choice in user-space code?
ASolution

When the critical section can be long or the lock is heavily contended. The spinner burns a core that could run the lock holder, and with more threads than cores it can livelock the system.

Semaphores

A semaphore is an integer with two atomic operations: wait (P, decrement, block if negative) and post (V, increment, wake a waiter).

#include <semaphore.h>
sem_t slots;
sem_init(&slots, 0, 4);      // four permits, shared between threads

sem_wait(&slots);            // acquire a permit (may block)
// ... use one of four resources ...
sem_post(&slots);            // release

C++20 has std::counting_semaphore and std::binary_semaphore; before that, use POSIX sem_t or build one from a mutex and a condition variable.

The difference from a mutex: a semaphore has no owner. Any thread may post it, which is useful for signalling (“data is ready”) and wrong for protecting data (where the releaser should be the holder).

QQuestionCan a semaphore replace a mutex?
ASolution

For mutual exclusion, a binary semaphore works if every waiter posts exactly once. But because it has no owner, a buggy thread can release a lock it never acquired, and priority inheritance does not apply. Use a mutex for locking.

Condition variables

A condition variable lets a thread sleep until a predicate becomes true. It is always used with a mutex, because the predicate is shared state.

#include <condition_variable>
#include <mutex>

std::mutex m;
std::condition_variable cv;
bool ready = false;

void waiter() {
    std::unique_lock<std::mutex> lock(m);
    cv.wait(lock, [] { return ready; });   // releases m while asleep
    // predicate true, m held again
}

void signaller() {
    {
        std::lock_guard<std::mutex> lock(m);
        ready = true;
    }
    cv.notify_one();
}

Three rules:

  1. Always wait in a loop or with a predicate. Wakeups can be spurious.
  2. Change the predicate while holding the mutex. Otherwise a wakeup can be lost between the check and the sleep.
  3. Notify after the state change. Notifying while holding the lock is correct but can cause the woken thread to block immediately (the “hurry up and wait” problem).
QQuestionWhy must wait take the mutex?
ASolution

It must atomically release the mutex and go to sleep. Otherwise a notifier could change the predicate and signal in the gap, and the waiter would sleep forever.

Monitors

A monitor is a higher-level construct: a object whose methods are mutually exclusive by default, with condition variables for waiting. Java’s synchronized methods and blocks are monitors; C++ has no built-in monitor, but a class that locks a mutex in every public method is the same idea.

class Counter {
    mutable std::mutex m;
    int value = 0;
public:
    void increment() {
        std::lock_guard<std::mutex> lock(m);
        ++value;
    }
    int get() const {
        std::lock_guard<std::mutex> lock(m);
        return value;
    }
};

Monitors make the invariant explicit: the mutex protects the fields, and every method that touches them takes it. The failure mode is a method that forgets.

QQuestionWhat does a monitor add over a raw mutex?
ASolution

Encapsulation and a guarantee that every operation on the state is protected. The locking is tied to the object rather than scattered through call sites.

Producer-consumer

A bounded buffer with one producer and one consumer. The producer waits when the buffer is full, the consumer waits when it is empty.

#include <condition_variable>
#include <mutex>
#include <queue>

std::mutex m;
std::condition_variable not_full, not_empty;
std::queue<int> q;
constexpr size_t CAP = 8;

void produce(int x) {
    std::unique_lock<std::mutex> lock(m);
    not_full.wait(lock, [] { return q.size() < CAP; });
    q.push(x);
    lock.unlock();
    not_empty.notify_one();
}

int consume() {
    std::unique_lock<std::mutex> lock(m);
    not_empty.wait(lock, [] { return !q.empty(); });
    int x = q.front();
    q.pop();
    lock.unlock();
    not_full.notify_one();
    return x;
}

Two condition variables, not one. With one, a producer could wake another producer (which finds the buffer full and goes back to sleep) while a consumer stays asleep.

Variants: multiple producers/consumers (same code, notify_one still works), a lock-free ring buffer (harder, needs atomics and memory ordering), and a semaphore-based version (two counting semaphores plus a mutex).

QQuestionWhy is if (q.size() < CAP) wait(...) wrong?
ASolution

A spurious wakeup, or a wakeup for a different reason, leaves the predicate false. The loop in wait(lock, pred) rechecks and sleeps again; a single if would proceed with a full buffer.

Readers-writers

Many readers can read at once; writers need exclusive access. The interesting part is the policy:

C++17 gives a reader-writer lock:

#include <shared_mutex>
std::shared_mutex rw;

void reader() {
    std::shared_lock lock(rw);      // many readers concurrently
    read_data();
}

void writer() {
    std::unique_lock lock(rw);      // exclusive
    write_data();
}

Implementation detail: std::shared_mutex is typically writer-preferring on Linux, because reader-preference causes writer starvation in real workloads.

QQuestionWhy can reader preference starve a writer?
ASolution

As long as at least one reader is active, new readers are admitted. A continuous stream of readers means the writer never sees zero readers and never runs.

Dining philosophers

Five philosophers sit around a table with five forks. Each needs both adjacent forks to eat. Acquiring left then right, everyone at once:

std::mutex fork[5];

void philosopher(int i) {
    std::lock_guard<std::mutex> left(fork[i]);
    std::lock_guard<std::mutex> right(fork[(i + 1) % 5]);   // deadlock
    eat();
}

Every philosopher holds the left fork and waits for the right one: circular wait, so deadlock. Three standard fixes:

  1. Global ordering: always acquire the lower-numbered fork first. Breaks the cycle.
  2. Arbitrator: a waiter (mutex) allows at most four philosophers to try at once. Breaks the “all hold one” condition.
  3. Chandy-Misra: forks get dirty/clean states and are passed on request; no central arbiter.

C++17’s std::scoped_lock takes multiple locks and uses a deadlock-avoidance algorithm internally:

void philosopher(int i) {
    std::scoped_lock lock(fork[i], fork[(i + 1) % 5]);   // no deadlock
    eat();
}
QQuestionWhich Coffman condition does the global-ordering fix break?
ASolution

Circular wait. If every philosopher acquires forks in increasing index order, the cycle around the table cannot form.

Deadlocks

A deadlock is a set of threads each waiting for a resource held by another. Four conditions must all hold:

  1. Mutual exclusion: resources are not shareable.
  2. Hold and wait: a thread holds one resource and waits for another.
  3. No preemption: resources cannot be taken away.
  4. Circular wait: a cycle of holders and waiters.

Break any one and deadlock is impossible. The strategies:

Strategy Idea Cost
Prevention break one condition structurally restricts usage, low utilisation
Avoidance grant only if the state stays safe (Banker’s) needs maximum demands in advance
Detection find cycles, then recover runtime cost, may kill work
Ignorance reboot (most general-purpose OSes) cheap, rare failures

Banker’s algorithm is the classic avoidance scheme. Each process declares its maximum demand. A state is safe if there is an order in which all processes can finish. Example with resources A = 10, B = 5, C = 7 and five processes:

Process Allocation Max Need
P0 0 1 0 7 5 3 7 4 3
P1 2 0 0 3 2 2 1 2 2
P2 3 0 2 9 0 2 6 0 0
P3 2 1 1 2 2 2 0 1 1
P4 0 0 2 4 3 3 4 3 1

Available = (3, 3, 2). The safe sequence P1, P3, P4, P0, P2 works: P1 needs (1,2,2) ≤ (3,3,2), finishes and returns (5,3,2); P3 needs (0,1,1), returns (7,4,3); P4 needs (4,3,1), returns (7,4,5); P0 needs (7,4,3), returns (7,5,5); P2 needs (6,0,0), finishes. Every step stayed within available resources, so the state is safe. If a request would leave no safe sequence, it is denied (or the requester waits).

Detection is simpler: build a wait-for graph and look for a cycle. Recovery means killing a process or rolling it back. Most systems choose “ignore and reboot”.

QQuestionWhy is Banker’s algorithm rarely used in real systems?
ASolution

It requires every process to declare its maximum resource needs in advance, and processes do not know them. It also assumes resources are fixed and independent, which is false for I/O and memory-mapped devices.

QQuestionA deadlock needs all four conditions. Which one does a timeout break?
ASolution

No preemption, in effect: the system takes the resource back (by rolling back or killing the waiter) after a timeout. It is detection and recovery, not prevention.

Starvation and fairness

Starvation is indefinite postponement: a thread is runnable but never chosen. It is not a deadlock, because the system as a whole makes progress.

Livelock is different again: threads keep changing state in response to each other and make no progress (two people stepping aside in a corridor).

Priority inversion is the nasty one. A low-priority thread holds a lock; a high-priority thread needs it; a medium-priority thread preempts the low one. The high-priority thread is now effectively waiting behind the medium one.

The fix is priority inheritance: while the low thread holds the lock, it runs at the high thread’s priority. Priority ceiling is an alternative: the lock has a ceiling priority, and the holder runs at least that high.

This is not theoretical. The Mars Pathfinder mission in 1997 kept resetting because of priority inversion between an information bus task, a communications task, and a weather task; the fix was enabling priority inheritance in VxWorks.

QQuestionWhy does priority inheritance not solve all priority problems?
ASolution

It only applies while a lock is held, and only to direct holders. Chains of dependencies need transitive inheritance, and it does not fix unbounded waiting for non-lock resources.

Memory ordering and happens-before

On a modern CPU, stores are buffered and loads can be reordered. Two threads without synchronization can observe each other’s writes in different orders. The C++ memory model defines what is allowed through happens-before:

If A happens-before B, B sees every effect of A. A data race is two conflicting accesses with no happens-before between them; that is undefined behaviour.

std::atomic<bool> ready{false};
int data = 0;

// producer
data = 42;
ready.store(true, std::memory_order_release);

// consumer
if (ready.load(std::memory_order_acquire)) {
    assert(data == 42);     // guaranteed by the release/acquire pair
}

The memory orders, weakest to strongest:

Order Meaning Use
relaxed atomicity only, no ordering counters, statistics
acquire / release one-way barrier around a variable publish data, flags
acq_rel both on read-modify-write locks, refcounts
seq_cst total order across all threads default, easiest to reason about

A mutex lock/unlock is an acquire/release pair, which is why everything written inside a critical section is visible to the next thread that locks it.

volatile is not a synchronization tool in C++. It prevents some compiler optimisations for memory-mapped I/O and signal handlers; it does not provide atomicity or inter-thread ordering. std::atomic does.

QQuestionDoes x86 need acquire/release fences?
ASolution

x86 has a strong memory model (TSO): loads are not reordered with loads, stores not with stores, and stores are not reordered with later loads. But store-load reordering still exists, and the compiler can reorder regardless of the CPU. Still write acquire/release for portability and for the compiler.

Bugs and edge cases

QQuestionA program deadlocks only under load. What do you check first?
ASolution

Lock ordering and lock hold times. Under load, more threads contend, and a two-lock inversion that rarely interleaves at low load becomes reliable. Take a stack dump of all threads (gdb -p, pstack) and look for a cycle.

Next: Memory Management (OS Core #5) — page tables, page faults, and why a TLB miss is not a page fault.