Compare exchange and retry loops
Quick answer
Compare-exchange replaces an atomic value only if it matches an expected value. This supports conditional updates in concurrent algorithms.
Retry from the observed value
compare_exchange returns Ok(old) on success or Err(observed) on mismatch. The weak variant may fail spuriously and is suitable for retry loops. Success and failure orderings are separate; failure is a load and cannot use Release or AcqRel. For an independent integer counter, Relaxed suffices. A matching value does not prove that no intervening change occurred (the ABA problem).
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};fn main() { let n = AtomicUsize::new(4); assert_eq!(n.compare_exchange(3, 9, Relaxed, Relaxed), Err(4)); assert_eq!(n.compare_exchange(4, 9, Relaxed, Relaxed), Ok(4)); println!("{}", n.load(Relaxed));}Expected stdout (not executed):
9The wrong expected value leaves the atomic unchanged.
use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};fn increment(n: &AtomicUsize) { let mut old = n.load(Relaxed); while old < 2 { match n.compare_exchange_weak(old, old + 1, Relaxed, Relaxed) { Ok(_) => return, Err(actual) => old = actual, } }}fn main() { let n = AtomicUsize::new(0); std::thread::scope(|s| { for _ in 0..4 { s.spawn(|| increment(&n)); } }); println!("{}", n.load(Relaxed));}Expected stdout (not executed):
2The cap is checked again after every failure; completion assumes workers eventually make progress.
Common mistake
Do not reuse a stale expected value after a mismatch.
Try it yourself
Change the cap to three and explain why the loop cannot exceed it.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compare exchange and retry loops — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A compare_exchange loop encounters a different observed value. What should the next attempt use?
Compare exchange and retry loops — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; fn main() { let n = AtomicUsize::new(4); assert_eq!(n.compare_exchange(3, 9, Relaxed, Relaxed), Err(4)); assert_eq!(n.compare_exchange(4, 9, Relaxed, Relaxed), Ok(4)); println!("{}", n.load(Relaxed)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Compare exchange and retry loops — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; fn increment(n: &AtomicUsize) { let mut old = n.load(Relaxed); while old < 2 { match n.compare_exchange_weak(old, old + 1, Relaxed, Relaxed) { Ok(_) => return, Err(actual) => old = actual, } } } fn main() { let n = AtomicUsize::new(0); std::thread::scope(|s| { for _ in 0..4 { s.spawn(|| increment(&n)); } }); println!("{}", n.load(Relaxed)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.