std-method

compare_exchange_weak: retry-aware comparison

A weak comparison can fail even when the expected value matches. It is designed for retry loops. A bounded retry policy must handle the possibility of exhausting the budget; this demonstration checks only the invariant, not whether the first attempt succeeds. Expected stdout (not executed): true Common mistake: Asserting a weak comparison cannot fail when the value matches.

Formal Syntax & Structure

rust syntaxrust
n.compare_exchange_weak(current, new, success, failure)

Working Example

Example Snippetrust
fn main() {    use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};    let n = AtomicUsize::new(1);    let result = n.compare_exchange_weak(1, 2, Relaxed, Relaxed);    let expected = if result.is_ok() { 2 } else { 1 };    println!("{}", n.load(Relaxed) == expected);}
Rust Reference