How do LDAXR and STLXR implement atomic operations?
Short answer: An exclusive load establishes a reservation. An exclusive store succeeds only if the reservation remains valid; otherwise retry. Acquire/release forms provide ordering.
1: LDAXR W0, [X1]
ADD W0, W0, #1
STLXR W2, W0, [X1]
CBNZ W2, 1b
1. Why normal increment fails: Two cores can both load 10, add 1 and store 11, losing an increment.
2. Exclusive sequence: LDAXR reads and establishes an exclusive reservation. STLXR attempts the write and returns zero on success or nonzero on failure. Interference or other events can invalidate the reservation.
3. Retry: CBNZ repeats the sequence until a store succeeds. LDAXR has acquire semantics and STLXR release semantics.
// Linux kernel alternative
atomic_inc(&counter);
4. Modern ARM: LSE-capable cores also support single-instruction atomic read-modify-write operations, such as LDADD.
Interview takeaway: Exclusives make the update conditional on reservation validity; ordering semantics and atomicity are distinct.
Two-core exclusive retry trace
| Step | Core 0 | Core 1 |
|---|---|---|
| Initial | counter=10 | counter=10 |
| Load-exclusive | reads 10, reserves | reads 10, reserves |
| Add | computes 11 | computes 11 |
| Store-exclusive | succeeds, status 0 | fails if reservation invalidated |
| Retry | done | reloads 11, computes 12, stores successfully |
The exclusive monitor tracks the relevant reservation granule; interference, context changes and other permitted conditions can cause failure, not just an explicit write to the exact C object. Code must handle failure by retrying. A store-exclusive status value is not the stored data. Use the architecture's width, alignment and memory-type restrictions, and keep the exclusive sequence short.
For pure counter increments, LDXR/STXR can provide relaxed atomicity; LDAXR/STLXR add ordering. LSE instructions such as LDADD and ordering variants can avoid an explicit software retry loop when supported. In C or Linux, prefer compiler atomic or kernel atomic APIs to handwritten inline assembly unless the low-level implementation itself is the subject. A retry loop is not a bounded-time guarantee under contention.