Section 9.8

Atomic operation

Definition

An atomic operation is an operation on one shared memory location that other threads (instruction sequences sharing one memory) observe as indivisible: they see the location as it was before the operation or after it, never part-way through. Its kinds are the atomic load, which reads; the atomic store, which writes; and the atomic read-modify-write, which reads, computes and writes back as one step. Atomicity §8.3 concerns that one location only. How the operation is ordered against other memory accesses is a separate property, its memory order.

The idea

Two threads count events in one shared counter with the C statement count = count + 1. The processor carries this out in three steps: load the value into a register, add 1, store the result. If both threads load 3 before either stores, both store 4, and one event is lost. Neither thread is wrong on its own; the damage comes from one thread acting between another thread’s steps. This is a race condition §9.2: the result depends on the timing of the threads. The repair is to make the three steps one operation that no thread can split, so that every increment starts from the latest value.

Single reads and writes need the same care. A 32-bit processor writes a 64-bit value as two 32-bit stores, and a reader that runs between them sees half of the old value and half of the new one: a value that nobody ever wrote. An atomic load or store excludes that.

Atomicity settles one question: whether another thread can see a half-finished operation on this location. It leaves a second question open: in which order other threads see this operation and the thread’s other memory accesses. The memory order of the operation settles the second question. Confusing the two is the most common mistake made with atomic operations.

How it works

Hardware provides atomicity in three ways.

The Armv6-M architecture, used by the Cortex-M0, has no exclusive pair. On such a single-core processor a read-modify-write is made atomic toward interrupt handlers §6.12 by masking interrupts, that is, holding them pending, around it. That protects nothing against a second core.

C11, the 2011 edition of the C standard, makes atomic operations part of the language. A variable declared _Atomic int count, or with the equivalent type atomic_int, is an atomic object. Plain reads and writes of it are atomic loads and stores. count++ and count += 1 are atomic read-modify-writes, and library functions such as atomic_fetch_add and atomic_compare_exchange_strong provide the others. Each function has an _explicit form that takes a memory order. The standard defines six memory orders, and three cover most programs:

C11 adds rules that hold for every memory order, relaxed included. All writes to one atomic object fall into a single total order, the object’s modification order. A thread that has read one value of the object never later reads a value that comes earlier in that order. An atomic read-modify-write always reads the last value before its own write in that order, so no other write can fall between its read and its write. Two atomic accesses never form a data race §9.3, C’s name for two accesses to one location by different threads, at least one a write and at least one not atomic, that the happens-before relation §9.10 leaves unordered; a data race gives the program undefined behavior §4.12.

Worked example

A shared counter of type atomic_int holds 3, and threads A and B each add 1. With a read-modify-write:

  1. A runs atomic_fetch_add(&count, 1): it reads 3, writes 3+1=43 + 1 = 4 and returns the old value 3.

  2. B runs the same call: it reads 4, the last value in the modification order, writes 4+1=54 + 1 = 5 and returns 4.

In the other order B receives 3 and A receives 4, but the counter ends at 5 either way, the correct 3+23 + 2.

With two separate atomic operations,

tmp = atomic_load(&count);
atomic_store(&count, tmp + 1);

this order is possible:

  1. A loads 3.

  2. B loads 3.

  3. A stores 3+1=43 + 1 = 4.

  4. B stores 3+1=43 + 1 = 4.

All four operations are atomic and there is no data race, yet the counter ends at 4 and one increment is lost. The C statement count = count + 1 on an atomic object compiles to exactly this load and store, while count += 1 is a single read-modify-write.

A 64-bit counter on a 32-bit processor shows why single accesses matter too. The counter holds 0x00000000FFFFFFFF, which is 4,294,967,295. A plain increment writes 0x0000000100000000, which is 4,294,967,296, as two 32-bit stores. If the low half is stored first, a reader between the two stores sees the new low half 0x00000000 and the old high half 0x00000000, and reads 0. If the high half is stored first, the reader sees 0x00000001FFFFFFFF, which is 8,589,934,591. Neither value was ever the counter’s value. Declared _Atomic, the counter is read and written in one indivisible access, or, where the processor has no such access, through a library routine that may use a hidden lock.

Stated precisely

Let MM be an atomic object in C11. For every memory order, relaxed included:

  1. Indivisibility: every atomic load of MM returns the value that one single write to MM stored, or the value MM was initialized with; never a mixture.

  2. One modification order: all writes to MM form one total order, and a thread that has read a value of MM never reads, later in its own program order, a value that comes earlier in that order.

  3. No lost update: an atomic read-modify-write of MM reads the value immediately before its own write in the modification order.

  4. No data race on MM: two atomic accesses to MM never form a data race.

All four guarantees speak about MM alone. A guarantee about another object XX comes only from memory order. If thread A writes XX and then stores to MM with release order, and thread B’s load of MM with acquire order reads the stored value, the happens-before relation orders A’s write of XX before everything that B does after its load. With relaxed order on either side, nothing about XX follows.

Limits and common mistakes

A sequence of atomic operations is not atomic. A load followed by a store can be split by another thread, as the lost increment above shows. Use one read-modify-write or a compare-and-swap loop. An invariant that spans two locations, such as two counters that must stay equal, needs a lock, a transaction §8.7, or both values packed into one atomic object.

Atomic does not mean lock-free §9.13. C11 lets an implementation build an atomic type on a hidden lock, for example a 64-bit type on a 32-bit processor. The function atomic_is_lock_free and macros such as ATOMIC_LLONG_LOCK_FREE report the implementation’s choice; only atomic_flag is guaranteed to be lock-free. An atomic object built on a hidden lock must not be used from an interrupt handler that may have interrupted the holder of that lock.

An aligned access that the hardware performs in one step is not a C atomic operation. A C program in which two threads access a plain int, at least one of them writing, without synchronization has a data race, and the compiler may split, merge, repeat or remove those accesses.

The volatile qualifier §4.34 does not make an access atomic. It stops the compiler from removing or merging accesses, but it makes no read-modify-write indivisible and orders nothing between threads.

An atomic pointer protects the pointer, not the object it points to. Reading the object’s fields safely needs acquire-release ordering, so that the fields’ values are visible, and object lifetime §4.1 rules, so that the object still exists.

Device registers are outside the C model. Whether an access to a memory-mapped register, a hardware register that the processor reads and writes at a memory address, is indivisible, and in which order the device sees it, is fixed by the processor architecture and the device.

Atomic read-modify-writes cost more than plain accesses. When several cores update one word, each update moves the word between the cores’ caches, the small fast memories in which each core keeps copies of recently used memory.

Questions answered

Does atomic access also order earlier writes to another object?

Atomicity alone does not order earlier writes to another object: such writes are ordered only by the operation’s memory order, and only toward a thread that performs a matching operation. An atomic operation is a read or write of one shared memory location that no other thread can see half-done, and that property concerns the one location. In C11, an atomic store with memory_order_relaxed orders nothing else. Another thread can read the new value of the atomic variable and still have no guarantee about the earlier writes to another object; reading that object without other synchronization is then a data race, which is undefined behavior.

An atomic store with release order, or with the default sequentially consistent order, does order the storing thread’s earlier writes, but only toward a thread whose load with acquire order (or the sequentially consistent order) reads the value that the store wrote. After that load, every write the storing thread made before the store is visible to the loading thread. Processors behave the same way at the instruction level: in the Armv7-M architecture, neither a STREX nor a plain aligned store orders any other access unless a DMB barrier instruction is added.

Related entries: Compare-and-swap (§9.9), Acquire-release ordering (§9.11), Sequential consistency (§9.12), Atomicity (§8.3), Memory barrier (§4.37), Race condition (§9.2), Data race (§9.3). Further reading: [6, 78].