pub struct RwLock<T> { /* private fields */ }
Expand description
An async reader-writer lock.
This lock allows max_readers
readers at once, or one writer. This is different from a mutex,
which only allows one lock at a time, regardless of whether it is used for reading or writing.
This lock is fair, meaning that locks are provided in the order that they are requested. This is in contrast to a read-preferring lock, which would continue to allow readers to lock even if a writer is waiting. This stops the possibility of readers starving writers.
This type only implements Sync
when T
is Send
. Values are provided through the Deref
and DerefMut
implementations on the ReadGuard
and WriteGuard
types.
§Examples
use no_std_async::RwLock;
async fn foo() {
let lock = RwLock::new(42);
{
// we can have as many readers as we want.
let reads = [
lock.read().await,
lock.read().await,
lock.read().await,
lock.read().await,
// ...and so on
];
assert!(reads.iter().all(|r| **r == 42));
} // all readers are dropped here.
{
// we can only have one writer at a time.
let mut write = lock.write().await;
*write += 1;
assert_eq!(*write, 43);
} // the writer is dropped here.
}
Implementations§
Source§impl<T> RwLock<T>
impl<T> RwLock<T>
Sourcepub const fn with_max_readers(data: T, max_readers: usize) -> Self
pub const fn with_max_readers(data: T, max_readers: usize) -> Self
Creates a new RwLock
with the given data and maximum number of readers.
Sourcepub async fn write(&self) -> WriteGuard<'_, T>
pub async fn write(&self) -> WriteGuard<'_, T>
Acquires a write lock on the data.
Trait Implementations§
Auto Trait Implementations§
impl<T> !Freeze for RwLock<T>
impl<T> !RefUnwindSafe for RwLock<T>
impl<T> Unpin for RwLock<T>where
T: Unpin,
impl<T> !UnwindSafe for RwLock<T>
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more