On this page

A single read-modify-write instruction is not atomic just because it’s one instruction: unless the core locks the cache line exclusively, a sibling thread can slip in between the read and the write.

The arena from lesson 22 hands out memory, yet says nothing about two threads writing to the same word concurrently. Now we drop down to the cache-coherency bus: cache lines, MESI states, the lock prefix, the futex syscall, and fs:-relative thread-local storage.

Mental Model: Words vs. Cache Lines

Intuition What the testbed shows
add [counter], 1 is a single atomic operation Four threads lost more than half of their 400,000 increments
xchg without lock isn’t atomic xchg with a memory operand locks the line implicitly—no f0 prefix byte is emitted
Synchronization always requires a syscall A spinlock completes 400,000 acquisitions with zero trips to the kernel
futex is a standalone kernel mutex It is a syscall operating on an ordinary 32-bit word in user memory
Two adjacent variables don’t affect each other Counters sharing a cache line ran nearly 6x slower

Why add [mem], 1 Loses Updates

The C99 harness increments a shared counter across four threads. The helper uses volatile so the compiler won’t hoist or eliminate the memory accesses:

c
static void race_inc(volatile uint64_t *counter)
{
    uint64_t value = *counter;

    *counter = value + 1;
}

With -O2, the compiler collapses the load, increment, and store into a single instruction—producing the exact form intuition assumes is atomic:

$ objdump -d -M intel build/atomics_test | sed -n '/<plain_worker>:/,/ret/p'
00000000000016a0 <plain_worker>:
    16a0:	48 83 7f 18 00       	cmp    QWORD PTR [rdi+0x18],0x0
    16a5:	74 17                	je     16be <plain_worker+0x1e>
    16a7:	48 8b 17             	mov    rdx,QWORD PTR [rdi]
    16aa:	31 c0                	xor    eax,eax
    16ac:	0f 1f 40 00          	nop    DWORD PTR [rax+0x0]
    16b0:	48 83 02 01          	add    QWORD PTR [rdx],0x1
    16b4:	48 83 c0 01          	add    rax,0x1
    16b8:	48 3b 47 18          	cmp    rax,QWORD PTR [rdi+0x18]
    16bc:	72 f2                	jb     16b0 <plain_worker+0x10>
    16be:	31 c0                	xor    eax,eax
    16c0:	c3                   	ret

add QWORD PTR [rdx],0x1 is that “single instruction.” Internally, the CPU still executes three micro-steps: reading the cache line, adding 1 in the ALU, and writing the result back. Between the read and the write, ownership of the cache line can move to another core.

Core 1memory at rdxCore 0Core 1memory at rdxCore 0one update lostread → 1001read → 1002write 1013write 1014
Core 1memory at rdxCore 0Core 1memory at rdxCore 0one update lostread → 1001read → 1002write 1013write 1014
Fig. 1. Lost update on a non-atomic increment

Modern CPUs keep caches coherent via the MESI protocol. Every 64-byte cache line sits in one of four states:

  • Modified — the line is dirty and owned exclusively by this core;
  • Exclusive — the line is clean and owned exclusively by this core;
  • Shared — the line resides in multiple cores’ caches and matches main memory;
  • Invalid — the local copy is stale and cannot be read.

Writing requires exclusive ownership: the core broadcasts an invalidation request for the line, transitions all other copies to Invalid, and only then commits the write. Two cores executing an un-locked add simultaneously can both read the same stale value and overwrite it with the same incremented result.

Atomicity is not the same as memory ordering. The x86 memory model is TSO. The lock prefix therefore serves double duty: it guarantees an indivisible read-modify-write and acts as a full memory barrier.

$ ./build/atomics_test | head -2
race: plain 400000 -> 199497
race: locked 400000

Out of 400,000 un-locked increments, only 199,497 made it into the counter. The exact count varies from run to run, but is consistently below 400,000—those missing counts are lost updates.

xchg, lock cmpxchg, and a Spinlock

A spinlock is built on an atomic exchange: xchg with a memory operand locks the cache line implicitly for the duration of the operation without needing an explicit prefix.

atomics.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; atomics.asm — xchg spinlock, trylock, and futex-based lock.

default rel

%define SYS_FUTEX 202
%define FUTEX_WAIT 0
%define FUTEX_WAKE 1

section .text
    global asm_spin_lock
    global asm_spin_trylock
    global asm_spin_unlock
    global asm_futex_lock
    global asm_futex_unlock

; ------------------------------------------------------------------------------
; void asm_spin_lock(uint32_t *lock)
; Input:     rdi = pointer to lock word (0 = free, 1 = held)
; Output:    none; *lock = 1 upon acquisition
; Clobbers:  rax, flags (writes to [rdi])
; ------------------------------------------------------------------------------
asm_spin_lock:
    mov eax, 1

.retry:
    xchg eax, [rdi]
    test eax, eax
    jz .done

.spin:
    pause
    cmp dword [rdi], 0
    jne .spin
    mov eax, 1
    jmp .retry

.done:
    ret

; ------------------------------------------------------------------------------
; int asm_spin_trylock(uint32_t *lock)
; Input:     rdi = pointer to lock word
; Output:    eax = 1 if acquired (*lock = 1), 0 if already held
; Clobbers:  rax, flags (writes to [rdi])
; ------------------------------------------------------------------------------
asm_spin_trylock:
    mov eax, 1
    xchg eax, [rdi]
    test eax, eax
    setz al
    movzx eax, al

    ret

; ------------------------------------------------------------------------------
; void asm_spin_unlock(uint32_t *lock)
; Input:     rdi = pointer to lock word
; Output:    none; *lock = 0
; Clobbers:  none (flags untouched; writes to [rdi])
; ------------------------------------------------------------------------------
asm_spin_unlock:
    mov dword [rdi], 0

    ret

; ------------------------------------------------------------------------------
; void asm_futex_lock(uint32_t *lock)
; Input:     rdi = pointer to lock word
; Output:    none; *lock = 1 upon acquisition
; Clobbers:  rax, rcx, rsi, rdx, r10, r11, flags (syscall clobbers rcx and r11)
; ------------------------------------------------------------------------------
asm_futex_lock:
    mov ecx, 1
    xor eax, eax
    lock cmpxchg dword [rdi], ecx
    je .done

.retry:
    cmp dword [rdi], 0
    je .acquire

    ; syscall: futex(lock, FUTEX_WAIT, 1, NULL)
    mov eax, SYS_FUTEX
    mov esi, FUTEX_WAIT
    mov edx, 1
    xor r10d, r10d
    syscall

.acquire:
    mov ecx, 1
    xor eax, eax
    lock cmpxchg dword [rdi], ecx
    jne .retry

.done:
    ret

; ------------------------------------------------------------------------------
; void asm_futex_unlock(uint32_t *lock)
; Input:     rdi = pointer to lock word
; Output:    none; *lock = 0
; Clobbers:  rax, rcx, rsi, rdx, r11 (flags untouched; writes to [rdi])
; ------------------------------------------------------------------------------
asm_futex_unlock:
    mov dword [rdi], 0

    ; syscall: futex(lock, FUTEX_WAKE, 1)
    mov eax, SYS_FUTEX
    mov esi, FUTEX_WAKE
    mov edx, 1
    syscall

    ret

section .note.GNU-stack noalloc noexec nowrite progbits

Both unlock functions clear the lock word with a plain mov dword [rdi], 0 without a lock prefix, and that is completely sound. Under x86-64 TSO, stores are already ordered after all preceding loads and stores inside the critical section, making release semantics free at the store instruction level.

Instruction-by-instruction breakdown of acquiring the spinlock:

  • mov eax, 1 loads the “held” state into the accumulator;
  • xchg eax, [rdi] atomically swaps it with memory and returns the previous lock value in eax;
  • test eax, eax checks whether the lock was free: zero means we acquired it;
  • pause inside the wait loop reduces coherency-bus traffic and hints to a hyper-threaded core that the thread is spinning;
  • cmp dword [rdi], 0 polls the lock read-only so we don’t steal exclusive cache-line ownership from the holder on every spin iteration.

Looking at the machine-code bytes makes it obvious where the f0 prefix is emitted and where it isn’t:

0000000000000005 <asm_spin_lock.retry>:
   5:	87 07                	xchg   DWORD PTR [rdi],eax
0000000000000038 <asm_futex_lock+0x7>:
  38:	f0 0f b1 0f          	lock cmpxchg DWORD PTR [rdi],ecx

xchg with memory has no f0 byte—it asserts the bus/cache lock implicitly by definition. For cmpxchg, the lock prefix is mandatory: without it, the compare and store fall apart into separate non-atomic steps.

lock cmpxchg implements CAS. The same pattern shows up at the OS boundary: open with O_CREAT|O_EXCL checks and creates a file in one atomic VFS operation, whereas pairing access() and open() leaves a TOCTOU window where the file can be swapped underneath you.

Spinlocks shine on tiny critical sections, but waste CPU cycles when waiting gets long. That brings us to futex.

futex: A Syscall Only When Sleeping

A futex isn’t a kernel object—it is a syscall operating on an ordinary 32-bit word in user memory. The fast path stays entirely in user space:

  • lock cmpxchg attempts to transition the word from 0 to 1;
  • if already held, the thread calls futex(FUTEX_WAIT, 1) to sleep: passing the expected value 1 prevents lost wakeups because the kernel atomically checks *lock == 1 before putting the thread to sleep and returns immediately if the holder has already unlocked it;
  • unlocking writes 0 and calls futex(FUTEX_WAKE) to wake one waiter.

In our testbed, the critical section is tiny, so contention is rare. strace reveals the opposite of what intuition expects: almost all syscalls go to waking, not sleeping.

$ strace -f -e trace=futex ./build/atomics_test 2>&1 | grep -c 'FUTEX_WAKE,'
4000
$ strace -f -e trace=futex ./build/atomics_test 2>&1 | grep -c 'FUTEX_WAIT,'
1

The FUTEX_WAIT count depends on scheduler timing: across repeated runs it typically varies from 0 to 2. What never changes is the 4,000 wake calls for 4,000 acquisitions: asm_futex_unlock calls into the kernel on every release, even when no threads are waiting. Production mutexes therefore track a waiter state or count in the lock word and only invoke FUTEX_WAKE when waiters exist; our pedagogical implementation makes those 4,000 extra kernel crossings, clearly exposing the cost of an unconditional FUTEX_WAKE.

The -f flag in both commands tells strace to follow child threads spawned via clone, not just the main thread. Without -f, futex calls made by worker threads wouldn’t appear in the trace because the thread releasing the lock is the one issuing the wake.

TLS: Every Thread Gets Its Own Word

An ordinary global variable is shared across all threads. A thread-local variable lives in .tbss and receives a separate per-thread instance.

tls_demo.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; tls_demo.asm — thread-local variable in .tbss addressed via fs base.

default rel

section .tbss
    align 8
    global tls_counter
    tls_counter: resq 1

section .text
    global asm_tls_bump
    global asm_tls_get

; ------------------------------------------------------------------------------
; void asm_tls_bump(void)
; Input:     none
; Output:    none; increments the current thread's counter by 1
; Clobbers:  rax, flags (caller-saved; writes to TLS counter)
; ------------------------------------------------------------------------------
asm_tls_bump:
    mov rax, [rel tls_counter wrt ..gottpoff]
    inc qword [fs:rax]

    ret

; ------------------------------------------------------------------------------
; uint64_t asm_tls_get(void)
; Input:     none
; Output:    rax = current thread's counter value
; Clobbers:  rax (caller-saved; flags untouched)
; ------------------------------------------------------------------------------
asm_tls_get:
    mov rax, [rel tls_counter wrt ..gottpoff]
    mov rax, [fs:rax]

    ret

section .note.GNU-stack noalloc noexec nowrite progbits

Accessing TLS takes two instructions:

  • mov rax, [rel tls_counter wrt ..gottpoff] loads the TLS offset from the GOT: [rel ...] addresses the table slot RIP-relatively, while wrt ..gottpoff emits an R_X86_64_GOTTPOFF relocation. The dynamic linker populates that slot not with an address, but with the variable’s offset relative to the fs segment base;
  • inc qword [fs:rax] increments the word at “thread base + offset”: in 64-bit long mode, the fs segment base points to the current thread’s Thread Control Block.

fs is not a general-purpose register—it holds a hidden segment base managed by the runtime and kernel across context switches. The .tbss section takes zero bytes in the ELF file on disk; each thread gets its own zero-initialized copy. In the symbol table, it shows up with type TLS:

Thread 0: fs_base_0 + offset (< 0) ──► [ copy 0: tls_counter ]
Thread 1: fs_base_1 + offset (< 0) ──► [ copy 1: tls_counter ]

In ELF on x86-64, static TLS variables sit below the Thread Control Block pointer at fs:0, which is why R_X86_64_GOTTPOFF resolves to a negative offset in rax (appearing in GDB as something like 0xfffffffffffffff8).

$ readelf -sW build/tls_demo.o | grep tls_counter
     8: 0000000000000000     0 TLS     GLOBAL DEFAULT    1 tls_counter
$ readelf -rW build/tls_demo.o | grep GOTTPOFF | head -1
0000000000000003  0000000800000016 R_X86_64_GOTTPOFF      0000000000000000 tls_counter - 4

TLS in the Type column denotes a thread-local template rather than a single global variable: every thread gets its own instance at the same offset from its fs base. A size of zero in .tbss is normal here—the section is NOBITS and occupies no file space, while the runtime loader/threading library allocates space for each thread’s copy.

Four threads performing 1,000 increments each end up with 1000 in their own copies, while main still sees 0 in its separate instance:

tls: per-thread 1000, main 0

False Sharing

Two completely independent variables can accidentally land on the same 64-byte cache line. When that happens, cores constantly bounce exclusive ownership of the line back and forth even though they never touch the same bytes. The harness compares two layouts: two adjacent uint64_t fields vs. the same fields padded 64 bytes apart.

$ ./build/atomics_test | grep 'false sharing'
false sharing: packed=6187489 ns padded=1062165 ns

Eliminating false sharing comes down to alignment and padding: adding pad[56] pushes the second counter onto its own cache line, cutting runtime from over six million nanoseconds down to one.

packed:  [ left 8 B | right 8 B ]             ── both in one 64-byte line:
                                                 cores 0 and 1 fight for ownership

padded:  [ left 8 B | pad[56] ]               ── line A (core 0, Modified)
         [ right 8 B ]                        ── line B (core 1, Modified)

Terminal Verification

$ make test
23-cpu-atomics: spin/futex/TLS OK
$ ./build/atomics_test
race: plain 400000 -> 199497
race: locked 400000
trylock: busy=0 free=1
futex: 4000
tls: per-thread 1000, main 0
false sharing: packed=6187489 ns padded=1062165 ns
atomics: ok

Under the spinlock, all 400,000 increments reach the counter, trylock returns 0 when held and 1 when free, and both the futex lock and TLS counters report exact totals.

Common Failure Modes

  1. Believing add [counter], 1 is atomic.
    Symptom: Four threads performed 100,000 increments each, yet the counter ended at 199497 instead of 400000.
    Cause: Without a lock prefix, the instruction splits internally into load, add, and store, allowing another core to steal the line in between.
    Fix: Protect the counter with a spinlock, lock xadd, or a lock cmpxchg loop.

  2. Thinking xchg with memory needs an explicit lock prefix.
    Symptom: In the disassembly, xchg DWORD PTR [rdi],eax encodes as 87 07, with no f0 byte.
    Cause: Any xchg with a memory operand implicitly locks the cache line regardless of prefixes.
    Fix: Do not prepend lock to xchg; reserve the explicit prefix for cmpxchg, xadd, and memory add/sub.

  3. Assuming futex enters the kernel on every lock acquisition.
    Symptom: 4,000 lock cycles produced 4,000 FUTEX_WAKE syscalls and only rare FUTEX_WAIT calls (1 in the run above, typically 0–2 depending on scheduling).
    Cause: The lock cmpxchg fast path stays in userspace, while our asm_futex_unlock calls FUTEX_WAKE unconditionally.
    Fix: Track whether waiters exist before issuing FUTEX_WAKE, or use a standard mutex implementation that avoids waking when uncontended.

  4. Assuming adjacent variables don’t interfere with each other.
    Symptom: Packed counters took 6,187,489 ns vs. 1,062,165 ns when padded 64 bytes apart.
    Cause: Writing to any byte in a cache line requires exclusive ownership of the entire 64-byte line, causing cores to ping-pong it back and forth.
    Fix: Separate hot per-thread fields by 64 bytes or align structs to cache-line boundaries.

Lab

Goal. Implement int asm_cas_u32(uint32_t *p, uint32_t expected, uint32_t desired) and build a lock-free counter on top of it.

Contract.

  • Inputs: rdi = word pointer, esi = expected value, edx = desired value.
  • Output: eax = 1 if the swap succeeded, 0 if memory held a different value.
  • Must use a single lock cmpxchg instruction plus transferring ZF into eax.
  • The C99 test harness spawns two threads, each performing 200,000 successful CAS increments in a retry loop.

Acceptance criteria.

  1. make test passes with a final counter of 400,000.
  2. objdump -d -M intel shows lock cmpxchg and sete.
  3. make leaks reports no ASan errors.
Hints, expected output, and walkthrough

cmpxchg always compares memory against eax, so move expected into eax first. After the instruction, ZF = 1 indicates the swap succeeded; sete al followed by movzx eax, al converts ZF into 0 or 1.

asm_cas_u32:
    mov eax, esi
    lock cmpxchg dword [rdi], edx
    sete al
    movzx eax, al

    ret

Expected testbed output:

cas: 400000 exact

If the final count is below 400,000, the CAS loop exited on failure instead of retrying. If asm_cas_u32 returns 1 on a mismatch, sete and setne were swapped.

Testbed sources, Makefile, and automated tests for this lesson: lessons/23-cpu-atomics.

Summary

  1. A bare add [mem], 1 without lock is not atomic: another core can claim the cache line between the read and write.
  2. MESI arbitrates exclusive cache-line ownership, and xchg with a memory operand locks the line implicitly.
  3. lock cmpxchg implements CAS and forms the building block for lock-free algorithms.
  4. Spinlocks avoid syscalls altogether, at the cost of burning cycles under long contention.
  5. futex handles the uncontended fast path in user space and enters the kernel only to sleep or wake waiters.
  6. TLS gives every thread its own instance of a variable via an offset from the fs segment base.
Bridge to the next lesson
Synchronization, memory, and vectors have each been covered in isolation. Lesson 24 pulls the whole series together into a compact reference: registers, System V ABI, flags, conditional jumps, SIB addressing, and memory barriers you can keep open while debugging.