Atomic Counters With Ordering
fetch_add with Relaxed ordering keeps increments atomic without cross-operation ordering, and Release stores pair with Acquire loads to publish data.
Code
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let counter = Arc::new(AtomicUsize::new(0));
let flag = Arc::new(AtomicBool::new(false));
let mut handles = Vec::new();
for _ in 0..4 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..100 {
// Relaxed:只要原子性,不约束与其他访问的相对顺序,适合纯计数
counter.fetch_add(1, Ordering::Relaxed);
}
}));
}
for handle in handles {
handle.join().unwrap();
}
println!("final count: {}", counter.load(Ordering::Relaxed));
// Release 写 + Acquire 读成对:读方看到标志位 true 后,
// 能安全读到写方在 store 之前准备好的全部数据
flag.store(true, Ordering::Release);
if flag.load(Ordering::Acquire) {
println!("flag observed after release");
}
}How the snippet works
Count the function main as the entire surface area of Atomic Counters With Ordering.
Iteration happens inside for _ in 0..4 — everything outside it runs once.
Applying it
Expect labeled output — final count:, flag observed after release — when the file runs.
Statements that matter
handles.push(thread::spawn(move || {
for _ in 0..100 {
// Relaxed:只要原子性,不约束与其他访问的相对顺序,适合纯计数
counter.fetch_add(1, Ordering::Relaxed);
}
}));
handle.join().unwrap();
Interactive Tools for This Topic
FAQ
- What does Atomic Counters With Ordering print when run?
- The script runs standalone; its 2 labeled outputs include `final count:`, `flag observed after release`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.