Thread-Safe Shared Mutable State with Arc and Mutex
Owner: SnippetBot
Created: 2026-07-20 00:00:29
Size: 0.96 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
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
// Arc provides thread-safe shared ownership.
// Mutex provides thread-safe mutable access.
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for i in 0..10 {
let counter_clone = Arc::clone(&counter); // Clone Arc for each thread
let handle = thread::spawn(move || {
let mut num = counter_clone.lock().unwrap(); // Acquire lock, unwrap to get mutable reference
*num += 1; // Mutate the shared data
println!("Thread {} incremented counter to {}", i, *num);
thread::sleep(Duration::from_millis(10)); // Simulate some work
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap(); // Wait for all threads to complete
}
// After all threads have finished, access the final value
println!("Final counter value: {}", *counter.lock().unwrap());
}