41. Rust: Safe Counter (Arc & Mutex)
RustSharing state across multiple threads without data races.
use std::sync::{Arc, Mutex};
use std::thread;
fn create_counter() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
}));
}
}
When to use
Use it when many threads need to modify the same shared value without risking a data race.
Common pitfalls
This example is missing join() on the thread handles — without it, the program can exit before all threads finish their work.