skip to content

In C++, why is compare_exchange_weak normally called in a loop, and when should you prefer compare_exchange_strong instead?

level: seniorimportance: should knowfreq 52%

answer

  1. may fail spuriously
  2. expected is updated on failure
  3. LL/SC hardware
  4. loop already retries: weak
  5. single attempt: strong

basics

~20 s

compare_exchange_weak may fail spuriously even when the value matches, so it only makes sense where a failure is retried anyway. On failure it writes the current value back into expected. Use compare_exchange_strong when a single attempt decides something.

solid answer

~40 s

`a.compare_exchange_weak(expected, desired)` atomically compares `a` with `expected` and, if equal, stores `desired` and returns `true`. If not equal it returns `false` and **writes the value it read into `expected`**, so the next iteration recomputes from fresh data without another load. The weak form may also **fail spuriously** — return `false` even though the values were equal — because on load-linked/store-conditional machines the store can be interrupted. The standard notes that nearly every use of the weak form is therefore a loop, where a spurious failure costs one more iteration, and that the weak version can be faster there. `compare_exchange_strong` never fails spuriously: prefer it when you try once and act on the answer, or when the loop body is expensive enough that a spurious retry costs more than the strong form.

code

cpp · 23 lines
cpp
#include <atomic>
#include <cstdio>
#include <thread>
#include <vector>

std::atomic<int> peak{0};

// Raise peak to v unless another thread already stored something larger.
void record(int v) {
    int cur = peak.load(std::memory_order_relaxed);
    while (cur < v &&
           !peak.compare_exchange_weak(cur, v, std::memory_order_relaxed)) {
        // on failure (real or spurious) cur now holds the value just read
    }
}

int main() {
    std::vector<std::thread> ts;
    for (int t = 0; t < 4; ++t)
        ts.emplace_back([t] { for (int i = 0; i < 100000; ++i) record(i * 4 + t); });
    for (auto& th : ts) th.join();
    std::printf("peak=%d\n", peak.load());  // 399999
}

go deeper

for a junior

Recall that compare-and-exchange stores the new value only if the atomic still holds the expected one, and reports which happened.

for a middle

Explain that a failed call writes the current value into expected, and that the weak form may fail spuriously, so it lives in a loop.

for a senior

Choose weak or strong per call site, set the success and failure orders correctly, and recognise when fetch_add or exchange replaces the loop.

for a principal

Limit hand-written CAS loops to reviewed primitives, because their failure modes under contention and ABA rarely show up in tests.

## The operation `std::atomic<T>` offers two **compare-and-exchange** members, each in two overload shapes: - `compare_exchange_weak(T& expected, T desired, std::memory_order order = std::memory_order::seq_cst)` - `compare_exchange_strong(T& expected, T desired, std::memory_order order = std::memory_order::seq_cst)` - and versions taking separate `success` and `failure` orders. Both atomically compare the object's value representation with `expected`. If they are equal, the object becomes `desired` and the call returns `true` — a read-modify-write. If not, the call returns `false`, and **only on failure** `expected` is overwritten with the value the operation read. That last rule is what makes the loop idiom work: the loop never needs a separate `load()` to refresh its view. ## Spurious failure The standard allows the weak form to **fail spuriously**: even when the values compare equal it may return `false` (and store the same value back into `expected`). Its note explains why: this permits implementation on **load-linked/store-conditional** machines such as arm64 without LSE or POWER, where the conditional store fails if anything disturbs the reservation. The strong form must hide that, typically by looping internally. ## The loop idiom The standard's own example of expected use is: ```cpp expected = current.load(); do { desired = function(expected); } while (!current.compare_exchange_weak(expected, desired)); ``` A real case is recording the **peak** value several threads have seen: 1. Load the current peak once, relaxed. 2. While the candidate `v` is larger and the CAS fails, loop; each failure refreshes `cur`. 3. Stop when the CAS succeeds or another thread has already stored something at least as large. A spurious failure only costs one more trip round a loop that had to exist anyway, which is why the weak form fits. ## Weak or strong | Situation | Choose | Reason | |---|---|---| | Retry loop with a cheap body | `compare_exchange_weak` | spurious failure = one extra iteration; may compile tighter on LL/SC targets | | One attempt whose result drives a decision ("did I claim the slot?") | `compare_exchange_strong` | a spurious `false` would be a wrong answer | | Loop whose body is expensive to recompute | `compare_exchange_strong` | the standard's note prefers strong when weak would need a loop and strong would not | | x86-64 | either | both compile to `lock cmpxchg`; there is no spurious failure in practice | ## Memory orders on CAS With one order argument, the failure order is derived from it: `acq_rel` becomes `acquire` and `release` becomes `relaxed` on failure. With two arguments, the failure order cannot be `release` or `acq_rel` — a failed CAS is only a load, and a load cannot be a release. The peak example uses `relaxed` throughout because the value publishes nothing else; a CAS that publishes a node (a lock-free stack push) needs `release` on success. ## Senior pitfalls - **Comparing value representations.** CAS compares bits, not `operator==`: floating-point `-0.0` and `+0.0` compare unequal, and for a struct with padding C++20 says padding bits do not take part — a rule libc++'s status page still lists as unimplemented, so avoid padded types in a CAS. - **ABA.** A CAS that succeeds because the value returned to `A` after being `B` can corrupt a pointer-based structure; that design problem belongs with lock-free algorithms in general. - **Livelock under contention.** A thread that keeps losing keeps looping; compare-and-swap progress in general is covered with atomics and CAS as an idea. When a single read-modify-write exists (`fetch_add`, `fetch_or`, `exchange`) use it instead of a CAS loop. ## Reviewing a CAS loop A short checklist catches most mistakes in review: 1. Is there exactly one load before the loop, and none inside it? The failed call already refreshed `expected`. 2. Does the loop body recompute `desired` from the refreshed `expected` every time, rather than from a value captured earlier? 3. Is the weak form used only where a `false` simply means "try again"? 4. Do the success and failure orders match what the operation publishes — `release` or `acq_rel` on success when the new value hands over other data, `relaxed` when it does not? 5. Could the whole loop be one `fetch_add`, `fetch_or` or `exchange`?

  • Why does the peak loop need no load() inside its body?
    Because a failed `compare_exchange_weak` already stores the value it read into `expected` (here `cur`). The loop condition `cur < v` is re-evaluated with that fresh value, so a second load would only add work and a window for staler data. The initial `load()` before the loop is the only explicit read.
  • Is it legal to pass memory_order_release as the failure order?
    No. The two-order overloads forbid `memory_order::release` and `acq_rel` as the failure order, because a failed compare-exchange performs only a load and a load cannot have release semantics. With the single-order overload you may pass `release`; the library then uses `relaxed` for the failure case automatically.

  • compare_exchange_weak fails only when another thread changed the value.
  • After a failed compare-exchange you must load the atomic again yourself.
  • compare_exchange_strong is always slower, so weak is always better.
  • A compare-exchange compares objects with their operator==.
  • On failure, expected is left unchanged so the caller can retry it.