pub struct RwLock<T>{ /* private fields */ }Expand description
A scalable reader-writer lock.
This lock favours reader performance over writers. Each reader thread gets its own “lock” while writers share a single lock.
T represents the underlying type protected by the lock.
Calling read() returns a read-guard that can be used to safely read T.
Calling write() returns a write-guard that can be used to safely mutate T.
Implementations§
Source§impl<T> RwLock<T>
impl<T> RwLock<T>
Sourcepub fn new(t: T) -> Self
pub fn new(t: T) -> Self
Returns a new instance of a RwLock. Default constructs the underlying data structure.
Sourcepub fn write(&self, n: usize) -> WriteGuard<'_, T>
pub fn write(&self, n: usize) -> WriteGuard<'_, T>
Locks the underlying data-structure for writes. The caller can retrieve
a mutable reference from the returned WriteGuard.
n is the number of active readers currently using this reader-writer lock.
§Example
use node_replication::rwlock::RwLock;
// Create the lock.
let lock = RwLock::<usize>::default();
// Acquire the write lock. This returns a guard that can be used
// to perform writes against the protected data. We need to know
// the number of concurrent reader threads upfront.
const N_CONCURRENT_READERS: usize = 32;
let mut w_guard = lock.write(N_CONCURRENT_READERS);
*w_guard = 777;Sourcepub fn read(&self, tid: usize) -> ReadGuard<'_, T>
pub fn read(&self, tid: usize) -> ReadGuard<'_, T>
Locks the underlying data-structure for reads. Allows multiple readers to acquire the lock. Blocks until there aren’t any active writers.
§Example
use node_replication::rwlock::RwLock;
// Create the lock.
let lock = RwLock::<usize>::default();
// Acquire the read lock. This returns a guard that can be used
// to perform reads against the protected data. We need
// a thread identifier to acquire this lock.
const MY_THREAD_ID: usize = 16;
let r_guard = lock.read(MY_THREAD_ID);
assert_eq!(0, *r_guard);Trait Implementations§
impl<T: Sized + Sync> Sync for RwLock<T>
Sync trait allows RwLock to be shared between threads. The read() and
write() logic ensures that we will never have threads writing to and
reading from the underlying data structure simultaneously.