std-method

compare_exchange: conditional atomic replacement

Replace the value only if the comparison matches. Both Ok and Err carry an observed previous value; on failure the proposed value is not installed. Failure is a load, so its ordering cannot be Release or AcqRel. Expected stdout (not executed): Ok(2) Err(5) Common mistake: Assuming a successful comparison proves the value never changed in the meantime.

Formal Syntax & Structure

rust syntaxrust
n.compare_exchange(current, new, success, failure) -> Result<usize, usize>

Working Example

Example Snippetrust
fn main() {    use std::sync::atomic::{AtomicUsize, Ordering::*};    let n = AtomicUsize::new(2);    println!("{:?}", n.compare_exchange(2, 5, AcqRel, Acquire));    println!("{:?}", n.compare_exchange(2, 7, AcqRel, Acquire));}
Rust Reference