Shared State With Arc and Mutex
Share mutable counters across threads with Arc for ownership and Mutex for exclusive access, avoiding data races at compile time.
Code
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0u64));
let handles: Vec<_> = (0..8)
.map(|_| {
let counter = Arc::clone(&counter);
thread::spawn(move || {
for _ in 0..1000 {
let mut value = counter.lock().expect("mutex poisoned");
*value += 1;
}
})
})
.collect();
for handle in handles {
handle.join().expect("thread panicked");
}
let total = *counter.lock().expect("mutex poisoned");
println!("total = {total}");
}Report a problem with this exampleOpens a pre-filled issue on GitHub.