Last active
March 1, 2022 23:12
-
-
Save charlespierce/87a16e28a98198d0312f8982e1c29623 to your computer and use it in GitHub Desktop.
Example of using a Mutex in multiple threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create a shared, mutable counter | |
let counter = Arc::new(Mutex::new(0)); | |
// Spawn one thread incrementing the counter | |
let counter1 = counter.clone(); | |
let handle1 = thread::spawn(move || { | |
for _ in 0..10 { | |
*counter1.lock().unwrap() += 1; | |
} | |
}); | |
// Spawn another thread incrementing the counter | |
let counter2 = counter.clone(); | |
let handle2 = thread::spawn(move || { | |
for _ in 0..10 { | |
*counter2.lock().unwrap() += 1; | |
} | |
}); | |
// Wait for the threads to complete | |
handle1.join().unwrap(); | |
handle2.join().unwrap(); | |
// Will write "Value: 20", since each thread incremented the counter 10 times. | |
println!("Value: {}", *counter.lock().unwrap()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment