Atomic operations and shared state
Quick answer
Atomic types support indivisible operations on a single shared value. They are useful for simple flags and counters without a mutex around each operation.
Read, write and modify
Atomic operations take an Ordering that specifies synchronization constraints. load reads, store writes and fetch_add reads and updates atomically, returning the old value. A load followed by a store is not one atomic update. Atomic availability depends on the target architecture. Use a mutex for invariants spanning several values unless you have a proven atomic protocol.
use std::sync::atomic::{AtomicUsize, Ordering};fn main() { let n = AtomicUsize::new(5); let old = n.fetch_add(3, Ordering::SeqCst); println!("{old} {}", n.load(Ordering::SeqCst));}Expected stdout (not executed):
5 8The old and new values are distinct.
use std::sync::atomic::{AtomicUsize, Ordering};fn main() { let n = AtomicUsize::new(0); std::thread::scope(|s| { for _ in 0..4 { s.spawn(|| { n.fetch_add(1, Ordering::SeqCst); }); } }); println!("{}", n.load(Ordering::SeqCst));}Expected stdout (not executed):
4Every worker contributes one increment.
Common mistake
Atomicity does not make a sequence of separate atomic operations indivisible.
Try it yourself
Make each worker add two and predict the final count.
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
Atomic operations and shared state — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
An atomic counter starts at 5. What does fetch_add(3, ordering) return?
Atomic operations and shared state — 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}; fn main() { let n = AtomicUsize::new(5); let old = n.fetch_add(3, Ordering::SeqCst); println!("{old} {}", n.load(Ordering::SeqCst)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Atomic operations and shared state — 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}; fn main() { let n = AtomicUsize::new(0); std::thread::scope(|s| { for _ in 0..4 { s.spawn(|| { n.fetch_add(1, Ordering::SeqCst); }); } }); println!("{}", n.load(Ordering::SeqCst)); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.