8.5 Atomics

CONCURRENCYSTATUS: STABLELEVEL: DEEPREVIEWED: 2026-11-18
Before this page Race Conditions, Mutexes

8.5.1 Motivation

Threads share memory. When two threads write the same location at the same time without synchronization, C, C++ and Rust all leave the result undefined. An atomic operation completes as one indivisible step visible to all threads. Atomics are the foundation of synchronization without locks, and locks themselves are built on them.

8.5.2 The problem

Suppose thread A writes a block of data and then signals “I am done” with a flag. Thread B reads the flag. If it is set, thread B reads the data. What if thread B sees the flag but the data write has not yet arrived? Without explicit ordering, the CPU or compiler can reorder writes. The compiler can write the flag first. On some CPUs, other cores can see the two writes in either order. Thread B then reads stale data.

Mutual exclusion with mutexes solves this by making threads wait. Atomics with the right memory ordering solve it more directly: they state which earlier writes a thread is guaranteed to see once it sees the flag.

8.5.3 Mental model: indivisible operations

An atomic operation is a read, a write, or a read-modify-write that the hardware executes as one indivisible step. A plain variable has no such promise. A value wider than the machine word, or a misaligned one, can be written in two pieces, and the compiler may split, merge, or drop plain loads and stores, since it assumes no other thread is looking. An atomic integer promises that every other thread sees either the old value or the new value, never a partial write.

The cost of an atomic depends on where its cache line is. If the core already holds the line, the operation stays inside that core’s cache. If other cores are using the same line, each operation first has to pull the line over. That is why an uncontended atomic is fast and a contended one is slow.

8.5.4 Mechanism: the hardware layer

Modern CPUs execute compare-and-swap (CAS) and fetch-and-add (FAA) atomically. x86 has both as single instructions (lock cmpxchg and lock xadd), and so has Arm since Armv8.1. Older Arm cores build them from a load-exclusive and store-exclusive pair in a loop that retries if another core wrote the line in between. A CAS takes three values: an address, an expected value, and a new value. The CPU checks whether the address holds the expected value. If yes, it stores the new value and reports success. If no, it reports failure and the value it found. No thread interferes between the check and the store.

In Rust:

use std::sync::atomic::{AtomicUsize, Ordering};

fn main() {
    let counter = AtomicUsize::new(0);

    // Fetch the old value and add 1. The operation is atomic.
    let old = counter.fetch_add(1, Ordering::Relaxed);

    // Load the current value.
    let now = counter.load(Ordering::Relaxed);

    // Compare and swap: set to 5 only if the current value is 3.
    // Returns Ok(previous) on success, Err(actual) if the value had moved on.
    match counter.compare_exchange(3, 5, Ordering::Relaxed, Ordering::Relaxed) {
        Ok(_prev) => { /* the swap happened */ }
        Err(actual) => { /* someone else got there first; actual is what was found */ }
    }
}

The CPU enforces atomicity through the cache-line hierarchy. A cache line is a block of memory, typically 64 bytes, that moves between cores as a unit. For a core to write a value, it must own that cache line exclusively. Before a core executes a compare-and-swap, it asks for exclusive ownership of the line, and the other cores invalidate their copies. The core then holds the line and delays any other core’s request for it until the read-modify-write finishes. Intel’s manuals call this cache locking: for a value inside one cache line of ordinary memory, holding the line, not locking the memory bus, is what makes the operation atomic on x86 cores since the P6.

8.5.5 Memory ordering: the hard part

Atomicity alone is not enough. In the flag-and-data scenario, thread A needs every store to the data block to be visible to any thread that sees the flag. Thread B needs its reads of the data to happen after its read of the flag. These guarantees come from memory ordering.

CPUs reorder memory operations for performance, and they differ in how much. For ordinary write-back memory, an x86 core keeps its stores in program order. The one reordering other cores can observe is a later load completing before an earlier store, to a different address, has left the core’s store buffer: the x86-TSO model of Sewell and colleagues <https://www.cl.cam.ac.uk/~pes20/weakmemory/cacm.pdf>. Arm and POWER cores allow much more. Loads and stores to different addresses can be reordered in every combination unless a dependency or a barrier prevents it. A compiler can reorder almost anything. Without explicit ordering, there is no order.

Every atomic operation in Rust takes an Ordering argument. C11 and C++11 accept one too and default to sequential consistency when it is left out. Rust’s orderings follow the C++20 memory model. The argument says what the operation must order, and the compiler turns that into barriers or special instructions where the CPU needs them.

Relaxed ordering gives atomicity only and orders nothing else. Other threads can see a relaxed store before they see writes the code made earlier. Use it only when you need atomicity but not synchronization. A global counter with independent increments is safe. A flag that coordinates access is not.

Acquire and Release come in pairs. If an Acquire load reads the value written by a Release store, the loading thread sees every write the storing thread made before that store. The acquiring thread cannot move any subsequent operation before the acquire. The releasing thread cannot move any prior operation after the release. These are one-directional barriers.

SeqCst (sequentially consistent) ordering adds one more promise to Acquire and Release: all SeqCst operations fall into a single total order that every thread agrees on, as if they ran on one core. It is the easiest ordering to reason about, though it does not repair an algorithm that is wrong in other ways. Its cost depends on the CPU. On x86, Acquire loads, Release stores and SeqCst loads are all plain moves, and a SeqCst store needs a locked xchg (or a plain store followed by mfence). On 64-bit Arm, SeqCst loads and stores use the same ldar and stlr instructions as Acquire and Release (the C/C++11 mappings <https://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html>).

Here is the classic flag-and-data example:

use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread;

static DATA: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)];
static READY: AtomicBool = AtomicBool::new(false);

fn main() {
    thread::scope(|s| {
        // Thread A: write the data, then set the flag.
        s.spawn(|| {
            DATA[0].store(42, Ordering::Relaxed);
            DATA[1].store(99, Ordering::Relaxed);
            READY.store(true, Ordering::Release);
        });

        // Thread B: read the flag, then read the data.
        s.spawn(|| {
            if READY.load(Ordering::Acquire) {
                // If B saw the flag, this prints 42 and 99.
                let a = DATA[0].load(Ordering::Relaxed);
                let b = DATA[1].load(Ordering::Relaxed);
                println!("Data: {a} {b}");
            }
        });
    });
}

If thread B’s Acquire load reads the true that thread A’s Release store wrote, every write thread A made before that store, including both data stores, happens before thread B’s reads that follow the load. Safe Rust will not let two threads touch a plain array, so the data is atomic too, and Relaxed is enough for it because the flag carries the ordering. Only one Release-Acquire pair is necessary. If both threads use SeqCst, the program is also correct, and on some CPUs slower.

thread A thread B data = 42 store(flag, Release) load(flag, Acquire) sees flag, reads 42 happens-before

When thread B’s Acquire load sees the flag that thread A’s Release store wrote, everything A did before the store is visible to B after the load.

8.5.6 Cost: contention and false sharing

An uncontended atomic is fast. One core owns the cache line and executes the operation. A Relaxed load or store costs the same as a plain one on x86 and Arm. A read-modify-write such as fetch_add costs more even uncontended, partly because on x86 the locked instruction also drains the core’s store buffer. David, Guerraoui and Trigonakis <https://doi.org/10.1145/2517349.2522714> measured such operations at about 20 cycles on their 2013 multi-socket servers.

A contended atomic is expensive. Multiple cores compete for the same cache line. Each core that wants to execute an atomic operation must wait for exclusive access. The cache line bounces between cores. In the same study, an atomic operation on a line that another core held modified cost about 120 cycles on the same Intel socket and up to about 430 cycles across Intel sockets, and about 110 cycles on one AMD die and up to about 300 cycles across AMD sockets. At high contention, threads mostly wait for cache-line ownership, not for the operation itself.

False sharing makes contention worse. Suppose two threads each maintain their own counter in separate variables. If those variables land on the same cache line, they are false sharers. One thread’s atomic fetch-and-add invalidates the other thread’s cache line copy. The other thread stalls. Padding variables to different cache lines solves this but wastes memory.

A counter that one core updates with a Relaxed fetch_add stays in that core’s cache. Spread the same increments across several cores and each increment first has to win the line, so the total rate stops growing with the number of cores. On the multi-socket machines in the same study, throughput on one shared location fell steeply as soon as a second core used it.

core 0 fetch_add core 1 fetch_add one cache line 64 bytes, one owner at a time ownership moves and moves back Every atomic write needs exclusive ownership, so the line ping-pongs between cores. Uncontended, the operation takes a few nanoseconds; contended, it costs a coherence round trip.

Two cores running fetch_add on the same location pass one cache line back and forth, and each handoff is a coherence round trip.

8.5.7 Atomic reference counting

Reference counting is a form of garbage collection. When an object is no longer referenced, it is freed. Every time a thread copies a reference, the count increments. Every time a reference goes out of scope, the count decrements. If the count reaches zero, the object is freed.

With no threading, this is cheap. Rust’s Rc (reference count) is implemented with plain integers. Increments and decrements are a few CPU cycles.

With threading, every reference count is a potential bottleneck. Rust’s Arc (atomic reference count) uses atomics: Arc::clone is a Relaxed fetch_add, and dropping an Arc is a Release fetch_sub, followed by an Acquire fence when the count reaches zero. With one thread, the line stays in that core’s cache and the cost is the atomic instruction alone. With many threads sharing the same Arc, the reference count becomes a contended atomic, and every clone and drop on another core has to pull the cache line over first.

CPython’s free-threaded build handles this case with biased reference counting, a technique from Choi, Shull and Torrellas <https://doi.org/10.1145/3243176.3243195> (PACT 2018) that PEP 703 adopted. Each object records the thread that created it. That thread updates a local count with plain instructions, and every other thread updates a separate shared count with atomics. The PEP rests this on the observation that most objects are only accessed by a single thread, even in multi-threaded programs, so most updates avoid atomics. It is one option R could borrow.

8.5.8 Mechanism: cache-line detail

Each cache tracks a state for every line it holds. In the MESI protocol the states are Modified, Exclusive, Shared and Invalid. A core can write a line only when it holds it Modified or Exclusive, which means no other cache has a valid copy. Some processors extend the protocol, for example AMD’s MOESI, which adds an Owned state.

Before a core executes an atomic store, it acquires exclusive ownership. Before a compare-and-swap, it acquires exclusive ownership, runs the operation, and holds ownership until another core requests the line. In the sequence below, “the arbiter” stands for whatever tracks which cache holds each line: a broadcast to all caches on some machines, a directory on others.

Here is the sequence for a contended fetch-and-add:

  1. Core A wants to execute fetch-and-add. It signals the cache arbiter: “I need exclusive access to address X.”
  2. Core B currently owns the line. The arbiter sends a request: “Invalidate your copy of X.”
  3. Core B acknowledges. The line is now invalid at B.
  4. The arbiter grants exclusive access to A.
  5. Core A executes fetch-and-add and holds the line.
  6. Core C now wants fetch-and-add at X. The arbiter sends: “Give up exclusive access.”
  7. Core A acknowledges and invalidates its copy.
  8. The arbiter grants exclusive access to C.

Each handoff is a message in the interconnect. With many cores contending, these messages can saturate the interconnect and stall the cores.

Memory ordering is enforced mostly inside each core, not by this protocol. On x86 the store buffer already drains in program order, so a Release store needs no extra instruction, while a locked instruction or mfence waits for the store buffer to drain. On Arm, a Release store (stlr) does not become visible until every earlier load and store has, and an Acquire load (ldar) holds back every later load and store until it completes.

8.5.9 The R connection: SEXP header mutations

R’s SEXPREC structure embeds reference counting and garbage collection bookkeeping directly in the object header. Since R 4.0 the 16-bit field that once held NAMED holds a reference count, which R uses to decide when it must copy an object before modifying it. The mark bit records whether the collector found the object reachable. The count changes whenever a binding or a list slot starts or stops pointing at the object, and the collector writes the mark bit on every collection, including on objects the program only reads.

SEXP reference counts and mark bits are plain non-atomic fields today. Making them atomic would put an atomic instruction on every reference-count update, and a contended one whenever two threads touch the same object.

Single-threaded R pays nothing for this. Multithreaded R that lets threads share objects faces a choice: either every thread takes a lock before touching any object header, or the header fields become atomics. Both are slow, which is why free-threading a dynamic language runtime is expensive. The third option is not to share objects at all.

CPython’s free-threaded build faced the same constraint, with a reference count in every object header. Making every reference count atomic would tax single-threaded code, which is why it uses the biased scheme described above.

threaded-r and r-in-rust both take the third option for now: an object belongs to one interpreter, and only that interpreter’s thread touches it. The one exception is the small immortal arena in threaded-r, whose objects every interpreter reads and no collector or count update writes.

8.5.10 The hard part

Atomics appear simple but compose poorly. The operations are correct, but the interaction of many atomics creates complexity.

Liveness and deadlock. A lock can deadlock if two threads hold locks in opposite order. A single CAS retry loop cannot: when one thread’s CAS fails, another thread’s succeeded, so the system as a whole makes progress. One thread can still lose over and over under heavy contention and starve, and anything built from atomics, such as a spinlock, can deadlock just as a mutex can.

ABA problem. Thread A reads an atomic value, gets A. Thread B changes it to B and back to A. Thread A’s CAS thinks nothing changed. But the intervening mutation can have freed memory, leaked resources, or changed invariants. The usual defenses are a version counter stored next to the value, so the CAS sees the change, or a memory reclamation scheme such as hazard pointers or epochs (Rust’s crossbeam-epoch) that keeps memory from being reused while another thread may still hold its address.

Ordering intuition. Memory ordering is non-intuitive. Many programmers incorrectly use Relaxed when they need Acquire or Release. ThreadSanitizer catches an ordering that is too weak when it leaves a plain variable unprotected, since that shows up as a data race. It does not catch a wrong result among atomics that are each race-free.

Performance assumptions. An uncontended atomic is fast. A contended one is slow. But “contended” depends on thread count, hardware, and cache behavior. An optimization that works on a 4-core laptop can fail on a 64-core server.

8.5.11 Tradeoffs

Atomics vs locks. An atomic makes one operation on one memory location indivisible. A lock makes a whole critical section indivisible, across every field it covers. Use atomics for small, hot data like counters and flags. Use locks when an update spans several values.

Ordering strength. Relaxed orders nothing beyond the operation itself. SeqCst is the easiest to reason about and, on some CPUs, the slowest. Acquire and Release sit between them. Choose the weakest ordering that is correct for the algorithm, which means understanding the algorithm, the hard part.

Reference counting. Arc pays an atomic operation on every clone and drop. Code that would clone an Arc millions of times per second across threads usually clones it less: once per thread, or not at all, lending &T to scoped threads (std::thread::scope).

8.5.12 Other systems

The Rust standard library provides std::sync::atomic with AtomicBool, AtomicUsize, and other types. Its orderings follow the C++20 memory model, without the consume ordering. The Rustonomicon atomics chapter explains them.

C++11 provides std::atomic in <atomic>, and C11 provides _Atomic types and functions in <stdatomic.h>. Rust took its memory model from C++, so the orderings mean the same thing in all three.

Java provides java.util.concurrent.atomic with AtomicInteger and similar classes. Its memory model dates from JSR-133 (2004), before C++11. Java 9’s VarHandle added access modes that line up with the C++ ones: opaque with relaxed, acquire and release with acquire and release, and volatile with sequential consistency (Doug Lea’s guide <https://gee.cs.oswego.edu/dl/html/j9mm.html>).

With the GIL held, CPython updates reference counts with plain increments, since only one thread runs Python code at a time. The free-threaded build, available since CPython 3.13, uses the biased reference counting described above so that most updates still avoid atomics.

8.5.13 Relevance to my work

threaded-r uses atomics in a few narrow places. GNU R handed out connection ids from a plain counter, so two interpreters creating connections at once could get the same id, and one interpreter’s finalizer could then close another’s live connection. An atomic fetch_add fixed that without adding a lock to every connection (patch 0091). R_InterpreterState has one atomic field, cancel_requested, which another thread sets to cancel an interpreter (patch 0098). No SEXP field is atomic, because objects belong to one interpreter.

r-in-rust has almost no atomics. Each interpreter is one value owned by one thread, so its heap needs none. The exception sits in the C API layer: R’s exported R_interrupts_pending and R_interrupts_suspended are AtomicI32 statics, the same size and alignment as the C int that packages expect, accessed with Relaxed ordering.

8.5.14 Open questions

Can biased reference counting reduce the cost of Arc in Rust? Does it require language changes, or only a new library type?

Can R adopt a per-interpreter heap and defer SEXPREC field access to interpreter-owned critical sections, avoiding atomics entirely?

Further reading

  • The Rust Programming Language, chapter 16.3, Shared-State Concurrency <https://doc.rust-lang.org/book/ch16-03-shared-state.html>. Mutex and Arc.
  • The Rustonomicon, Atomics <https://doc.rust-lang.org/nomicon/atomics.html>.
  • Jeff Preshing, Acquire and Release Semantics <https://preshing.com/20120913/acquire-and-release-semantics/>, blog post, 2012.
  • Jeff Preshing, The Happens-Before Relation <https://preshing.com/20130702/the-happens-before-relation/>, blog post, 2013.
  • PEP 703: Making the Global Interpreter Lock Optional in CPython <https://peps.python.org/pep-0703/>.
  • C11 standard, ISO/IEC 9899:2011, section 7.17, Atomics <stdatomic.h>. The final public draft is N1570 <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf>.
  • C++11 standard, ISO/IEC 14882:2011, clause 29, Atomic operations library. N3337 <https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf> is the working draft published right after it, with editorial changes only.
  • The Linux kernel memory model <https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/tools/memory-model>, in tools/memory-model of the kernel source: a formal model of the ordering the kernel relies on, with plain-text explanations in its Documentation folder.
  • Herb Sutter, atomic Weapons: The C++ Memory Model and Modern Hardware <https://herbsutter.com/2013/02/11/atomic-weapons-the-c-memory-model-and-modern-hardware/>, a two-part talk from C++ and Beyond 2012, with video and slides.

Where this appears

Where to go next

Back to top