Lesson 4 · Synchronization and deadlocks

Test-and-Set and Spinlocks

Software locks like Peterson's break on modern CPUs. Hardware fixes it with one indivisible read-and-write, and a spinlock is the simplest lock you can build from it.

Test-and-Set and Spinlocks concept diagramLeft: a CPU writes 1 to the lock word and gets the old value back in one atomic step; below, two CPUs that read and write separately both read 0 and both enter. Right: the spinlock loop, which repeats test-and-set while it returns 1, then runs the critical section and stores 0.test_and_set(&lock): one indivisible stepCPUlock wordwrite 1old valueno other CPU can touch the word in betweenif the read and write were separateCPU ACPU Bread 0write 1read 0write 1timeboth read 0, so both enter the critical sectionspinlock acquire and releaseold = test_and_set(&lock)old == 1 ?yes: spinno: lock was freecritical sectionlock = 0 (release)waiting = busy looping on the CPU
1

One Indivisible Read and Write

  1. Read the current value of the lock word.
  2. Write 1 to the lock word, whatever it held.
  3. Return the value that was read.
  4. All three happen atomically – no other processor can read or write the word in between.

A lock needs a thread to check that the lock is free and claim it, with nothing slipping in between. In plain code that is two operations, a read and then a write, and two CPUs can both read 0 before either writes 1. Both then enter the critical section. Software fixes such as Peterson's solution avoid this with careful ordering, but modern processors and compilers reorder memory operations, so those algorithms are not reliable on real hardware without memory barriers.

The hardware answer is an atomic instruction: one instruction that reads and writes a memory word as a single indivisible step. The test-and-set instruction (TAS) is the simplest. It returns the old value of a boolean word and sets the word to true (1), in one operation that no other CPU can interleave with. If two CPUs execute it at the same moment, the hardware serialises them: one reads 0, the other reads 1.

Its behaviour, written as a function, is bool test_and_set(bool *target) { bool old = *target; *target = true; return old; } — except that the whole body executes atomically. On x86 the equivalent is XCHG (or LOCK BTS); C++ exposes it as std::atomic_flag::test_and_set and Java as AtomicBoolean.getAndSet(true).

  • Atomic is not the same as fast: a TAS must lock the cache line or the bus, so it costs far more than a plain store
  • Calling TAS when the lock is already held changes nothing, since 1 is written over 1
2

Building a Spinlock

  1. Acquire – while (test_and_set(&lock)) spins until TAS returns 0.
  2. Critical section – exactly one CPU is here at a time.
  3. Release – lock = false lets the next TAS succeed.
  4. Remainder section – the CPU does other work, then may try again.

A spinlock is a lock where a waiting thread keeps retrying in a tight loop instead of going to sleep. With test-and-set it is three lines. Acquire: while (test_and_set(&lock)) ; — keep executing TAS until it returns 0. Critical section. Release: lock = false; — a plain store (with release ordering) is enough, because only the owner ever writes 0.

Why it gives mutual exclusion: the lock word starts at 0. The first TAS to reach it reads 0 and writes 1. Every later TAS reads 1 until the owner stores 0, and the next TAS after that is again the only one to read 0. Because TAS is atomic, two CPUs can never both read 0 for the same release.

The waiting loop is called busy waiting or spinning: the CPU executes instructions the whole time it waits, doing no useful work.

  • Pitfall: releasing with a plain non-atomic store and no release ordering lets the compiler or CPU move critical-section writes after the release
  • Pitfall: a thread that tries to take a spinlock it already holds spins forever; spinlocks are not re-entrant
3

Compare-and-Swap and Other Atomic Instructions

Compare-and-swap (CAS) is the more general instruction: compare_and_swap(&value, expected, new) writes new only if the word still equals expected, and returns the old value either way. A spinlock with CAS is while (compare_and_swap(&lock, 0, 1) != 0) ;. CAS is what lock-free data structures are built on, because it can update a word conditionally, for example pushing onto a stack only if the top pointer has not changed since it was read. On x86 it is LOCK CMPXCHG.

Every modern CPU provides at least one such primitive. They differ in how much they can do in one step, but any of them can build a lock.

Atomic hardware primitives
InstructionWhat it does atomicallyTypical use
Test-and-setreturn old value, set word to 1simplest spinlock
Exchange (swap)swap a register with a memory wordspinlock (x86 XCHG)
Compare-and-swapwrite new only if the word equals expectedspinlocks, lock-free stacks and queues
Fetch-and-addadd to a word, return the old valuecounters, ticket locks
Load-linked / store-conditionalstore succeeds only if nobody wrote since the loadARM, RISC-V, POWER equivalent of CAS
  • The ABA problem: CAS only checks the value, so a word that changed from A to B and back to A looks untouched
  • LL/SC avoids ABA because any write to the word, even of the same value, makes the store fail
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Atomic instructionA read-modify-write that no other processor can interleave with.
  • Test-and-setReturn a word's old value and set it to 1, atomically.
  • SpinlockA lock whose waiters loop until it is free instead of sleeping.
  • Busy waitingExecuting a loop while waiting; the CPU does no useful work.
  • StarvationA waiting thread that loses every race and never gets the lock.

Mechanisms

  • TAS spinlockwhile (test_and_set(&lock)) ; … critical section … lock = false;
  • CAS spinlockwhile (compare_and_swap(&lock, 0, 1) != 0) ;
  • Bounded-waiting TASwaiting[i] = true; spin while waiting[i] && TAS; release hands off to the next waiting[j].
  • TTASSpin on a plain read; try TAS only when the lock looks free.
  • Ticket lockmy = fetch_and_add(&next, 1); spin until now_serving == my.
Implementation

Test-and-set: starvation, then bounded waiting

CPUS = ["A", "B", "C"]
# Which CPU gets the memory bus on each tick. Fixed so the run is repeatable.
SCHEDULE = "ABCAABCABBACBAABCC"


class Lock:
    def __init__(self):
        self.word = 0

    def test_and_set(self):
        # On hardware this read-and-write is one atomic instruction.
        old = self.word
        self.word = 1
        return old


def simulate(bounded):
    lock = Lock()
    waiting = {c: False for c in CPUS}
    phase = {c: "want" for c in CPUS}
    fails = {c: 0 for c in CPUS}
    entries = []
    for t, cpu in enumerate(SCHEDULE, start=1):
        if phase[cpu] in ("want", "spin"):
            first = phase[cpu] == "want"
            if bounded and not first and not waiting[cpu]:
                phase[cpu] = "cs"
                entries.append((cpu, t))
                text = f"waiting[{cpu}] = 0 -> handed the lock, enters"
            else:
                prefix = ""
                if bounded and first:
                    waiting[cpu] = True
                    prefix = f"waiting[{cpu}] = 1, "
                if lock.test_and_set() == 0:
                    waiting[cpu] = False
                    phase[cpu] = "cs"
                    entries.append((cpu, t))
                    text = prefix + "TAS read 0 -> acquired"
                else:
                    phase[cpu] = "spin"
                    fails[cpu] += 1
                    text = prefix + "TAS read 1 -> spin"
        elif phase[cpu] == "cs":
            phase[cpu] = "exit"
            text = "critical section"
        else:
            phase[cpu] = "want"
            i = CPUS.index(cpu)
            later = [CPUS[(i + d) % 3] for d in (1, 2)]
            nxt = next((c for c in later if waiting[c]), None)
            if bounded and nxt:
                waiting[nxt] = False  # hand off: the lock word stays 1
                text = f"release, hand off to {nxt} (lock stays 1)"
            else:
                lock.word = 0
                text = "release, lock = 0"
        print(f"t={t:<2} {cpu}: {text}")
    order = " ".join(f"{c}@{t}" for c, t in entries)
    print(f"entries: {order}")
    print("failed TAS: " + ", ".join(f"{c}={fails[c]}" for c in CPUS))


print("== plain test-and-set spinlock ==")
simulate(False)
print()
print("== bounded-waiting test-and-set ==")
simulate(True)
#include <atomic>
#include <iostream>
#include <map>
#include <string>
#include <utility>
#include <vector>

const std::string CPUS = "ABC";
// Which CPU gets the memory bus on each tick. Fixed so the run is repeatable.
const std::string SCHEDULE = "ABCAABCABBACBAABCC";

void simulate(bool bounded) {
    // A real atomic: exchange(1) is test-and-set (XCHG on x86).
    std::atomic<int> lock{0};
    std::map<char, bool> waiting{{'A', false}, {'B', false}, {'C', false}};
    std::map<char, std::string> phase{{'A', "want"}, {'B', "want"}, {'C', "want"}};
    std::map<char, int> fails{{'A', 0}, {'B', 0}, {'C', 0}};
    std::vector<std::pair<char, int>> entries;

    for (int t = 1; t <= (int)SCHEDULE.size(); t++) {
        char cpu = SCHEDULE[t - 1];
        std::string text;
        if (phase[cpu] == "want" || phase[cpu] == "spin") {
            bool first = phase[cpu] == "want";
            if (bounded && !first && !waiting[cpu]) {
                phase[cpu] = "cs";
                entries.push_back({cpu, t});
                text = std::string("waiting[") + cpu + "] = 0 -> handed the lock, enters";
            } else {
                std::string prefix;
                if (bounded && first) {
                    waiting[cpu] = true;
                    prefix = std::string("waiting[") + cpu + "] = 1, ";
                }
                if (lock.exchange(1) == 0) {
                    waiting[cpu] = false;
                    phase[cpu] = "cs";
                    entries.push_back({cpu, t});
                    text = prefix + "TAS read 0 -> acquired";
                } else {
                    phase[cpu] = "spin";
                    fails[cpu]++;
                    text = prefix + "TAS read 1 -> spin";
                }
            }
        } else if (phase[cpu] == "cs") {
            phase[cpu] = "exit";
            text = "critical section";
        } else {
            phase[cpu] = "want";
            int i = CPUS.find(cpu);
            char next = 0;
            for (int d = 1; d <= 2 && !next; d++) {
                if (waiting[CPUS[(i + d) % 3]]) next = CPUS[(i + d) % 3];
            }
            if (bounded && next) {
                waiting[next] = false; // hand off: the lock word stays 1
                text = std::string("release, hand off to ") + next + " (lock stays 1)";
            } else {
                lock.store(0);
                text = "release, lock = 0";
            }
        }
        std::string ts = std::to_string(t);
        std::cout << "t=" << ts << std::string(3 - ts.size(), ' ') << cpu << ": " << text << "\n";
    }
    std::cout << "entries:";
    for (auto [c, t] : entries) std::cout << " " << c << "@" << t;
    std::cout << "\nfailed TAS: A=" << fails['A'] << ", B=" << fails['B'] << ", C=" << fails['C'] << "\n";
}

int main() {
    std::cout << "== plain test-and-set spinlock ==\n";
    simulate(false);
    std::cout << "\n== bounded-waiting test-and-set ==\n";
    simulate(true);
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    static final String CPUS = "ABC";
    // Which CPU gets the memory bus on each tick. Fixed so the run is repeatable.
    static final String SCHEDULE = "ABCAABCABBACBAABCC";

    static void simulate(boolean bounded) {
        // A real atomic: getAndSet(true) is test-and-set.
        AtomicBoolean lock = new AtomicBoolean(false);
        Map<Character, Boolean> waiting = new HashMap<>();
        Map<Character, String> phase = new HashMap<>();
        Map<Character, Integer> fails = new HashMap<>();
        for (char c : CPUS.toCharArray()) {
            waiting.put(c, false);
            phase.put(c, "want");
            fails.put(c, 0);
        }
        List<String> entries = new ArrayList<>();

        for (int t = 1; t <= SCHEDULE.length(); t++) {
            char cpu = SCHEDULE.charAt(t - 1);
            String text;
            String p = phase.get(cpu);
            if (p.equals("want") || p.equals("spin")) {
                boolean first = p.equals("want");
                if (bounded && !first && !waiting.get(cpu)) {
                    phase.put(cpu, "cs");
                    entries.add(cpu + "@" + t);
                    text = "waiting[" + cpu + "] = 0 -> handed the lock, enters";
                } else {
                    String prefix = "";
                    if (bounded && first) {
                        waiting.put(cpu, true);
                        prefix = "waiting[" + cpu + "] = 1, ";
                    }
                    if (!lock.getAndSet(true)) {
                        waiting.put(cpu, false);
                        phase.put(cpu, "cs");
                        entries.add(cpu + "@" + t);
                        text = prefix + "TAS read 0 -> acquired";
                    } else {
                        phase.put(cpu, "spin");
                        fails.merge(cpu, 1, Integer::sum);
                        text = prefix + "TAS read 1 -> spin";
                    }
                }
            } else if (p.equals("cs")) {
                phase.put(cpu, "exit");
                text = "critical section";
            } else {
                phase.put(cpu, "want");
                int i = CPUS.indexOf(cpu);
                char next = 0;
                for (int d = 1; d <= 2 && next == 0; d++) {
                    char c = CPUS.charAt((i + d) % 3);
                    if (waiting.get(c)) next = c;
                }
                if (bounded && next != 0) {
                    waiting.put(next, false); // hand off: the lock word stays 1
                    text = "release, hand off to " + next + " (lock stays 1)";
                } else {
                    lock.set(false);
                    text = "release, lock = 0";
                }
            }
            System.out.printf("t=%-2d %c: %s%n", t, cpu, text);
        }
        System.out.println("entries: " + String.join(" ", entries));
        System.out.printf("failed TAS: A=%d, B=%d, C=%d%n", fails.get('A'), fails.get('B'), fails.get('C'));
    }

    public static void main(String[] args) {
        System.out.println("== plain test-and-set spinlock ==");
        simulate(false);
        System.out.println();
        System.out.println("== bounded-waiting test-and-set ==");
        simulate(true);
    }
}
Watch it run

Step through it

Running on CPUs A, B, C; bus order ABCAABCABBACBAABCC; critical section = 1 tick

shared memorylock0 (free)CPU Awants the lockfailed TAS: 0CPU Bwants the lockfailed TAS: 0CPU Cwants the lockfailed TAS: 0CPU ACPU BCPU C123456789101112131415161718tickplain spinlock: while (test_and_set(&lock)) ;
Step 1

Three CPUs, one lock word, a fixed bus order

All three CPUs want the same critical section. The lock word is 0, meaning free. Each tick one CPU gets the memory bus and performs its next step; the order is fixed: A B C A A B C A B B A C B A A B C C. Real hardware makes this choice by arbitration, which is exactly why it can be unlucky for one CPU.

Output
1 / 18
4

Mutual Exclusion, Progress and Bounded Waiting

  1. Announce – waiting[i] = true; key = true;
  2. Spin – while (waiting[i] && key) key = test_and_set(&lock);
  3. Enter – waiting[i] = false; then run the critical section.
  4. Scan – j = (i + 1) % n; while (j != i && !waiting[j]) j = (j + 1) % n;
  5. Release or hand off – if j == i set lock = false, else set waiting[j] = false.

A correct critical-section solution must satisfy three requirements. The plain TAS spinlock meets the first two but not bounded waiting: when the lock is released, whichever CPU's TAS reaches memory first wins, with no notion of who has waited longest. An unlucky CPU can lose every race indefinitely. That is starvation, and the tracer above shows CPU C failing every attempt while A and B take turns.

The fix keeps a shared array waiting[n], all false. To enter, CPU i sets waiting[i] = true and spins while (waiting[i] && key) key = test_and_set(&lock);. On leaving, it scans j = i+1, i+2, … (mod n) for the first CPU with waiting[j] true. If it finds one it sets waiting[j] = false, handing the lock over directly without ever clearing it. Only if nobody is waiting does it set lock = false. Because the scan moves round the circle, a waiting CPU is served within n − 1 turns.

The three requirements, checked
RequirementPlain TAS spinlockTAS with waiting[] hand-off
Mutual exclusionyes – only one TAS reads 0 per releaseyes – the lock is either free or handed to exactly one CPU
Progressyes – if the lock is free, some TAS succeedsyes
Bounded waitingno – a CPU can lose every raceyes – at most n − 1 others enter first
  • The hand-off never sets the lock to 0, so a CPU that arrives late cannot slip in ahead of the one being served
  • The scan costs O(n) on every release, which is the price of the n − 1 bound
5

Busy Waiting, Test-and-Test-and-Set and Ticket Locks

Spinning costs more than the waiting CPU's time. Every TAS is a write, so on a cache-coherent multiprocessor each attempt takes the lock's cache line in exclusive mode and invalidates every other CPU's copy. With several spinners the line bounces between caches and floods the interconnect, slowing down the owner who is trying to finish.

Test-and-test-and-set (TTAS) spins on an ordinary read first: while (true) { while (lock) ; if (!test_and_set(&lock)) break; }. The inner read loop hits in each CPU's own cache and generates no traffic; only when the lock is seen free does a CPU try the expensive TAS. Adding exponential backoff after a failed TAS spreads the retries out further.

A ticket lock fixes fairness with fetch-and-add. Each arriving thread takes my = fetch_and_add(&next_ticket, 1) and spins until now_serving == my; release increments now_serving. Threads enter in exact arrival order, like a deli counter, so waiting is bounded. The Linux kernel used ticket spinlocks from 2.6.25, then moved to queued spinlocks (MCS-style) in which each waiter spins on its own cache line.

Spinlock variants
LockSpins onFair?Cache traffic while waiting
TASatomic write every iterationnohigh – line bounces on every attempt
TTASplain read, TAS only when freenolow while held, burst on release
TTAS + backoffread, TAS, then wait longer after failuresnolower
Ticket locknow_serving counteryes, FIFOall waiters reread one line on release
MCS / queued locka flag in the waiter's own nodeyes, FIFOminimal – one waiter woken per release
  • TTAS still causes a burst on release: every spinner sees 0 at once and all try TAS together
  • A ticket lock is fair but has no back-off of its own: if the next ticket holder is preempted, everyone behind it waits
6

Spinlock vs Mutex

A mutex in the usual OS sense is a sleeping lock: a thread that finds it held is put on a wait queue and blocked, and the CPU runs something else. That costs two context switches, typically microseconds. A spinlock costs nothing to wait except the spinning itself. So the choice depends on how long the wait will be compared with the cost of sleeping and waking.

Spinlocks are the right choice when critical sections are short (a few hundred instructions), when the machine is a multiprocessor so the owner is actually running and will release soon, and in kernel code that cannot sleep, such as interrupt handlers. On a single CPU a spinning thread only wastes its time slice, since the owner cannot run until the spinner is preempted; uniprocessor kernels disable interrupts or preemption instead. Many practical mutexes are hybrids: they spin briefly, then sleep (Linux adaptive mutexes, futex-based locks).

Spinlock against sleeping mutex
AspectSpinlockMutex (sleep lock)
While waitingbusy-waits on the CPUblocks; CPU runs other work
Cost to waitCPU cycles for the whole waittwo context switches
Best whencritical section is very shortcritical section is long or may block
Single CPUwasteful – owner cannot runfine
Interrupt handlersusable (with interrupts disabled locally)not allowed – cannot sleep
Holder may sleep?noyes
ExamplesLinux spin_lock, std::atomic_flag loopspthread_mutex_t, Java synchronized when contended
  • Never sleep while holding a spinlock: a waiter would spin for the whole sleep
  • In the kernel, take a spinlock with interrupts disabled if an interrupt handler can take the same lock, or the handler spins forever on its own CPU
7

Strengths, Weaknesses and Uses

Test-and-set is the foundation layer: semaphores, mutexes and monitors are all implemented on top of an atomic instruction, usually guarding their own internal queues with a short spinlock.

Its strengths are simplicity (one instruction and a loop), no context switch to acquire, and use where sleeping is forbidden. Its weaknesses are wasted CPU time while spinning, no bounded waiting without the waiting[] array, heavy cache traffic under contention, and priority inversion when the holder is preempted while others spin.

  • OS kernels: run queues, interrupt handlers, per-CPU data
  • Building blocks for mutexes, semaphores and condition variables
  • Lock-free structures with compare-and-swap
  • User-space fast paths in futex-based locks