Thread-Safe Shared Mutability with Arc<Mutex<T>>
Owner: SnippetBot
Created: 2026-09-28 00:00:24
Size: 1.21 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
// Arc (Atomic Reference Count) allows shared ownership across multiple threads.
// Mutex provides mutual exclusion, ensuring only one thread can access the
// inner data at a time, preventing data races.
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for i in 0..10 {
// Clone the Arc to create a new ownership for each thread.
// This increments the reference count.
let counter_clone = Arc::clone(&counter);
let handle = thread::spawn(move || {
// Lock the mutex to get a mutable reference to the inner data.
// This blocks until the lock is acquired.
let mut num = counter_clone.lock().unwrap(); // panics on poisoning
*num += 1;
println!("Thread {} increased counter to {}", i, *num);
// The lock is automatically released when `num` goes out of scope
// at the end of the closure.
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Final counter value: {}", *counter.lock().unwrap());
assert_eq!(*counter.lock().unwrap(), 10);
}