Atomics in Rust
For a counter or a flag, an atomic is cheaper than a mutex.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let hits = Arc::new(AtomicUsize::new(0));
let done = Arc::new(AtomicBool::new(false));
let handles: Vec<_> = (0..4)
.map(|_| {
let hits = Arc::clone(&hits);
thread::spawn(move || {
for _ in 0..500 {
hits.fetch_add(1, Ordering::Relaxed);
}
})
})
.collect();
for h in handles {
h.join().unwrap();
}
done.store(true, Ordering::Release);
println!("{}", hits.load(Ordering::Acquire));
println!("{}", done.load(Ordering::Acquire));
}
How it works
fetch_addincrements and returns the previous value.Orderingstates how strict the memory guarantees must be.- No lock, no guard, no chance of poisoning.
Keywords and builtins used here
Vecfnforinletmainmoveuse
The run, in numbers
- Lines
- 27
- Characters to type
- 540
- Tokens
- 190
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 109 seconds.
Step 3 of 3 in Shared state, step 6 of 15 in Concurrency & async.