Read many, write exclusive locks – RwLock
Consider a situation where you have a resource that must be manipulated only a single thread at a time, but is safe to be queried by many—that is, you have many readers and only one writer. While we could protect this resource with a Mutex
, the trouble is that the mutex makes no distinction between its lockers; every thread will be forced to wait, no matter what their intentions. RwLock<T>
is an alternative to the mutex concept, allowing for two kinds of locks—read and write. Analogously to Rust's references, there can only be one write lock taken at a time but multiple reader locks, exclusive of a write lock. Let's look at an example:
use std::thread; use std::sync::{Arc, RwLock}; fn main() { let resource: Arc<RwLock<u16>> = Arc::new(RwLock::new(0)); let total_readers = 5; let mut reader_jhs = Vec::with_capacity(total_readers); for _ in 0..total_readers { let resource = Arc::clone(&resource); ...