pub struct RwLock<T: ?Sized> { /* private fields */ }
Expand description
A reader-writer lock for protecting shared data.
This type is an async version of std::sync::RwLock
.
§Examples
use async_std::sync::RwLock;
let lock = RwLock::new(5);
// Multiple read locks can be held at a time.
let r1 = lock.read().await;
let r2 = lock.read().await;
assert_eq!(*r1, 5);
assert_eq!(*r2, 5);
drop((r1, r2));
// Only one write locks can be held at a time.
let mut w = lock.write().await;
*w += 1;
assert_eq!(*w, 6);
Implementations§
Source§impl<T: ?Sized> RwLock<T>
impl<T: ?Sized> RwLock<T>
Sourcepub async fn read(&self) -> RwLockReadGuard<'_, T>
pub async fn read(&self) -> RwLockReadGuard<'_, T>
Acquires a read lock.
Returns a guard that releases the lock when dropped.
§Examples
use async_std::sync::RwLock;
let lock = RwLock::new(1);
let n = lock.read().await;
assert_eq!(*n, 1);
assert!(lock.try_read().is_some());
Sourcepub fn try_read(&self) -> Option<RwLockReadGuard<'_, T>>
pub fn try_read(&self) -> Option<RwLockReadGuard<'_, T>>
Attempts to acquire a read lock.
If a read lock could not be acquired at this time, then None
is returned. Otherwise, a
guard is returned that releases the lock when dropped.
§Examples
use async_std::sync::RwLock;
let lock = RwLock::new(1);
let n = lock.read().await;
assert_eq!(*n, 1);
assert!(lock.try_read().is_some());
Sourcepub async fn write(&self) -> RwLockWriteGuard<'_, T>
pub async fn write(&self) -> RwLockWriteGuard<'_, T>
Acquires a write lock.
Returns a guard that releases the lock when dropped.
§Examples
use async_std::sync::RwLock;
let lock = RwLock::new(1);
let mut n = lock.write().await;
*n = 2;
assert!(lock.try_read().is_none());
Sourcepub fn try_write(&self) -> Option<RwLockWriteGuard<'_, T>>
pub fn try_write(&self) -> Option<RwLockWriteGuard<'_, T>>
Attempts to acquire a write lock.
If a write lock could not be acquired at this time, then None
is returned. Otherwise, a
guard is returned that releases the lock when dropped.
§Examples
use async_std::sync::RwLock;
let lock = RwLock::new(1);
let n = lock.read().await;
assert_eq!(*n, 1);
assert!(lock.try_write().is_none());
Sourcepub fn into_inner(self) -> Twhere
T: Sized,
pub fn into_inner(self) -> Twhere
T: Sized,
Consumes the lock, returning the underlying data.
§Examples
use async_std::sync::RwLock;
let lock = RwLock::new(10);
assert_eq!(lock.into_inner(), 10);
Sourcepub fn get_mut(&mut self) -> &mut T
pub fn get_mut(&mut self) -> &mut T
Returns a mutable reference to the underlying data.
Since this call borrows the lock mutably, no actual locking takes place – the mutable borrow statically guarantees no locks exist.
§Examples
use async_std::sync::RwLock;
let mut lock = RwLock::new(0);
*lock.get_mut() = 10;
assert_eq!(*lock.write().await, 10);