What is the difference between Mutex and RwLock

Mutex grants exclusive access for any operation, while RwLock allows concurrent reads or exclusive writes for better performance in read-heavy scenarios.

A Mutex allows only one thread to access data at a time (read or write), while an RwLock allows multiple readers or a single writer simultaneously. Use Mutex for simple exclusive access and RwLock when reads are frequent and writes are rare to improve concurrency.

use std::sync::{Mutex, RwLock};

let mutex_data = Mutex::new(5);
let rwlock_data = RwLock::new(5);

// Mutex: lock for read or write
let mut guard = mutex_data.lock().unwrap();
*guard = 10;

// RwLock: lock for read (multiple allowed) or write (exclusive)
let read_guard = rwlock_data.read().unwrap();
let write_guard = rwlock_data.write().unwrap();
*write_guard = 20;