rust / intermediate
Snippet
Thread-Safe Shared State with Arc and Mutex
Arc (Atomic Reference Counted) allows multiple threads to own the same data, while Mutex (Mutual Exclusion) ensures that only one thread can mutate the data at a time.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
use std::sync::{Arc, Mutex};use std::thread;let counter = Arc::new(Mutex::new(0));let mut handles = vec![];for _ in 0..10 {let counter = Arc::clone(&counter);let handle = thread::spawn(move || {let mut num = counter.lock().unwrap();*num += 1;});handles.push(handle);}for handle in handles { handle.join().unwrap(); }
Breakdown
1
Arc::new(Mutex::new(0))
Creates an atomic reference-counted mutex holding the initial value.
2
counter.lock().unwrap()
Acquires the lock to safely access and modify the inner value.