C829 of 55
0 XP
  1. Hook
  2. Play
  3. Predict
  4. Name it
  5. Check
  6. Explain

C8 · Lesson 29 · Atomic instructions and locks

Read-modify-write that can't be interrupted, even by another core, and what sharing a counter costs

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.

  • 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.

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?

Name it

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:

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.

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.

Worked example

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

Show the 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.

Worked 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?

Show the 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×200=1600million/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.

Worked 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?

Show the solution
  1. One critical section. A 100 ns acquisition plus 50 ns of work: 100+50=150ns
  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

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

Check

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

Check

A contended spinlock takes 100 ns to acquire and protects 20 ns of work. What percentage of the time is spent in the critical section's work?

Check

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

Check

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

Check

8 cores could each do 100 million increments a second on private counters. By what factor does that beat one shared atomic counter whose cache line takes 100 ns per handoff?

Check

Enumerate every interleaving of two threads that each do k = 2 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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Explain why

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.

Practice

Keep practicing

8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.