PR3-Rust-SS26/G-concurrency/mutexInThreads.rs

36 lines
1.2 KiB
Rust

use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
// 1. Wrap the counter in a Mutex, and wrap that Mutex inside an Arc.
// Arc is the Atomic Reference Counter, contrary to the normal reference counter
// Arc is saved on the heap
let counter = Arc::new(Mutex::new(0));
// 2. Clone the Arc pointer for Thread 1
let counter_clone1 = Arc::clone(&counter);
// The word move makes sure that counter_clone1 is also saved on the private stack of handle1
let handle1 = thread::spawn(move || {
for _ in 0..10 {
let mut guard = counter_clone1.lock().unwrap();
*guard += 1;
}
}); // guard drops here, releasing the lock automatically
// 3. Clone the Arc pointer for Thread 2
let counter_clone2 = Arc::clone(&counter);
// The word move makes sure that counter_clone2 is also saved on the private stack of handle2
let handle2 = thread::spawn(move || {
for _ in 0..10 {
let mut guard = counter_clone2.lock().unwrap();
*guard += 1;
}
});
// 4. Wait for both threads to finish
handle1.join().unwrap();
handle2.join().unwrap();
// 5. Print the final result
println!("Final value: {}", *counter.lock().unwrap());
}