Fetch Update Folds The CAS Retry

fetch_update folds the compare-and-swap retry loop into one call: Ok carries the previous value when the closure wrote, Err carries it when the closure refused.

RustResilience

Code

rustsnippet
22 lines
use std::sync::atomic::{AtomicUsize, Ordering};

static CONN_LIMIT: AtomicUsize = AtomicUsize::new(10);

fn halve_limit() -> Result<usize, usize> {
    // fetch_update folds the CAS retry loop into one call:
    // the closure writes only when it returns Some(new); None gives up
    CONN_LIMIT.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
        if current >= 2 {
            Some(current / 2)
        } else {
            None
        }
    })
}

fn main() {
    println!("10 -> {:?}", halve_limit()); // Ok(10), new value 5
    println!("5 -> {:?}", halve_limit()); // Ok(5), new value 2
    println!("2 -> {:?}", halve_limit()); // Ok(2), new value 1
    println!("1 -> {:?}", halve_limit()); // Err(1), closure refused
}

What the demo folds

halve_limit wraps the whole compare-and-swap retry loop inside fetch_update: the closure receives the current value and returns Some(current / 2) when it is at least 2, None otherwise. The call spins internally until the compare-and-swap sticks.

Four invocations walk the atomic down: Ok(10), Ok(5) and Ok(2) each carry the previous value with the halved one now stored. The final call sees 1, the closure returns None, and Err(1) reports the refusal without any write.

Caveats and details

  • Ok and Err both carry the value seen before the attempt.
  • The retry loop lives inside fetch_update, not in your code.

Interactive Tools for This Topic

FAQ

What does the Err variant mean here?
The closure returned None, so no update was applied; Err(1) hands back the unchanged current value, as the final printed line shows.