pub struct Mutex<T: ?Sized> { /* private fields */ }
Expand description
A mutual exclusion primitive for protecting shared data.
This type is an async version of std::sync::Mutex
.
§Examples
use async_std::sync::{Arc, Mutex};
use async_std::task;
let m = Arc::new(Mutex::new(0));
let mut tasks = vec![];
for _ in 0..10 {
let m = m.clone();
tasks.push(task::spawn(async move {
*m.lock().await += 1;
}));
}
for t in tasks {
t.await.unwrap();
}
assert_eq!(*m.lock().await, 10);
Implementations§
Source§impl<T: ?Sized> Mutex<T>
impl<T: ?Sized> Mutex<T>
Sourcepub async fn lock(&self) -> MutexGuard<'_, T>
pub async fn lock(&self) -> MutexGuard<'_, T>
Acquires the lock.
Returns a guard that releases the lock when dropped.
§Examples
use async_std::sync::{Arc, Mutex};
use async_std::task;
let m1 = Arc::new(Mutex::new(10));
let m2 = m1.clone();
task::spawn(async move {
*m1.lock().await = 20;
})
.await.unwrap();
assert_eq!(*m2.lock().await, 20);
Sourcepub fn try_lock(&self) -> Option<MutexGuard<'_, T>>
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>>
Attempts to acquire the lock.
If the 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::{Arc, Mutex};
use async_std::task;
let m1 = Arc::new(Mutex::new(10));
let m2 = m1.clone();
task::spawn(async move {
if let Some(mut guard) = m1.try_lock() {
*guard = 20;
} else {
println!("try_lock failed");
}
})
.await.unwrap();
assert_eq!(*m2.lock().await, 20);
Sourcepub fn into_inner(self) -> Twhere
T: Sized,
pub fn into_inner(self) -> Twhere
T: Sized,
Consumes the mutex, returning the underlying data.
§Examples
use async_std::sync::Mutex;
let mutex = Mutex::new(10);
assert_eq!(mutex.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 mutex mutably, no actual locking takes place – the mutable borrow statically guarantees no locks exist.
§Examples
use async_std::sync::Mutex;
let mut mutex = Mutex::new(0);
*mutex.get_mut() = 10;
assert_eq!(*mutex.lock().await, 10);
Trait Implementations§
impl<T: ?Sized + Send> Send for Mutex<T>
impl<T: ?Sized + Send> Sync for Mutex<T>
Auto Trait Implementations§
impl<T> !Freeze for Mutex<T>
impl<T> !RefUnwindSafe for Mutex<T>
impl<T> Unpin for Mutex<T>
impl<T> UnwindSafe for Mutex<T>where
T: UnwindSafe + ?Sized,
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