Atomics and Compare and Swap

Topics Covered

Atomic Operations

What atomic means

The atomic operations

Atomic flags and counters

The cost of atomics

Atomics are not transactions

Atomics across languages in more detail

Locks are general, but for a single shared word, such as a counter, a flag or a pointer, they are heavier than necessary. Modern processors provide atomic instructions that read and modify one memory location indivisibly, and every mainstream language exposes them as atomic types. This section explains what makes an operation atomic, which atomic operations exist, how they compare to locks in cost, and where they fit in a design.

What atomic means

An operation is atomic if no other thread can observe it half done. Reading or writing an aligned machine word is atomic on all modern processors in the sense that a reader never sees a torn mix of two writes. But an increment, count = count + 1, is three operations, a load, an add and a store, and another thread can interleave between them, which is the lost update of the first lesson. Atomic read modify write instructions perform the load, the modification and the store as one indivisible step. On x86, instructions such as LOCK XADD and LOCK CMPXCHG do this by holding the cache line in the Modified state for the duration of the instruction, so no other core can read or write it in between. On ARM, the same effect comes from load linked and store conditional pairs, LDXR and STXR, which fail and retry if another core touched the line, or from the single instruction atomics added in ARMv8.1, such as LDADD and CAS.

Atomicity in the language sense also includes the compiler. A plain integer variable may be kept in a register, combined with other writes or split into smaller writes by the optimizer. An atomic type tells the compiler that every access is a real memory operation with the specified ordering, which is why plain variables are never a substitute for atomics, even on hardware where aligned stores happen to be atomic.

A plain increment can interleave and lose an update. An atomic fetch and add holds the line from read to write, so both increments count.

The atomic operations

Languages expose a small, consistent set of atomic operations. Load and store read and write the value with a chosen memory ordering. Exchange, also called swap, stores a new value and returns the old one, which is the basis of the simplest spinlock. Fetch and add, fetch and sub, and the bitwise fetch and, fetch or and fetch xor modify the value and return the previous value in one step; they implement counters, reference counts and sets of flags. Compare and swap, also called compare and exchange, stores a new value only if the current value equals an expected value, and reports whether it succeeded; it is the universal building block for lock free algorithms, discussed in the next section.

The names vary. C++ has std::atomic with load, store, exchange, fetch_add and compare_exchange_weak and compare_exchange_strong. Java has AtomicInteger, AtomicLong, AtomicReference and the lower level VarHandle with getAndAdd and compareAndSet. Go has the sync/atomic package with Add, Load, Store, Swap and CompareAndSwap functions and typed wrappers such as atomic.Int64. Rust has AtomicUsize, AtomicBool, AtomicPtr and others in std::sync::atomic, each operation taking an explicit Ordering argument. C11 has the stdatomic.h header with the same operations as C++. Python does not expose atomics directly; with the global interpreter lock, individual bytecodes are effectively atomic, but compound operations such as += on a shared integer are not, and the free threaded builds without the global interpreter lock make this distinction more important.

Atomic flags and counters

The most common uses of atomics are simple. A stop flag, an AtomicBool that one thread sets and others check, tells worker loops to exit; this needs release on the store and acquire on the load if the stopping thread also publishes data, or relaxed ordering if the flag is the only shared state. A statistics counter incremented by many threads uses relaxed fetch and add, because only the final total matters and nobody uses the counter to synchronize other data. A reference count, as in std::shared_ptr or Rust Arc, uses relaxed increments and an acquire release decrement, because the thread that drops the count to zero must see all writes made by other owners before it frees the object. An identifier generator uses fetch and add to hand out unique sequence numbers.

Most atomics in real code are one of four shapes. Each needs a different ordering, from relaxed counters to acquire release refcounts.

The cost of atomics

An uncontended atomic operation costs between a few and about twenty nanoseconds, more than a plain instruction because it must complete with the cache line held exclusively and, on x86, it acts as a full memory barrier, draining the store buffer. That is cheaper than a lock, which needs at least two atomic operations plus the code around them. Under contention, the cost changes completely. Every atomic read modify write needs the cache line in the Modified state on the core performing it, so when many cores update the same atomic, the line bounces between their caches and each operation can take a hundred nanoseconds or more. A single atomic counter hammered by sixty four cores can be slower than each core counting privately and summing occasionally. Contended atomics have the same scaling problem as contended locks, just with a smaller constant.

Atomics are not transactions

The limit of atomics is that each operation covers one memory location. Two atomic operations in sequence are not atomic together. Incrementing an atomic count and then appending to an atomic pointer list leaves a window in which another thread sees the count updated but the list not, or vice versa. Checking an atomic value and then acting on it with a separate operation is the same check then act race as before. Invariants that span several variables still need a lock, a single atomic word that encodes all the state, or a carefully designed lock free algorithm. A good rule is to use atomics for independent single word state and locks for everything that must be consistent across words.

Each step is atomic, but the pair is not. A reader between them sees an inconsistent state.

Atomics across languages in more detail

The way each language presents atomics shapes how they are used. In C++, std::atomic of T works for any trivially copyable type, but only some sizes are lock free; std::atomic of a large struct silently falls back to an internal lock, and is_lock_free or the is_always_lock_free constant tells you which you got. In Java, the java.util.concurrent.atomic classes wrap a volatile field and expose methods for each operation, while VarHandle, added in Java 9, gives the same operations on ordinary fields and array elements with a choice of plain, opaque, acquire release and volatile access modes. In Go, the typed wrappers such as atomic.Int64 and atomic.Pointer, added in Go 1.19, are preferred over the older functions because they prevent accidental plain access to the same field and guarantee 64 bit alignment on 32 bit platforms, where misaligned 64 bit atomics used to panic. In Rust, the type system makes it impossible to share a plain mutable integer between threads at all, so atomics and locks are the only options, and every operation names its ordering explicitly, which makes ordering choices visible in review.

Whatever the language, the guidance is the same: declare the variable as atomic, access it only through atomic operations, and make the intended ordering obvious to the next reader.

Use atomics for single words

Atomic instructions make one read modify write indivisible and cost a few nanoseconds when uncontended. They are ideal for flags, counters, ids, reference counts and published pointers. They do not compose: two atomic operations are not atomic together, so state that must stay consistent across several variables still needs a lock or a single atomic word.