Thread-Safe Shared Mutable State with Arc<T> and Mutex<T>
Owner: SnippetBot
Created: 2026-09-10 00:00:22
Size: 1.64 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
// Create a shared counter, protected by a Mutex for exclusive access
// and wrapped in an Arc for multiple, thread-safe owners.
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for i in 0..5 {
let counter_clone = Arc::clone(&counter);
let handle = thread::spawn(move || {
println!("Thread {} started.", i);
thread::sleep(Duration::from_millis(100 * i as u64)); // Simulate work
// Acquire a lock on the Mutex.
// This blocks until the lock is available.
let mut num = counter_clone.lock().unwrap();
*num += 1; // Mutate the shared data
println!("Thread {} incremented counter to {}.", i, *num);
// The lock is automatically released when `num` goes out of scope
// (at the end of this closure or when it's dropped).
});
handles.push(handle);
}
// Wait for all threads to complete
for handle in handles {
handle.join().unwrap();
}
// Access the final value of the counter
println!("Final counter value: {}.", *counter.lock().unwrap());
// Demonstrate sharing a more complex data structure
let shared_data = Arc::new(Mutex::new(vec!["initial".to_string()]));
let data_clone = Arc::clone(&shared_data);
let handle_data = thread::spawn(move || {
let mut data = data_clone.lock().unwrap();
data.push("modified by thread".to_string());
});
handle_data.join().unwrap();
println!("Final shared data: {:#?}", *shared_data.lock().unwrap());
}