One number made me stop scrolling: 5.7x. A C++ write-up called Optimizing a Spin-Lock takes the simplest lock there is and makes it 5.7 times faster and 5.4 times lighter on energy at four threads. The ending is sensible, too. It tells you to keep std::mutex in most code.
Then I thought about the 30-year question this blog keeps asking. A lock tuned this tightly is tuned for one chip. What happens on a different one? I had an M1 on the desk, so I rebuilt the four versions and found out.
What did the original measure?
Four versions of the same lock, each fixing one problem. Threads take the lock, bump a shared 64-bit counter and release it. The author used clang, pinned threads to cores, and read perf counters. Latency at four threads, from the article's tables:
| Version | Change | 4 threads | Energy, 4 threads |
|---|---|---|---|
| V1 naive | atomic exchange in a loop | 246 ns | 64.92 J |
| V2 ordering | acquire on lock, release on unlock |
131 ns | 34.45 J |
| V3 test-and-test-and-set | spin on a read, with a pause | 120 ns | 30.97 J |
| V4 backoff | doubling pause, capped at 64 | 43 ns | 11.92 J |
The perf counters explain why. In V1 at four threads, 61.73% of L1 data loads missed, because every waiter writes the same cache line and steals it from the others. By V4 that fell to 12.88%. The article doesn't name the CPU, so treat the absolute numbers as belonging to that box.
What did I run on the M1?
Same four versions, same shape: a lock on its own cache line, a counter on another, 2,000,000 increments per thread, built with clang++ -std=c++20 -O3. I added std::mutex as a fifth row, because the article's own advice is that it's the default.
My environment, so you can check me: Apple M1 (4 performance and 4 efficiency cores), Apple clang 17.0.0, macOS 26.6.2. Each cell is the median of seven runs, and I ran the whole sweep twice. Three honest differences from the original:
- No pinning. macOS doesn't give you thread affinity, so the scheduler can put a thread on an efficiency core.
- No energy numbers. The article reads RAPL counters, which are an Intel feature, so I can't compare joules.
- A busy machine. Load average was between 3 and 6 while I measured, because other jobs were running. My first sweep read 81 ns for V1 at four threads. The next two read 46 and 44. That spread is noise I'm not going to hide.
My latency is wall-clock time divided by total acquisitions across all threads, so it isn't the same quantity as the article's per-operation figure. Compare the shape, not the digits.
// V4, the version that won on x86
void lock() {
int d = 1;
while (f.exchange(true, std::memory_order_acquire)) {
do {
for (int i = 0; i < d; i++) cpu_relax(); // "yield" on arm64
if (d < 64) d <<= 1;
} while (f.load(std::memory_order_relaxed));
}
}
What did the M1 say?
Two sweeps, shown as first / second. All in ns per acquisition.
| Version | 1 thread | 2 threads | 4 threads |
|---|---|---|---|
| V1 naive | 8.2 / 7.3 | 15.8 / 17.1 | 45.6 / 44.3 |
| V2 acquire/release | 5.1 / 5.1 | 15.7 / 16.3 | 30.5 / 30.3 |
| V3 test-and-test-and-set | 5.1 / 5.1 | 15.7 / 17.0 | 24.6 / 26.2 |
| V4 exponential backoff | 5.1 / 5.1 | 16.1 / 19.7 | 37.5 / 41.4 |
std::mutex |
8.9 / 9.0 | 16.1 / 15.9 | 26.2 / 25.4 |
Steps one through three behaved. Ordering took about a third off V1 at four threads, and the read-only spin took a bit more. Then the story flips. V4 is slower than V3 at four threads, by roughly 50 to 60 percent, in both sweeps. And std::mutex sits at 25 to 26 ns, level with the best spin-lock.
That's the opposite of the original, where backoff gave the single biggest gain. Why? When I first wrote this I couldn't tell you, and I'd have been guessing if I'd blamed the efficiency cores. I found a cause later, and it's the pause instruction itself; the section on Rust and Go below has the measurement. What I can say is that a constant I'd have copied without thinking, the cap of 64, is wrong on this chip for this workload.
Is that a knock on the article? No. It measured what it said it measured, on the machine it named. It's a knock on copying a number.
Why does the x86 history make this worse?
The pause hint is the part of a spin-lock that has changed under people before. On x86 it's the PAUSE instruction, and a 2018 PostgreSQL mailing-list thread pointed out that the instruction went from about 9 clock cycles on Haswell to 141 on Skylake-class processors, citing Agner Fog's instruction tables. I haven't read Intel's manual or Fog's tables myself, so I'm relying on that thread for the figures. The shape of the problem needs no number, though. A backoff cap written when a pause cost 9 cycles means something very different when it costs 141.
Code like that doesn't fail a test. It gets slower on new hardware, quietly, years after the person who tuned it has moved on. If your repository will outlive its current CI runners, that's the kind of decay worth pricing in.
What does a broken version look like?
V2 changes the memory ordering, and that's the change most likely to be copied wrong. So I broke it on purpose: relaxed on both lock and unlock, protecting a plain long counter. Four threads, 200,000 increments each, -O2.
counter=200000 expected=800000
counter=200000 expected=800000
counter=200000 expected=800000
The correct version, with acquire and release, printed 800,000 three times. The broken one lost three quarters of the work and never crashed. I looked at the generated arm64 code to see why. The compiler loads counter once before the loop, adds in a register, and stores once after it, because a relaxed exchange isn't a barrier it has to respect. Each thread then overwrites the others. That listing is from one batch of runs. Run again later, the same program printed 200,000 twice and 400,000 once, probably because threads that barely overlapped lost less. The size of the loss changes between runs; the fact that it happens doesn't. cppreference is blunt about it: a lock needs acquire on the way in and release on the way out, or the data it guards isn't protected.
I wanted to show you what ThreadSanitizer prints for this. It can't, here. Both of my sanitizer builds, the correct one and the broken one, died with a segmentation fault (exit 139) before running anything. That's the sanitizer runtime on this macOS and compiler combination, not the lock. So I can't show a TSan report, and I won't invent one.
What can a gate actually see?
Take the blog's usual question: what would catch this before a reviewer's tired eyes do?
- A lost-update assertion. My harness exits non-zero if the counter isn't
threads * iterations. It's six lines and it caught the broken lock instantly. A concurrency test that checks a total costs almost nothing. It also fails on its own schedule: a lost update that shows up in a few runs out of 300 is a much harder specimen, and a retry policy can hide it. - ThreadSanitizer on Linux CI. The Clang docs describe it as a data-race detector. Since it didn't run on my Mac, I'd put it on a Linux runner and treat a crash of the sanitizer itself as a failure, not a skip.
- A review rule for
memory_order. Anything other than the default needs a one-line comment saying what it synchronizes with. Reviewers can enforce that; compilers can't. - A benchmark that reports and doesn't block. My own coverage-metric post argues that a gate on a number invites gaming. A lock benchmark is worse, because the number changes with the chip. Record it with the hardware named, and don't fail builds on it.
For the compiler-flag side of the same discipline, the per-flag promotion approach for legacy C++ applies. And where this sits among the checks I'd run first is in twelve CI gates.
Can you rerun this?
Yes, and you should, because a table of numbers from one laptop proves little. Here is the harness, trimmed to the essentials. The four lock versions follow the original write-up's descriptions, so the code is my reading of them, not the author's source.
// clang++ -std=c++20 -O3 bench.cpp -o bench
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <mutex>
#include <thread>
#include <vector>
static inline void cpu_relax() {
#if defined(__aarch64__)
asm volatile("yield" ::: "memory");
#else
asm volatile("pause" ::: "memory");
#endif
}
struct V1 { alignas(128) std::atomic<bool> f{false};
void lock() { while (f.exchange(true)) {} }
void unlock() { f.store(false); } };
struct V2 { alignas(128) std::atomic<bool> f{false};
void lock() { while (f.exchange(true, std::memory_order_acquire)) {} }
void unlock() { f.store(false, std::memory_order_release); } };
struct V3 { alignas(128) std::atomic<bool> f{false};
void lock() { while (f.exchange(true, std::memory_order_acquire)) {
while (f.load(std::memory_order_relaxed)) cpu_relax(); } }
void unlock() { f.store(false, std::memory_order_release); } };
struct V4 { alignas(128) std::atomic<bool> f{false};
void lock() { int d = 1;
while (f.exchange(true, std::memory_order_acquire)) {
do { for (int i = 0; i < d; i++) cpu_relax(); if (d < 64) d <<= 1; }
while (f.load(std::memory_order_relaxed)); } }
void unlock() { f.store(false, std::memory_order_release); } };
struct M { alignas(128) std::mutex m;
void lock() { m.lock(); } void unlock() { m.unlock(); } };
constexpr long ITERS = 2'000'000;
template <class L> double run(int threads) {
L lock; alignas(128) long counter = 0;
std::vector<std::thread> ts;
auto t0 = std::chrono::steady_clock::now();
for (int t = 0; t < threads; t++)
ts.emplace_back([&] { for (long i = 0; i < ITERS; i++) { lock.lock(); counter++; lock.unlock(); } });
for (auto& t : ts) t.join();
auto t1 = std::chrono::steady_clock::now();
if (counter != ITERS * threads) std::printf("LOST UPDATES\n");
return std::chrono::duration<double, std::nano>(t1 - t0).count() / double(ITERS * threads);
}
template <class L> void row(const char* name) {
std::printf("%-6s", name);
for (int th : {1, 2, 4}) {
std::vector<double> r;
for (int k = 0; k < 7; k++) r.push_back(run<L>(th));
std::sort(r.begin(), r.end());
std::printf(" %6.1f", r[3]); // median of seven
}
std::printf("\n");
}
int main() { row<V1>("V1"); row<V2>("V2"); row<V3>("V3"); row<V4>("V4"); row<M>("mutex"); }
I reran it on the same M1 while the machine was far busier than during the first sweeps, with a load average near 19. The absolute numbers were noisier and higher, so I won't quote them. The shape held in the last two of four reruns, the ones I kept after the load settled a little: one-thread times of about 5 ns for V2 to V4 and about 9 ns for std::mutex, V4 slower than V3 at four threads, and std::mutex in the same range as the spin-locks. That agrees with the table above, and it's the only claim I'd ask you to check on your own hardware.
What happens in Rust and Go?
I'd only tested C++, so I added the other two languages people write this lock in. Same M1, same shape: lock and counter each on their own 128-byte line, 2,000,000 acquisitions per thread, median of seven runs, two sweeps. Rust is 1.99.1 with -C opt-level=3, Go is 1.27.3. The harnesses and the raw output are in the repo. The load average sat between 6 and 12 on eight cores, higher than during the first sweeps, so the C++ column here is noisier and higher than the table above. Go's "threads" are goroutines, which isn't the same thing.
Four threads, ns per acquisition, first and second sweep:
| Version | C++ | Rust | Go |
|---|---|---|---|
| V1 naive | 88.5 / 92.3 | 94.3 / 107.1 | 93.0 / 101.6 |
| V2 acquire/release | 85.1 / 66.7 | 80.8 / 59.9 | none |
| V3 test-and-test-and-set | 53.7 / 64.1 | 53.2 / 50.6 | 106.2 / 96.2 |
V3 with runtime.Gosched() |
none | none | 17.7 / 21.2 |
| V4 backoff | 54.1 / 76.4 | 7.7 / 8.2 | 45.5 / 83.5 |
| mutex | 29.3 / 29.4 | 30.2 / 30.6 | 84.4 / 100.3 |
Look at Rust's V4. Seven or eight nanoseconds at four threads, in the neighborhood of the 5 ns one uncontended thread needs. The same four-line loop in C++ was no faster than V3 on this chip, so something other than the language was going on.
The assembly said what. std::hint::spin_loop() compiled to isb in my build, and rustc --emit asm shows it twice. My C++ cpu_relax is yield, and the clang output has two of those and no isb. So I swapped them. C++ with isb in the backoff: 6.4 and 6.9 ns at four threads, against 38.9 and 41.3 for the same loop with yield. Rust with an inline-asm yield instead of spin_loop: 62.2 and 39.7 ns, against 9.1 and 6.8 with spin_loop. Nothing else changed.
::cts On the same chip, the same backoff loop ran at 6 ns or 40 ns depending on which instruction the word "pause" turned into.
My reading, which I haven't confirmed with a profiler: a yield hint costs almost nothing here, so doubling the wait up to 64 hints is still a short wait and the waiters keep hammering the lock's cache line. An isb is a much longer stall, so the waiters really do step aside. I'd also read the near-single-thread result with suspicion. A figure that close to the uncontended one means the lock is changing hands in long runs, and I measured throughput, not fairness. One thread could be winning it again and again while the rest sit in backoff. I wouldn't ship that on this evidence either.
The Rust documentation for spin_loop says it emits "a machine instruction" to signal a busy-wait loop, and it names none. Which one you get is a property of your compiler and target, and you find out by reading the assembly. That's the earlier x86 story again, one layer down: the old PAUSE changed cost between processor generations, and here the same hint is a different instruction depending on the language.
Go's rows tell a second story. The Go memory model says that "all the atomic operations executed in a program behave as though executed in some sequentially consistent order", so there is no acquire/release choice and no V2 to get wrong. I also didn't find a pause hint in the standard library. The nearest thing is runtime.Gosched(), which hands the goroutine back to the scheduler. At four goroutines that ran at 17.7 and 21.2 ns, far ahead of the plain read spin at about 100 ns. It's a different mechanism, though, not a cheaper pause. And sync.Mutex at four goroutines took 84 to 100 ns, against about 30 for the C++ and Rust mutexes. I didn't investigate that. Goroutines, a loaded machine and one chip are three reasons not to generalize it.
Now the broken counter, which is where the languages split. In the gate list above I said ThreadSanitizer was out of reach on this Mac. Go's race detector isn't. I wrote the plain counter += 1 version for each language and ran it.
$ rustc lost.rs
error[E0499]: cannot borrow `counter` as mutable more than once at a time
$ go run lost.go (three runs)
counter=252028 expected=800000
counter=250967 expected=800000
counter=247583 expected=800000
$ go run -race lost.go
WARNING: DATA RACE
Read at 0x00c00018e038 by goroutine 8:
Rust refused to compile it. Go compiled it, lost about two thirds of the updates, and the race detector named the line. The Go documentation lists darwin/arm64 as supported, with cgo enabled. So for Go, put -race in your test command. For Rust, the borrow checker is the gate until you write unsafe, which my lock harness has to do with UnsafeCell, and at that point you're back to the lost-update assertion and ThreadSanitizer. The C++ advice above stands.
Where does this break?
It's one chip, one workload and a busy machine. A counter increment is the shortest possible critical section, and real code does real work under a lock. Under a longer critical section the waiters would wait differently, so I wouldn't stretch these numbers to cover it. I'd still want pinned threads and perf counters before saying why the pause instruction matters this much, and macOS gives me neither.
So here's what I'd stand behind. Reach for std::mutex. If you must hand-roll a lock, write the ordering down, add the lost-update test, and record which chip your constants came from. Does your repository say that anywhere? For the debugger side of C++ on Linux, see Debugging C++ on Linux.