Day 28: Explore shared-state concurrency with Mutex and RwLock.

Day 28: Explore shared-state concurrency with Mutex and RwLock.

On Day 28, let's delve into shared-state concurrency using Mutex (Mutual Exclusion) and RwLock (Read-Write Lock) in Rust. These synchronization primitives help manage access to shared data among multiple threads.

Shared-State Concurrency with Mutex and RwLock

Mutex (Mutual Exclusion)

Mutex provides exclusive access to shared data by allowing only one thread to acquire the lock at a time. It ensures that the data remains consistent while being accessed by multiple threads.

Example:

use std::sync::Mutex;
use std::thread;

fn main() {
    let data = Mutex::new(0);

    let handle = thread::spawn(move || {
        let mut num = data.lock().unwrap();
        *num += 1;
    });

    handle.join().expect("Thread panicked!");

    println!("Data: {:?}", data.lock().unwrap());
}

RwLock (Read-Write Lock)

RwLock allows multiple threads to acquire read access simultaneously but enforces exclusive access for write operations. This enables multiple readers or a single writer at a time, ensuring data consistency.

Example:

use std::sync::{RwLock, Arc};
use std::thread;

fn main() {
    let data = Arc::new(RwLock::new(0));
    let mut handles = vec![];

    for _ in 0..5 {
        let data = Arc::clone(&data);
        let handle = thread::spawn(move || {
            let num = data.read().unwrap();
            println!("Read Data: {}", *num);
        });
        handles.push(handle);
    }

    let write_handle = thread::spawn(move || {
        let mut num = data.write().unwrap();
        *num = 42;
    });

    handles.into_iter().for_each(|h| h.join().expect("Thread panicked!"));
    write_handle.join().expect("Write thread panicked!");

    println!("Final Data: {:?}", *data.read().unwrap());
}

Conclusion

Mutex and RwLock are crucial synchronization primitives in Rust for managing shared-state concurrency. While Mutex provides exclusive access for both reading and writing, RwLock allows multiple readers or a single writer, balancing concurrency and data consistency.

Understanding and effectively utilizing Mutex and RwLock helps ensure thread safety and prevent data races in multi-threaded applications. Keep exploring and practicing these synchronization primitives to build robust and efficient concurrent Rust programs!

Happy coding with Rust!

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/@maheshwarligade

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!