expression
Relaxed ordering for an independent counter
Relaxed read-modify-write is sufficient for a standalone counter when no other data is published by it. Scoped thread completion provides the synchronization needed before reading the final total. This is not a general publication protocol. Expected stdout (not executed): 12 Common mistake: Reading the final count before workers finish or using the counter to publish unrelated memory.
Formal Syntax & Structure
rust syntaxrust
fetch_add(1, Ordering::Relaxed)Working Example
Example Snippetrust
fn main() { use std::{sync::atomic::{AtomicUsize, Ordering::Relaxed}, thread}; let total = AtomicUsize::new(0); thread::scope(|s| { for _ in 0..3 { s.spawn(|| { for _ in 0..4 { total.fetch_add(1, Relaxed); } }); } }); println!("{}", total.load(Relaxed));}