Programming Search⌘K

Conceptcore

Atomic operations and memory models

Also called atomics, atomic operations, memory model, memory ordering, compare-and-swap, CAS, happens-before, sequential consistency, acquire and release.

An atomic operation reads or changes shared memory in one indivisible step. A memory model states which writes of other threads a read can see, and which orders of memory access a program can rely on.

Applies to
core-languages

Idea

When two threads change the same variable, an operation that looks like one step can be several steps. counter += 1 reads the value, adds one, and writes the result. If two threads read the same old value before either one writes, one of the increments is lost. An atomic operation is a read, a write or a read-modify-write that other threads cannot see half done: it occurs completely or not at all. A memory model is the set of rules that says which values a read in one thread can see, when other threads write to memory at the same time:

counter = 0

a = counter
b = counter
counter = a + 1
counter = b + 1
print("two increments, interleaved:", counter)

import threading

counter = 0
lock = threading.Lock()


def work():
    global counter
    for _ in range(100_000):
        with lock:
            counter += 1


threads = [threading.Thread(target=work) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("with a lock:", counter)
Output
two increments, interleaved: 1
with a lock: 400000

The first part shows by hand the order in which two threads can run the steps of counter += 1. The second part makes the steps indivisible with a lock. An atomic instruction does the same for one memory word, with no lock: the processor does the read, the change and the write as one operation.

How it works

Indivisible operations. Processors provide atomic loads and stores of aligned words, and atomic read-modify-write instructions, such as fetch-and-add, exchange, and compare-and-swap. A compare-and-swap writes a new value only if the variable still holds an expected value, and it reports if it succeeded. With it, a program can make any update atomic: read the value, compute the new value, and retry if another thread changed the variable in the meantime. Languages expose these instructions as atomic types. Java describes its atomic classes as "a small toolkit of classes that support lock-free thread-safe programming on single variables."1 C# Interlocked "provides atomic operations for variables that are shared by multiple threads."2

Reordering. Atomicity is not enough. Compilers reorder memory accesses that are independent in one thread, and processors with store buffers and caches make writes visible to other cores in a different order from the program order. cppreference states: "Absent any constraints on a multi-core system, when multiple threads simultaneously read and write to several variables, one thread can observe the values change in an order different from the order another thread wrote them."3 A thread that writes data and then sets a flag can have the flag seen first.

Sequential consistency. The simplest model is the one that Leslie Lamport defined in 1979: "the result of any execution is the same as if the operations of all the processors were executed in some sequential order, and the operations of each individual processor appear in this sequence in the order specified by its program."4 Real hardware does not give this model for plain accesses, because it would make every memory access slow.

Data races and the DRF guarantee. Language memory models solve the problem with a contract. A data race is two accesses to the same location from different threads, at least one of them a write, that are not ordered by synchronization. The Java specification states: "When a program contains two conflicting accesses that are not ordered by a happens-before relationship, it is said to contain a data race."5 In return for no data races, the language gives sequential consistency: "If a program is correctly synchronized, then all executions of the program will appear to be sequentially consistent".5 C and C++ go further, and a data race is undefined behavior. Go defines a data race in the same way, "unless all the accesses involved are atomic data accesses as provided by the sync/atomic package."6 See data races.

Happens-before. Synchronization operations create the order between threads. A release store to an atomic variable and an acquire load that reads the stored value are the basic pair. cppreference states that then "the store in thread A synchronizes-with the load in thread B. All memory writes (including non-atomic and relaxed atomic) that happened-before the atomic store in thread A also happened-before the atomic load in thread B."3 Locks, thread start and join, and channel operations create the same edges.

Memory orders. C, C++ and Rust let each atomic operation choose its order. relaxed operations "are not synchronization operations; they do not impose an order among concurrent memory accesses. They only guarantee atomicity and modification order consistency."3 release and acquire give the pairing above. seq_cst, the default, also gives "a single total order ... in which all threads observe all modifications in the same order".3 Java, Go and JavaScript give sequentially consistent atomics only, which is simpler and in most programs fast enough.

In languages

LanguageVerdictNote
PythonAbsent
C++Standard library
JavaStandard library
CStandard library
C#Standard library
JavaScriptNative
TypeScriptNativeAs JavaScript, with Atomics on typed arrays over a SharedArrayBuffer.
GoStandard library
RustStandard library
KotlinStandard libraryOn the JVM, Kotlin uses the classes of java.util.concurrent.atomic, such as AtomicInteger and AtomicReference; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyThe database engine makes each statement atomic, and transactions and isolation levels control what concurrent sessions see.
BashDoes not applyBash processes do not share memory with each other. Alternative: Flock serializes access to a shared file, and mkdir is an atomic test-and-create for a lock directory.
PowerShellStandard libraryScripts can call the .NET class System.Threading.Interlocked on a variable that runspaces share; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no shared memory.
CSSDoes not applyCSS has no shared memory.
Regular expressionsDoes not applyA regular expression has no shared memory.
Language Verdict Mechanism
Python absent threading.Lock, the GIL, queues
JavaScript native Atomics on a SharedArrayBuffer
TypeScript native as JavaScript
Java stdlib java.util.concurrent.atomic, volatile, VarHandle
Kotlin stdlib the Java atomic classes on the JVM
C# stdlib Interlocked, Volatile, volatile fields
Go stdlib sync/atomic types, all sequentially consistent
Rust stdlib std::sync::atomic types with an Ordering per operation
C stdlib _Atomic, <stdatomic.h>, memory orders
C++ stdlib std::atomic, std::atomic_ref, std::memory_order
Bash n/a no shared memory; flock for files
PowerShell stdlib [System.Threading.Interlocked]
SQL n/a atomic statements and transactions
Regex, HTML, CSS n/a no shared memory

C and C++ define the reference model. std::atomic<T> makes concurrent access well defined: "If one thread writes to an atomic object while another thread reads from it, the behavior is well-defined".7 C11 has the same operations in <stdatomic.h>.8 Rust uses the C++ model: "Atomic types provide primitive shared-memory communication between threads, and are the building blocks of other concurrent types."9

Java has atomic classes and volatile fields, and the Java memory model in chapter 17 of the specification defines happens-before.5 C# has Interlocked and Volatile.2

Go has sync/atomic, and "all the atomic operations executed in a program behave as though executed in some sequentially consistent order." The memory model adds that this has "the same semantics as C++'s sequentially consistent atomics and Java's volatile variables."6 The same document also says: "If you must read the rest of this document to understand the behavior of your program, you are being too clever. Don't be clever."6

JavaScript shares memory between workers only through a SharedArrayBuffer. "The Atomics namespace object contains static methods for carrying out atomic operations."10

Python has no atomic types. The global interpreter lock protects the interpreter, not the programs that run on it. The free-threaded build, in which the GIL is disabled, keeps the same guarantees for built-in types: "Built-in types like dict, list, and set use internal locks to protect against concurrent modifications in ways that behave similarly to the GIL."11 A program that needs a read-modify-write step to be atomic uses a lock.

PythonGitHub
import threading
from collections import Counter
from concurrent.futures import ThreadPoolExecutor


class SafeCounter:
    def __init__(self):
        self._value = 0
        self._lock = threading.Lock()

    def add(self, n=1):
        with self._lock:
            self._value += n
            return self._value

    @property
    def value(self):
        with self._lock:
            return self._value


counter = SafeCounter()


def work(_):
    for _ in range(50_000):
        counter.add()


with ThreadPoolExecutor(max_workers=4) as pool:
    list(pool.map(work, range(4)))
print(counter.value)


def count_words(text):
    return Counter(text.split())


with ThreadPoolExecutor() as pool:
    parts = pool.map(count_words, ["a b a", "b c", "a"])
print(sum(parts, Counter()))
Output
200000
Counter({'a': 3, 'b': 2, 'c': 1})
  • Verdict: absent. Python has no atomic integer type and no memory-order API. A threading.Lock makes a read-modify-write sequence indivisible.
  • The global interpreter lock makes single operations on built-in types safe in the default build, and the free-threaded build uses internal locks to keep similar behavior. A sequence such as counter += 1 is still several steps, and other threads can run between them.
  • The second part avoids shared state: each thread counts its own part, and the main thread combines the results.
#include <atomic>
#include <iostream>
#include <string>
#include <thread>
#include <vector>

std::atomic<int> hits{0};
std::string message;
std::atomic<bool> ready{false};

int main() {
    {
        std::vector<std::jthread> workers;
        for (int t = 0; t < 4; ++t) {
            workers.emplace_back([] {
                for (int i = 0; i < 100000; ++i) {
                    hits.fetch_add(1, std::memory_order_relaxed);
                }
            });
        }
    }
    std::cout << hits.load() << "\n";

    int expected = 400000;
    bool swapped = hits.compare_exchange_strong(expected, 0);
    std::cout << std::boolalpha << swapped << " " << hits.load() << "\n";

    std::jthread producer([] {
        message = "hello";
        ready.store(true, std::memory_order_release);
    });
    while (!ready.load(std::memory_order_acquire)) {
    }
    std::cout << message << "\n";
}
Output
400000
true 0
hello
  • Verdict: stdlib. std::atomic<T> makes loads, stores and read-modify-write operations atomic, and each operation can take a std::memory_order. The default is memory_order_seq_cst.
  • The release store and the acquire load make the plain write to message visible to the main thread. Without them, the access to message would be a data race.
  • std::atomic_ref gives atomic access to an object that is not declared atomic, for example an element of a large array.
#include <iostream>
#include <thread>

int hits = 0;

int main() {
    std::thread a([] { for (int i = 0; i < 100000; ++i) ++hits; });
    std::thread b([] { for (int i = 0; i < 100000; ++i) ++hits; });
    a.join();
    b.join();
    std::cout << hits << "\n";
}

Two threads increment a plain int without synchronization. This is a data race and undefined behavior. In practice, the program often prints a number below 200000, because increments are lost, and an optimizer can also merge the loop into one addition. ThreadSanitizer, -fsanitize=thread, reports the race.

JavaGitHub
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

public class Main {
    static volatile boolean ready;
    static String message;

    public static void main(String[] args) throws Exception {
        AtomicInteger hits = new AtomicInteger();
        LongAdder visits = new LongAdder();
        ExecutorService pool = Executors.newFixedThreadPool(4);
        for (int t = 0; t < 4; t++) {
            pool.submit(() -> {
                for (int i = 0; i < 100_000; i++) {
                    hits.incrementAndGet();
                    visits.increment();
                }
            });
        }
        pool.shutdown();
        pool.awaitTermination(1, TimeUnit.MINUTES);
        System.out.println(hits.get() + " " + visits.sum());

        System.out.println(hits.compareAndSet(400_000, 0) + " " + hits.get());

        Thread producer = new Thread(() -> {
            message = "hello";
            ready = true;
        });
        producer.start();
        while (!ready) {
            Thread.onSpinWait();
        }
        System.out.println(message);
    }
}
Output
400000 400000
true 0
hello
  • Verdict: stdlib. java.util.concurrent.atomic has AtomicInteger, AtomicLong, AtomicReference and the adders. VarHandle gives atomic access with explicit memory order to fields and array elements.
  • A write to a volatile field happens-before every later read of that field. So the write to message before ready = true is visible to the thread that sees ready.
  • LongAdder spreads updates over several cells, so it is faster than one AtomicLong when many threads add at the same time.
#include <pthread.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdio.h>

static atomic_int hits;

static void *work(void *arg) {
    (void)arg;
    for (int i = 0; i < 100000; i++) {
        atomic_fetch_add_explicit(&hits, 1, memory_order_relaxed);
    }
    return NULL;
}

int main(void) {
    pthread_t threads[4];
    for (int t = 0; t < 4; t++) {
        pthread_create(&threads[t], NULL, work, NULL);
    }
    for (int t = 0; t < 4; t++) {
        pthread_join(threads[t], NULL);
    }
    printf("%d\n", atomic_load(&hits));

    int expected = 400000;
    bool swapped = atomic_compare_exchange_strong(&hits, &expected, 0);
    printf("%d %d\n", swapped, atomic_load(&hits));
    return 0;
}
Output
400000
1 0
  • Verdict: stdlib. C11 added the _Atomic qualifier, <stdatomic.h> and the same memory orders as C++. Operations without _explicit use sequentially consistent order.
  • Before C11, programs used compiler builtins, such as the GCC __atomic functions, or platform APIs. volatile does not make an access atomic and does not order other accesses.
int hits = 0;
Parallel.For(0, 4, _ =>
{
    for (int i = 0; i < 100_000; i++)
    {
        Interlocked.Increment(ref hits);
    }
});
Console.WriteLine(hits);

int old = Interlocked.CompareExchange(ref hits, 0, 400_000);
Console.WriteLine($"{old} {hits}");

long largest = 0;
Parallel.ForEach(new long[] { 7, 42, 13 }, value =>
{
    long seen;
    do
    {
        seen = Interlocked.Read(ref largest);
        if (value <= seen) return;
    } while (Interlocked.CompareExchange(ref largest, value, seen) != seen);
});
Console.WriteLine(largest);
Output
400000
400000 0
42
  • Verdict: stdlib. Interlocked has atomic increment, add, exchange and compare-exchange. Volatile.Read and Volatile.Write give acquire and release order.
  • The loop at the end is the usual pattern for an update that has no single atomic method: read the value, compute a new value, and retry if another thread changed it first.
JavaScriptGitHub
import { Worker } from "node:worker_threads";
import { once } from "node:events";

const shared = new Int32Array(new SharedArrayBuffer(4));
const source = `
const { workerData } = require("node:worker_threads");
for (let i = 0; i < 100000; i++) Atomics.add(workerData, 0, 1);
`;

const workers = [1, 2, 3, 4].map(() => new Worker(source, { eval: true, workerData: shared }));
await Promise.all(workers.map((worker) => once(worker, "exit")));
console.log(Atomics.load(shared, 0));

const old = Atomics.compareExchange(shared, 0, 400000, 0);
console.log(old, Atomics.load(shared, 0));
Output
400000
400000 0
  • Verdict: native. Each worker has its own heap, and only a SharedArrayBuffer is shared. The Atomics methods read, write and update its elements atomically, with sequentially consistent order.
  • Atomics.wait and Atomics.notify let a worker sleep until another worker changes a value. Browsers allow shared memory only on pages that are cross-origin isolated.
package main

import (
	"fmt"
	"sync"
	"sync/atomic"
)

func main() {
	var hits atomic.Int64
	var wg sync.WaitGroup
	for range 4 {
		wg.Go(func() {
			for range 100_000 {
				hits.Add(1)
			}
		})
	}
	wg.Wait()
	fmt.Println(hits.Load())

	fmt.Println(hits.CompareAndSwap(400_000, 0), hits.Load())

	var ready atomic.Bool
	var message string
	go func() {
		message = "hello"
		ready.Store(true)
	}()
	for !ready.Load() {
	}
	fmt.Println(message)
}
Output
400000
true 0
hello
  • Verdict: stdlib. sync/atomic has the types Int32, Int64, Uint64, Bool, Pointer[T] and Value. All atomic operations in Go are sequentially consistent, so the write to message before ready.Store is visible after ready.Load returns true.
  • The Go memory model recommends channels and mutexes first. The race detector, go run -race, finds data races at run time.
RustGitHub
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
use std::thread;

fn main() {
    let hits = AtomicUsize::new(0);
    thread::scope(|s| {
        for _ in 0..4 {
            s.spawn(|| {
                for _ in 0..100_000 {
                    hits.fetch_add(1, Ordering::Relaxed);
                }
            });
        }
    });
    println!("{}", hits.load(Ordering::Relaxed));

    let swapped = hits.compare_exchange(400_000, 0, Ordering::AcqRel, Ordering::Acquire);
    println!("{:?} {}", swapped, hits.load(Ordering::Relaxed));

    let data = AtomicU32::new(0);
    let ready = AtomicBool::new(false);
    thread::scope(|s| {
        s.spawn(|| {
            data.store(42, Ordering::Relaxed);
            ready.store(true, Ordering::Release);
        });
        while !ready.load(Ordering::Acquire) {
            std::hint::spin_loop();
        }
        println!("{}", data.load(Ordering::Relaxed));
    });
}
Output
400000
Ok(400000) 0
42
  • Verdict: stdlib. std::sync::atomic has atomic integers, AtomicBool and AtomicPtr. Each operation takes an Ordering, with the same meanings as in C++: Relaxed, Release, Acquire, AcqRel and SeqCst.
  • Safe Rust has no data races. The compiler does not let two threads use a plain variable unless one of them only reads, so shared counters must be atomic or behind a Mutex.
  • A relaxed counter is enough when only the final total matters. The flag needs Release and Acquire, so that the value stored before the flag is visible after the flag.

Locks. A mutex makes a whole block of code atomic. It is built from atomic instructions and from support in the operating system to put waiting threads to sleep.

Lock-free and wait-free algorithms. A lock-free data structure uses compare-and-swap loops so that some thread always makes progress, even if other threads stop. A wait-free structure guarantees progress for every thread. Both are hard to write correctly.

The ABA problem. A compare-and-swap checks only the value. If another thread changes a value from A to B and back to A, the check passes, although the data changed. Version counters and safe memory reclamation schemes, such as hazard pointers and epochs, solve it.

Fences. A fence, or memory barrier, orders accesses without a specific atomic variable. std::atomic_thread_fence and VarHandle.fullFence are examples.

Transactional memory. A transaction makes a block of reads and writes on many locations atomic, and retries the block if another thread changed the same data. Haskell has software transactional memory, and some processors have had hardware support.

Message passing. Channels and actors avoid shared variables, so most code needs no atomics or memory orders.

Pitfalls

Check then act. Two atomic operations are not one atomic operation. A load followed by a store, such as if (x.load() == 0) x.store(1), lets another thread act between them. Use a compare-and-swap or a lock.

volatile in C and C++. volatile stops the compiler from removing or merging accesses, which is for memory-mapped hardware. It does not make an access atomic, and it does not order other accesses. In Java and C#, volatile has a different meaning, and it does give visibility and ordering.

Relaxed order for a flag. A relaxed store to a flag does not publish the data written before it. Use release and acquire, or the default sequentially consistent order.

Tests that pass on x86. x86 processors reorder memory less than ARM and POWER processors. Code with a missing barrier can pass all tests on x86 and fail on ARM. Use the race detector of the language and tools such as ThreadSanitizer.

Contention and false sharing. Many threads that update one atomic variable force the cache line to move between cores, so the update can be much slower than a plain increment. Two variables on the same cache line slow each other down even when they are different variables. Per-thread counters that are summed at the end, such as Java LongAdder, avoid this.

Torn values. A plain access to a value wider than a machine word, such as a 64-bit integer on a 32-bit system or a structure, can be split into parts. Another thread can see half of an old value and half of a new one.

Cost

An atomic load or store with relaxed or acquire and release order often costs the same as a plain access on x86, and a little more on ARM. A read-modify-write instruction or a sequentially consistent store is slower, typically some tens of cycles without contention, because the processor must drain its store buffer and own the cache line. With contention, the cost grows with the number of cores that fight for the line. An atomic operation is still much cheaper than a lock that makes a thread sleep, but it is far more expensive than code that shares nothing.

History

Leslie Lamport defined sequential consistency in 1979.4 Atomic instructions such as test-and-set and compare-and-swap were part of mainframe instruction sets in the 1960s and 1970s. Maurice Herlihy showed in 1991 that compare-and-swap can implement any wait-free object. Java was the first mainstream language with a memory model in its specification, and Jeremy Manson, William Pugh and Sarita Adve revised it in 2004 for Java 5, with happens-before and the guarantee for programs without data races. Hans Boehm and Sarita Adve led the model for C++11, which C11 shares, and which Rust uses. Go published a revised memory model in 2022 that follows the same approach.6

References

  1. java.util.concurrent.atomic package summary, Java SE 25 API documentation, package description
  2. Interlocked Class, .NET API reference, Microsoft Learn, definition
  3. std::memory_order, cppreference.com, Explanation
  4. How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs, L. Lamport, IEEE Transactions on Computers C-28(9), 1979, page 690
  5. The Java Language Specification, Java SE 25 Edition, 17.4.5 Happens-before Order
  6. The Go Memory Model, version of June 6, 2022, Advice, Informal Overview and Atomic Values
  7. std::atomic, cppreference.com, description
  8. Concurrency support library, atomic operations, C, cppreference.com, Atomic operations
  9. Module std::sync::atomic, Rust standard library documentation, Atomic types
  10. Atomics, MDN Web Docs, introduction
  11. Python support for free threading, Python 3.14 documentation, Thread safety

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/3EMVDQ/text.yaml