Skip to content

Instantly share code, notes, and snippets.

@charlespierce
Last active March 1, 2022 23:12
Show Gist options
  • Save charlespierce/87a16e28a98198d0312f8982e1c29623 to your computer and use it in GitHub Desktop.
Save charlespierce/87a16e28a98198d0312f8982e1c29623 to your computer and use it in GitHub Desktop.
Example of using a Mutex in multiple threads
// 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