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 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?
Each thread has a load and a store, so there are = 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.
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
- A loads. A reads
count: 5. - B loads. B reads 5 as well.
- A stores. A adds and stores 6.
- B stores. B adds and stores 6.
- The result. Both increments ran, but
countwent from 5 to 6. Any schedule where both loads happen before either store loses one. - 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
- 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.
- Compare with one core. That's no better than one core, and far worse than one core working alone (200 million).
- Per-core counters. With each on its own cache line: 160 times more.
- 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
- One critical section. A 100 ns acquisition plus 50 ns of work:
- Throughput. That's about 6.7 million sections per second in total.
- Useful work. Only = 33% of the time does the protected work.
- 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 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.
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
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.