Struct Mutex
struct Mutex<T: ?Sized> { ... }
An asynchronous Mutex-like type.
This type acts similarly to std::sync::Mutex, with two major
differences: lock is an async method so does not block, and the lock
guard is designed to be held across .await points.
Tokio's Mutex operates on a guaranteed FIFO basis.
This means that the order in which tasks call the lock method is
the exact order in which they will acquire the lock.
Which kind of mutex should you use?
Contrary to popular belief, it is ok and often preferred to use the ordinary
Mutex from the standard library in asynchronous code.
The feature that the async mutex offers over the blocking mutex is the
ability to keep it locked across an .await point. This makes the async
mutex more expensive than the blocking mutex, so the blocking mutex should
be preferred in the cases where it can be used. The primary use case for the
async mutex is to provide shared mutable access to IO resources such as a
database connection. If the value behind the mutex is just data, it's
usually appropriate to use a blocking mutex such as the one in the standard
library or parking_lot.
Note that, although the compiler will not prevent the std Mutex from holding
its guard across .await points in situations where the task is not movable
between threads, this virtually never leads to correct concurrent code in
practice as it can easily lead to deadlocks.
A common pattern is to wrap the Arc<Mutex<...>> in a struct that provides
non-async methods for performing operations on the data within, and only
lock the mutex inside these methods. The mini-redis example provides an
illustration of this pattern.
Additionally, when you do want shared access to an IO resource, it is often better to spawn a task to manage the IO resource, and to use message passing to communicate with that task.
Examples:
use Mutex;
use Arc;
async
use Mutex;
use Arc;
async
There are a few things of note here to pay attention to in this example.
- The mutex is wrapped in an
Arcto allow it to be shared across threads. - Each spawned task obtains a lock and releases it on every iteration.
- Mutation of the data protected by the Mutex is done by de-referencing the obtained lock as seen on lines 13 and 20.
Tokio's Mutex works in a simple FIFO (first in, first out) style where all
calls to lock complete in the order they were performed. In that way the
Mutex is "fair" and predictable in how it distributes the locks to inner
data. Locks are released and reacquired after every iteration, so basically,
each thread goes to the back of the line after it increments the value once.
Note that there's some unpredictability to the timing between when the
threads are started, but once they are going they alternate predictably.
Finally, since there is only a single valid lock at any given time, there is
no possibility of a race condition when mutating the inner value.
Note that in contrast to std::sync::Mutex, this implementation does not
poison the mutex when a thread holding the MutexGuard panics. In such a
case, the mutex will be unlocked. If the panic is caught, this might leave
the data protected by the mutex in an inconsistent state.
Implementations
impl<T: ?Sized> Mutex<T>
fn new(t: T) -> Self where T: SizedCreates a new lock in an unlocked state ready for use.
Examples
use Mutex; let lock = new;const fn const_new(t: T) -> Self where T: SizedCreates a new lock in an unlocked state ready for use.
When using the
tracingunstable feature, aMutexcreated withconst_newwill not be instrumented. As such, it will not be visible intokio-console. Instead,Mutex::newshould be used to create an instrumented object if that is needed.Examples
use Mutex; static LOCK: = const_new;async fn lock(self: &Self) -> MutexGuard<'_, T>Locks this mutex, causing the current task to yield until the lock has been acquired. When the lock has been acquired, function returns a
MutexGuard.If the mutex is available to be acquired immediately, then this call will typically not yield to the runtime. However, this is not guaranteed under all circumstances.
Cancel safety
This method uses a queue to fairly distribute locks in the order they were requested. Cancelling a call to
lockmakes you lose your place in the queue.Examples
use Mutex; asyncfn blocking_lock(self: &Self) -> MutexGuard<'_, T>Blockingly locks this
Mutex. When the lock has been acquired, function returns aMutexGuard.This method is intended for use cases where you need to use this mutex in asynchronous code as well as in synchronous code.
Panics
This function panics if called within an asynchronous execution context.
- If you find yourself in an asynchronous execution context and needing
to call some (synchronous) function which performs one of these
blocking_operations, then consider wrapping that call inside [spawn_blocking()][crate::runtime::Handle::spawn_blocking] (or [block_in_place()][crate::task::block_in_place]).
Examples
use Arc; use Mutex; async- If you find yourself in an asynchronous execution context and needing
to call some (synchronous) function which performs one of these
fn blocking_lock_owned(self: Arc<Self>) -> OwnedMutexGuard<T>Blockingly locks this
Mutex. When the lock has been acquired, function returns anOwnedMutexGuard.This method is identical to
Mutex::blocking_lock, except that the returned guard references theMutexwith anArcrather than by borrowing it. Therefore, theMutexmust be wrapped in anArcto call this method, and the guard will live for the'staticlifetime, as it keeps theMutexalive by holding anArc.Panics
This function panics if called within an asynchronous execution context.
- If you find yourself in an asynchronous execution context and needing
to call some (synchronous) function which performs one of these
blocking_operations, then consider wrapping that call inside [spawn_blocking()][crate::runtime::Handle::spawn_blocking] (or [block_in_place()][crate::task::block_in_place]).
Examples
use Arc; use Mutex; async- If you find yourself in an asynchronous execution context and needing
to call some (synchronous) function which performs one of these
async fn lock_owned(self: Arc<Self>) -> OwnedMutexGuard<T>Locks this mutex, causing the current task to yield until the lock has been acquired. When the lock has been acquired, this returns an
OwnedMutexGuard.If the mutex is available to be acquired immediately, then this call will typically not yield to the runtime. However, this is not guaranteed under all circumstances.
This method is identical to
Mutex::lock, except that the returned guard references theMutexwith anArcrather than by borrowing it. Therefore, theMutexmust be wrapped in anArcto call this method, and the guard will live for the'staticlifetime, as it keeps theMutexalive by holding anArc.Cancel safety
This method uses a queue to fairly distribute locks in the order they were requested. Cancelling a call to
lock_ownedmakes you lose your place in the queue.Examples
use Mutex; use Arc; asyncfn try_lock(self: &Self) -> Result<MutexGuard<'_, T>, TryLockError>Attempts to acquire the lock, and returns
TryLockErrorif the lock is currently held somewhere else.Examples
use Mutex; # asyncfn get_mut(self: &mut Self) -> &mut TReturns a mutable reference to the underlying data.
Since this call borrows the
Mutexmutably, no actual locking needs to take place -- the mutable borrow statically guarantees no locks exist.Examples
use Mutex;fn try_lock_owned(self: Arc<Self>) -> Result<OwnedMutexGuard<T>, TryLockError>Attempts to acquire the lock, and returns
TryLockErrorif the lock is currently held somewhere else.This method is identical to
Mutex::try_lock, except that the returned guard references theMutexwith anArcrather than by borrowing it. Therefore, theMutexmust be wrapped in anArcto call this method, and the guard will live for the'staticlifetime, as it keeps theMutexalive by holding anArc.Examples
use Mutex; use Arc; # asyncfn into_inner(self: Self) -> T where T: SizedConsumes the mutex, returning the underlying data.
Examples
use Mutex; async
impl<T> Any for Mutex<T>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Mutex<T>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Mutex<T>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> Debug for Mutex<T>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl<T> Default for Mutex<T>
fn default() -> Self
impl<T> Freeze for Mutex<T>
impl<T> From for Mutex<T>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> From for Mutex<T>
fn from(t: never) -> T
impl<T> From for Mutex<T>
fn from(s: T) -> Self
impl<T> RefUnwindSafe for Mutex<T>
impl<T> Send for Mutex<T>
impl<T> Sync for Mutex<T>
impl<T> Unpin for Mutex<T>
impl<T> UnsafeUnpin for Mutex<T>
impl<T> UnwindSafe for Mutex<T>
impl<T, U> Into for Mutex<T>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Mutex<T>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Mutex<T>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>