use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0u64));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1_000 {
let mut n = counter.lock().unwrap();
*n += 1;
// lock is released when `n` (the guard) goes out of scope
}
}));
}
for h in handles { h.join().unwrap(); }
println!("final: {}", *counter.lock().unwrap()); // 10000
// For simple counters, prefer AtomicU64 — lock-free and faster.
}
Create a free account and build your private vault. Share publicly whenever you want.