pub type RwLock<T> = RwLock<RawRwLock, T>;Expand description
A reader-writer lock.
This type of lock allows a number of readers or at most one writer at any point in time. The write portion of this lock typically allows modification of the underlying data (exclusive access) and the read portion of this lock typically allows for read-only access (shared access).
This lock uses a task-fair locking policy which generally gives waiting writers priority over new readers. This means that readers trying to acquire the lock will block even if the lock is unlocked when there are writers waiting to acquire the lock. Because of this, attempts to recursively acquire a read lock within a single thread may result in a deadlock.
Use RecursiveRwLock instead if recursive read
locking is required.
The type parameter T represents the data that this lock protects. It is
required that T satisfies Send to be shared across threads and Sync to
allow concurrent access through readers. The RAII guards returned from the
locking methods implement Deref (and DerefMut for the write methods)
to allow access to the contents of the lock.
§Fairness
This rwlock uses unfair unlocking by default, which allows newly arriving threads to acquire the lock before a waiting thread and generally improves throughput. This can starve waiting threads.
Fair unlocking can be requested explicitly by calling
RwLockReadGuard::unlock_fair or RwLockWriteGuard::unlock_fair instead of
simply dropping the guard. A fair unlock gives waiting threads priority over
newly arriving threads.
§Differences from the standard library RwLock
- Task-fair locking policy instead of an unspecified platform default.
- No poisoning, the lock is released normally on panic.
- Only requires one word of lock state.
- Supports upgradable read locks and atomic upgrades to write locks.
- Supports locking with a timeout.
- Allows raw locking & unlocking without a guard.
- Supports explicit fair unlocking by calling
RwLockReadGuard::unlock_fairandRwLockWriteGuard::unlock_fair.
§Examples
use parking_lot::RwLock;
let lock = RwLock::new(5);
// Multiple readers can access the data concurrently.
std::thread::scope(|scope| {
for _ in 0..3 {
scope.spawn(|| {
let reader = lock.read();
assert_eq!(*reader, 5);
});
}
});
// All reader threads have finished. Only one write lock may be held.
{
let mut writer = lock.write();
*writer += 1;
assert_eq!(*writer, 6);
} // Write lock is released.Aliased Type§
pub struct RwLock<T> { /* private fields */ }