---
title: Atomic instructions and locks
heading: Read-modify-write that can't be interrupted, even by another core, and what sharing a counter costs
eyebrow: C8 · Lesson 29 · Atomic instructions and locks
xp: 40
---

::: hook
Lesson 28 fixed a race between an interrupt and the main loop by turning interrupts off around the update. On a chip with two cores that no longer works: the other core doesn't care about this core's interrupt switch, and both can load the same counter, add one and store, losing an update. Processors solve this with **atomic instructions**: a read-modify-write that the memory system guarantees no other core can split. RISC-V's A extension has two kinds, atomic memory operations such as `amoadd.w`, and the pair load-reserved / store-conditional for building anything else. Locks, queues and reference counts all rest on them, and so does a cost that grows with every core that touches the same data.
:::

::: play
- The throughput of a shared counter incremented by several cores, in millions of increments per second, against the number of cores. Each core could do 200 million increments a second on its own data.
- With one shared counter, every increment needs the cache line that holds it, which travels from core to core, taking the handoff time $h$ each time. Throughput stays flat at one increment per handoff.
- With per-core counters added up at the end, throughput grows with the core count.
:::

```sim plot
view: graph
x: n = 1..16
y: r = 0..3500
slider: h = 20..200 step 10 = 100
plot: 1e3/h + 0*n | label: one shared atomic counter, M/s
plot: 200*n | dashed | color: ch2 | label: per-core counters, M/s
readout: shared counter, millions per second = 1e3/h
```

::: predict
## Two threads each run `count = count + 1` once (load, add, store) on a shared variable starting at 0, with no locking. Of all the ways their instructions can interleave, how many leave count at 2?

- [ ] All of them
- [ ] Half of them
- [x] A third of them
- [ ] None

::: reveal
Each thread has a load and a store, so there are $\binom42$ = 6 interleavings. Only when one thread's store comes before the other's load (thread A entirely first, or thread B entirely first) is the result 2; in the other four, both load 0 and both store 1. With more increments per thread the odds of a correct result fall fast: for three increments each, only 20 of 924 interleavings are correct, and the final count can be as low as 2.
:::
:::

::: nameit
## Atomic memory operations

`amoadd.w rd, rs2, (rs1)` loads the word at the address in `rs1` into `rd`, adds `rs2`, and stores the sum, as one indivisible step: no other core's access to that word can come between the load and the store. Its relatives do swap, AND, OR, XOR, min and max. A shared counter becomes one instruction, `amoadd.w zero, t0, (a0)`.

## Load-reserved and store-conditional

For anything more complex, `lr.w` loads a word and places a reservation on it; `sc.w` stores only if no other core has written that word since, and writes 0 to its destination register if it succeeded, nonzero if not. A loop retries until it succeeds:

```asm
retry:
    lr.w t0, (a0)
    addi t0, t0, 1      # any computation here
    sc.w t1, t0, (a0)
    bnez t1, retry
```

Compare-and-swap, stacks and queues are built this way.

## Locks

A spinlock is a word that's 0 when free. To acquire it, atomically swap in a 1 and look at what came back: if it was 0, the lock is yours; if 1, someone holds it, so try again. To release it, store 0.

```asm
acquire:
    li t0, 1
    amoswap.w.aq t1, t0, (a0)
    bnez t1, acquire
    ...                 # critical section
    amoswap.w.rl zero, zero, (a0)
```

The `.aq` and `.rl` suffixes order memory: nothing in the critical section may appear to happen before the acquire or after the release. Without them, modern processors and compilers may reorder ordinary loads and stores across the lock. `fence` instructions order memory explicitly.

## The cost of sharing

An atomic operation needs exclusive ownership of the cache line holding the word (lesson 45). When several cores update the same word, the line bounces between their caches, each move taking tens to hundreds of nanoseconds, and the updates serialize: total throughput is about one per handoff, however many cores there are. Giving each core its own counter, in its own cache line, and summing them when needed removes the contention.
:::

::: example
## Show an interleaving of two threads, each doing one load, add and store on `count` = 5, that loses an update.

::: solution
1. **A loads.** A reads `count`: 5.
2. **B loads.** B reads 5 as well.
3. **A stores.** A adds and stores 6.
4. **B stores.** B adds and stores 6.
5. **The result.** Both increments ran, but `count` went from 5 to 6. Any schedule where both loads happen before either store loses one.
6. **With `amoadd.w`.** Each thread's load-add-store is indivisible, so the only possible results are A then B or B then A, both giving 7.

**Answer:** A loads 5, B loads 5, A stores 6 and B stores 6, so `count` ends at 6 instead of 7.
:::
:::

::: example
## Eight cores increment one shared atomic counter as fast as they can. Each cache-line handoff takes 100 ns. What's the total throughput, and what is it with per-core counters if each core can do 200 million increments per second locally?

::: solution
1. **One shared counter.** Each increment needs the line, and the line moves once per increment when cores alternate: about one increment per 100 ns, 10 million per second in total.
2. **Compare with one core.** That's no better than one core, and far worse than one core working alone (200 million).
3. **Per-core counters.** With each on its own cache line:
   $$8 \times 200 = 1600\ \text{million/s}$$
   160 times more.
4. **Reading the total.** A sum taken occasionally reads eight lines, which costs a few hundred nanoseconds.

**Answer:** about 10 million increments per second with the shared counter, and 1600 million with per-core counters.
:::
:::

::: example
## Two cores contend for a spinlock that protects a 50 ns critical section; acquiring it takes a 100 ns handoff of its cache line. If both want it continuously, how many critical sections per second complete, and what fraction of the time is spent doing useful work?

::: solution
1. **One critical section.** A 100 ns acquisition plus 50 ns of work:
   $$100 + 50 = 150\ \text{ns}$$
2. **Throughput.** That's about 6.7 million sections per second in total.
3. **Useful work.** Only $50/150$ = 33% of the time does the protected work.
4. **What follows.** Making the critical section longer amortizes the lock; making it shorter or more frequent makes the lock the bottleneck. That's why scalable code avoids sharing in the first place.

**Answer:** about 6.7 million critical sections per second, with 33% of the time spent on useful work.
:::
:::

::: check
given: k = 2 | 3 | 5
answer: 2*k
tolerance: 0.5%

## Two threads each increment a shared counter (starting at 0) {k} times using atomic `amoadd.w`. What is the final value?

::: right
Right: {answer}. Atomic increments can't lose updates, so every one counts.
:::

::: misses
- [k] Both threads' increments count.
- [2] That's the worst case without atomics.
- [any] Not yet. Every atomic increment takes effect.
:::
:::

::: check
given: h = 40 | 100 | 250; n = 2 | 8 | 32
answer: 1e3/h
tolerance: 0.5%

## {n} cores hammer one shared atomic counter. Every increment needs the cache line, which takes {h} ns to move between cores. About how many million increments per second happen in total?

::: right
Right. About one per handoff: {answer} million per second, whatever the number of cores.
:::

::: misses
- [n*1e3/h] The handoffs serialize: more cores don't add throughput.
- [any] Not yet. One increment per {h} ns.
:::
:::

::: check
given: h = 50 | 100 | 200; w = 20 | 50 | 200
answer: w/(h + w)*100
tolerance: 0.5%

## A contended spinlock takes {h} ns to acquire and protects {w} ns of work. What percentage of the time is spent in the critical section's work?

::: right
Right. $w/(h + w)$ = {answer}%.
:::

::: misses
- [w/h*100] The cycle is acquisition plus work: divide by $h + w$.
- [any] Not yet. Useful time over total time per section.
:::
:::

::: check
given: k = 3 | 4 | 5
answer: 2 + 0*k
tolerance: 0.5%

## Two threads each perform {k} unprotected increments (load, add, store) on a counter starting at 0. What's the smallest final value some interleaving can produce?

::: right
Right: {answer}. Thread A loads 0 and stalls; B runs all but its last increment; A stores 1; B loads that 1 and stalls; A finishes its other increments; B stores 2 over all of them. However many increments, the worst case is 2.
:::

::: misses
- [k] It can be worse than one thread's worth.
- [2*k] That's with no lost updates.
- [any] Not yet. Try a schedule where each thread's early load erases the other's work.
:::
:::

::: check
kind: choice

## Why doesn't disabling interrupts protect a shared counter on a two-core processor?

- [x] It stops this core from being interrupted, but the other core keeps running and can access the counter at the same time
- [ ] Multicore processors don't have interrupts
- [ ] Disabling interrupts also disables the cache
- [ ] It does protect it, as long as both cores disable interrupts

::: right
Right. Interrupt masking is per core. The other core's load and store can still land between this core's, so only an atomic instruction or a lock built from one can make the update indivisible.
:::

::: misses
- [2] Each core has its own interrupts.
- [3] The cache keeps running either way.
- [4] Even with both disabled, both cores run at once and can interleave their loads and stores.
:::
:::

::: check
given: n = 4 | 8 | 16; r = 100 | 200 | 400; h = 50 | 100
answer: n*r/(1e3/h)
tolerance: 0.5%

## {n} cores could each do {r} million increments a second on private counters. By what factor does that beat one shared atomic counter whose cache line takes {h} ns per handoff?

::: right
Right. Private: $nr$ million per second. Shared: $10^3/h$ million. The ratio is {answer}.
:::

::: misses
- [n] The shared counter is slower than even one core's private rate.
- [any] Not yet. $nr$ against $1000/h$.
:::
:::

::: check
kind: python
given: k = 1 | 2 | 3

## Enumerate every interleaving of two threads that each do `k` = {k} increments as two steps, a load into a private register and a store of that register plus one, to a shared counter starting at 0. Count the distinct schedules (`total`), how many give the correct `2*k` (`correct`), and the smallest final value (`worst`). Use `itertools.combinations` to choose which of the $4k$ steps belong to thread 0.

```python starter
total = correct = 1
worst = 2 * k
```

```python solution
from itertools import combinations
n = 2 * k
total = correct = 0
worst = None
for pos in combinations(range(2 * n), n):
    sched = [1] * (2 * n)
    for p in pos:
        sched[p] = 0
    shared, local, step = 0, [0, 0], [0, 0]
    for t in sched:
        if step[t] % 2 == 0:
            local[t] = shared
        else:
            shared = local[t] + 1
        step[t] += 1
    total += 1
    correct += shared == 2 * k
    worst = shared if worst is None else min(worst, shared)
```

```python tests
ref = {1: (6, 2, 1), 2: (70, 6, 2), 3: (924, 20, 2)}[k]
assert (total, correct, worst) == ref, f"For k = {k}: {ref[0]} schedules, {ref[1]} correct, worst {ref[2]}."
```

::: right
Right. The correct schedules are exactly those where the threads' increments never overlap, a vanishing fraction as $k$ grows, and the worst case drops to 2 however many increments there are.
:::
:::

::: explain
## A multithreaded program counts network packets with one shared counter updated by `amoadd.w` on every core. It's correct, but adding cores makes it slower. Explain why, and how to fix it without losing correctness.

::: model
Each `amoadd.w` needs exclusive ownership of the cache line holding the counter, so the line moves to whichever core is updating it. With several cores updating constantly, the line ping-pongs between their caches; each transfer takes tens to hundreds of nanoseconds, and the updates are serialized behind those transfers. Total throughput is about one increment per transfer regardless of the core count, and each core spends most of its time waiting, so per-core speed falls as cores are added. The fix is to stop sharing: give each core its own counter, in its own cache line so they don't share a line by accident, increment it with an ordinary or atomic local update, and add the per-core counters together only when the total is needed. The total is still exact.
:::
:::

::: practice

::: check
given: h = 30 | 80 | 150
answer: 1e3/h
tolerance: 0.5%

## About how many million updates per second can a shared atomic counter handle if each cache-line handoff takes {h} ns?

::: misses
- [h] One update per handoff: invert it.
- [any] $1000/h$ million per second.
:::
:::

::: check
given: h = 60 | 120; w = 30 | 90
answer: 1e3/(h + w)
tolerance: 0.5%

## A contended lock costs {h} ns to acquire and guards {w} ns of work. How many million critical sections per second complete?

::: misses
- [1e3/w] Include the acquisition time.
- [any] $1000/(h + w)$ million per second.
:::
:::
:::
