From 9e36ee2d015e696a7ab89a697f5b7463d26c6107 Mon Sep 17 00:00:00 2001 From: 3008505 <3008505.studs.hs-mannheim.de> Date: Sat, 13 Jun 2026 12:58:33 +0000 Subject: [PATCH] Added an Example how two threads can modfiy the same Integers using Mutex and Arc --- G-concurrency/mutexInThreads.rs | 36 +++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 G-concurrency/mutexInThreads.rs diff --git a/G-concurrency/mutexInThreads.rs b/G-concurrency/mutexInThreads.rs new file mode 100644 index 0000000..f0858a1 --- /dev/null +++ b/G-concurrency/mutexInThreads.rs @@ -0,0 +1,36 @@ +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()); +} \ No newline at end of file