rust armanriazi thread sync sharedstate mutex
Rust: Using Thread Synchronization with Shared State and Mutex
In Rust, thread synchronization is crucial when multiple threads need to access shared data concurrently. One way to achieve thread synchronization is by using the Mutex
type from the std::sync
module.
A Mutex
is a mutual exclusion primitive that allows only one thread to access the shared data at a time. Other threads that try to access the data while it is locked by a thread will be blocked until the lock is released.
Here's an example of how to use a Mutex
to synchronize access to shared state:
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
// Create a shared counter
let counter = Arc::new(Mutex::new(0));
// Create multiple threads that increment the counter
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
// Lock the mutex to access the shared counter
let mut num = counter.lock().unwrap();
*num += 1; // Increment the counter
});
handles.push(handle);
}
// Wait for all threads to finish
for handle in handles {
handle.join().unwrap();
}
// Print the final value of the counter
println!("Counter: {}", *counter.lock().unwrap());
}
In this example, we create a shared counter using an Arc
(atomic reference count) and a Mutex
. The Arc
allows multiple threads to share ownership of the counter, and the Mutex
ensures that only one thread can access the counter at a time.
Inside the thread's closure, we lock the Mutex
using the lock
method, which returns a MutexGuard
that represents the locked data. We can then modify the counter by dereferencing the MutexGuard
and incrementing its value.
After all threads have finished, we print the final value of the counter by locking the Mutex
again and accessing its value.
By using a Mutex
, we can safely share data between threads and avoid data races or other synchronization issues that might occur when multiple threads access shared data concurrently.