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.
Code
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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.cURL to fetch ConverterTranslate a curl command into equivalent JavaScript fetch() code, handling the request method, headers, JSON or raw body, and basic auth.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.