pub struct Mutex<T: ?Sized> { /* private fields */ }Expand description
A single-threaded async mutex.
This mutex is intentionally !Send and !Sync: it is only for tasks that
remain on one runite runtime thread.
§Differences from blocking and multithreaded mutexes
This mutex never blocks an OS thread and does not poison when a holder
panics. Unlike std::sync::Mutex or Tokio’s multithreaded mutex, it has no
Send/owned guard form: guards and wait futures are local to one runtime
thread. Contended waiters are queued FIFO.
§Examples
use std::cell::Cell;
use std::rc::Rc;
use runite::sync::Mutex;
let mutex = Rc::new(Mutex::new(1));
let observed = Rc::new(Cell::new(0));
runite::spawn({
let mutex = Rc::clone(&mutex);
let observed = Rc::clone(&observed);
async move {
let mut guard = mutex.lock().await;
*guard += 41;
observed.set(*guard);
}
});
runite::run();
assert_eq!(observed.get(), 42);
assert_eq!(*mutex.try_lock().expect("mutex should be unlocked"), 42);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>
Waits until the mutex is available and returns a guard.
Waiters are woken in FIFO order. Dropping the returned MutexGuard
releases the mutex to the next waiter, if any.
§Cancellation
Dropping the lock() future before it is selected removes it from the
waiter queue. If it has already been selected but is dropped before
returning a guard, the lock is passed to the next waiter instead of being
leaked.
Sourcepub fn try_lock(&self) -> Option<MutexGuard<'_, T>>
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>>
Attempts to acquire the mutex without waiting.
Returns None if the mutex is currently locked or if queued waiters
should acquire it first.