skip to content

In Rust, when do you use `compare_exchange_weak` instead of `compare_exchange` on an `AtomicUsize`, and what do the `try_update` and `update` methods add?

level: seniorimportance: should knowfreq 30%

answer

  1. spurious failure is allowed
  2. the loop already retries
  3. Err carries the actual value
  4. two orderings, failure cannot release
  5. renamed from fetch_update

basics

~20 s

Use compare_exchange_weak inside a retry loop, where a spurious failure just costs one more iteration and may compile to cheaper code; use compare_exchange for a one-shot attempt. try_update and update, stable since Rust 1.95, wrap that loop around a closure.

solid answer

~40 s

`compare_exchange(current, new, success, failure)` writes `new` only if the value equals `current`, returning `Ok(previous)` or `Err(actual)`. `compare_exchange_weak` may fail **spuriously** even when the values match, which on some platforms yields more efficient code. In a loop that already retries with the `Err` value that is harmless, so the weak form is the idiom there; a single attempt whose failure means "someone else got there" needs the strong form. The `failure` ordering applies to the load of a failed attempt and may be only `SeqCst`, `Acquire` or `Relaxed` — rustc's deny-by-default `invalid_atomic_ordering` lint rejects `Release` or `AcqRel`. Since Rust 1.95 `try_update` runs the loop for a closure returning `Option` and `update` for an infallible closure; in 1.99 the old `fetch_update` is deprecated as an alias of `try_update`. The closure may run more than once.

code

rust · 32 lines
rust
use std::sync::atomic::{AtomicUsize, Ordering};

const MAX_CONNS: usize = 3;
static ACTIVE: AtomicUsize = AtomicUsize::new(0);

// Hand-written CAS loop: take a slot only while ACTIVE < MAX_CONNS
fn try_acquire_manual() -> bool {
    let mut cur = ACTIVE.load(Ordering::Relaxed);
    loop {
        if cur >= MAX_CONNS {
            return false;
        }
        match ACTIVE.compare_exchange_weak(cur, cur + 1, Ordering::Relaxed, Ordering::Relaxed) {
            Ok(_) => return true,
            Err(actual) => cur = actual, // lost a race or failed spuriously: retry with the fresh value
        }
    }
}

// Same loop via try_update (stable since Rust 1.95)
fn try_acquire() -> bool {
    ACTIVE
        .try_update(Ordering::Relaxed, Ordering::Relaxed, |n| (n < MAX_CONNS).then_some(n + 1))
        .is_ok()
}

fn main() {
    let got: Vec<bool> = (0..2).map(|_| try_acquire_manual()).chain((0..2).map(|_| try_acquire())).collect();
    println!("{got:?} active={}", ACTIVE.load(Ordering::Relaxed));
    let prev = ACTIVE.update(Ordering::Relaxed, Ordering::Relaxed, |n| n.saturating_sub(1));
    println!("released from {prev}");
}

go deeper

for a junior

Recall that compare_exchange stores only when the value matches and returns Ok with the old value or Err with the actual one.

for a middle

Explain the Ok and Err payloads, why the weak form belongs in loops, and why a plain arithmetic update should stay fetch_add.

for a senior

Choose success and failure orderings, know the lint that rejects Release on failure, and know that try_update and update since 1.95 rerun the closure.

for a principal

Treat every hand-written CAS loop as code that needs a reviewer who checks retries, ABA and orderings, and prefer the dedicated fetch_ methods or std locks when they fit.

## What `compare_exchange` does `AtomicUsize::compare_exchange(current, new, success, failure)` is Rust's compare-and-swap. In one atomic step it compares the stored value with `current`; if they are equal it stores `new`. It returns a `Result`: - `Ok(previous)` — the comparison succeeded and `new` is now stored; `previous` equals `current`. - `Err(actual)` — the comparison failed; nothing was written, and `actual` is the value that was there. A failed `compare_exchange` is not a write, which the module documentation states explicitly when it defines a data race. ## Strong versus weak `compare_exchange_weak` has the same signature and the same `Result`, with one difference the documentation states: it "is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms". For example, on CPUs whose compare-and-swap is built from a load-linked/store-conditional pair, the strong form has to wrap that pair in an inner retry loop; the weak form can expose a single attempt. That makes the rule simple: 1. **Inside a retry loop, use `compare_exchange_weak`.** The loop already handles `Err` by trying again with the fresh value, so a spurious failure just costs one more iteration. 2. **For a single attempt, use `compare_exchange`.** If a failure means "another thread changed the value, so do something else", a spurious failure would be misread as contention. On x86-64 both forms typically compile to the same locked compare-exchange instruction, so the choice is about portable correctness and efficiency, not about how the code behaves on one machine. ## The canonical loop A connection limiter that hands out a slot only while fewer than `MAX_CONNS` are active cannot use `fetch_add`, because the update depends on a condition. The loop: ```rust let mut cur = ACTIVE.load(Ordering::Relaxed); loop { if cur >= MAX_CONNS { return false; } match ACTIVE.compare_exchange_weak(cur, cur + 1, Ordering::Relaxed, Ordering::Relaxed) { Ok(_) => return true, Err(actual) => cur = actual, } } ``` Note the `Err(actual) => cur = actual` arm: the failed call already returns the current value, so there is no need for a second `load`. ## Two orderings, and what the compiler rejects The `success` ordering applies to the read-modify-write when the exchange happens; the `failure` ordering applies to the load performed when it does not. The documentation restricts the failure ordering to `SeqCst`, `Acquire` or `Relaxed`, because a failed attempt does not store. rustc enforces this: passing `Ordering::Release` as the failure ordering is rejected by the **`invalid_atomic_ordering`** lint, which is deny-by-default, with the message that the failure ordering "may not be `Release` or `AcqRel`, since a failed `compare_exchange` does not result in a write". The same lint rejects a `store` with `Acquire` and a `load` with `Release`. For a counter-like limiter, `Relaxed` on both is enough. If winning the exchange grants access to other memory (a lock bit, a claimed buffer slot), the success ordering becomes `Acquire` or `AcqRel`. ## The closure-based methods | Method | Closure returns | Method returns | Since | |---|---|---|---| | `try_update(set, fetch, f)` | `Option<T>`; `None` aborts | `Ok(previous)` or `Err(previous)` | 1.95 | | `update(set, fetch, f)` | `T`; always stores | the previous value | 1.95 | | `fetch_update(set, fetch, f)` | `Option<T>` | as `try_update` | 1.45 for integers; deprecated in 1.99 | Both new methods were stabilised in Rust 1.95 for `AtomicBool`, the integer atomics and `AtomicPtr`. In the 1.99 library source `fetch_update` carries a `#[deprecated]` attribute with `since = "1.99.0"` and a note saying it was renamed to `try_update` for consistency, and rustc 1.99.1 prints a `deprecated` warning suggesting `try_update`. Both new methods are implemented as exactly the `compare_exchange_weak` loop shown above, so: - **the closure may run several times** when other threads change the value in between, though its result is stored only once — keep it free of side effects; - they are not a critical section; the documentation warns that they inherit the usual compare-and-swap drawbacks, including the ABA problem when the value is an index or a pointer. The limiter collapses to `ACTIVE.try_update(Relaxed, Relaxed, |n| (n < MAX_CONNS).then_some(n + 1)).is_ok()`. ## Choosing the tool - A plain arithmetic or bitwise update: `fetch_add`, `fetch_sub`, `fetch_max`, `fetch_or` — one instruction, no loop, never spurious. - A conditional or computed update: `try_update` or `update`, or a hand-written weak loop when you need to act inside the loop. - A single claim attempt whose failure has meaning: strong `compare_exchange`. - The old `compare_and_swap` method is deprecated since 1.50; it took one ordering and returned a bare value.

  • Why must the closure passed to `AtomicUsize::try_update` be free of side effects?
    `try_update` is a `compare_exchange_weak` loop: if another thread changes the value, or the weak exchange fails spuriously, it calls the closure again with the new value. A closure that logs, allocates an id or sends a message would do so once per attempt, not once per successful update.
  • When is the strong `compare_exchange` the right call even though the weak one is cheaper?
    When there is no loop and the failure carries meaning — for example `INIT.compare_exchange(false, true, Acquire, Relaxed)` deciding which single thread runs one-time setup. A spurious failure from the weak form would make every thread believe someone else won, and setup might never run.
  • Why can `fetch_add` not be replaced by `update` with no cost?
    `fetch_add` is a single atomic read-modify-write that never fails or retries. `update` is a load followed by a compare-exchange loop, which under contention can retry many times and calls the closure on each attempt. Use the dedicated `fetch_` method whenever one exists for the operation.

  • compare_exchange_weak is wrong inside a retry loop because it can fail spuriously.
  • A failed compare_exchange still stores the new value.
  • The failure ordering can be Release so a failed attempt publishes data.
  • try_update calls its closure exactly once per call.
  • fetch_update is the current, preferred name in Rust 1.99.

Assumes Rust 1.99: update and try_update are stable since 1.95, and fetch_update is deprecated since 1.99.0 as an alias of try_update.