pub struct Mutex<T>where
    T: ?Sized,{ /* private fields */ }
Expand description

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.

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 tokio::sync::Mutex;
use std::sync::Arc;

#[tokio::main]
async fn main() {
    let data1 = Arc::new(Mutex::new(0));
    let data2 = Arc::clone(&data1);

    tokio::spawn(async move {
        let mut lock = data2.lock().await;
        *lock += 1;
    });

    let mut lock = data1.lock().await;
    *lock += 1;
}
use tokio::sync::Mutex;
use std::sync::Arc;

#[tokio::main]
async fn main() {
    let count = Arc::new(Mutex::new(0));

    for i in 0..5 {
        let my_count = Arc::clone(&count);
        tokio::spawn(async move {
            for j in 0..10 {
                let mut lock = my_count.lock().await;
                *lock += 1;
                println!("{} {} {}", i, j, lock);
            }
        });
    }

    loop {
        if *count.lock().await >= 50 {
            break;
        }
    }
    println!("Count hit 50.");
}

There are a few things of note here to pay attention to in this example.

  1. The mutex is wrapped in an Arc to allow it to be shared across threads.
  2. Each spawned task obtains a lock and releases it on every iteration.
  3. Mutation of the data protected by the Mutex is done by de-referencing the obtained lock as seen on lines 12 and 19.

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> Mutex<T>where T: ?Sized,

pub fn new(t: T) -> Mutex<T>

Creates a new lock in an unlocked state ready for use.

Examples
use tokio::sync::Mutex;

let lock = Mutex::new(5);

pub const fn const_new(t: T) -> Mutex<T>

Available on crate feature parking_lot and non-loom only.

Creates a new lock in an unlocked state ready for use.

Examples
use tokio::sync::Mutex;

static LOCK: Mutex<i32> = Mutex::const_new(5);

pub async fn lock(&self) -> impl Future<Output = 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].

Cancel safety

This method uses a queue to fairly distribute locks in the order they were requested. Cancelling a call to lock makes you lose your place in the queue.

Examples
use tokio::sync::Mutex;

#[tokio::main]
async fn main() {
    let mutex = Mutex::new(1);

    let mut n = mutex.lock().await;
    *n = 2;
}

pub fn blocking_lock(&self) -> MutexGuard<'_, T>

Available on crate feature sync only.

Blockingly locks this Mutex. When the lock has been acquired, function returns a [MutexGuard].

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 std::sync::Arc;
use tokio::sync::Mutex;

#[tokio::main]
async fn main() {
    let mutex =  Arc::new(Mutex::new(1));
    let lock = mutex.lock().await;

    let mutex1 = Arc::clone(&mutex);
    let blocking_task = tokio::task::spawn_blocking(move || {
        // This shall block until the `lock` is released.
        let mut n = mutex1.blocking_lock();
        *n = 2;
    });

    assert_eq!(*lock, 1);
    // Release the lock.
    drop(lock);

    // Await the completion of the blocking task.
    blocking_task.await.unwrap();

    // Assert uncontended.
    let n = mutex.try_lock().unwrap();
    assert_eq!(*n, 2);
}

pub fn blocking_lock_owned(self: Arc<Mutex<T>>) -> OwnedMutexGuard<T>

Available on crate feature sync only.

Blockingly locks this Mutex. When the lock has been acquired, function returns an [OwnedMutexGuard].

This method is identical to Mutex::blocking_lock, except that the returned guard references the Mutex with an Arc rather than by borrowing it. Therefore, the Mutex must be wrapped in an Arc to call this method, and the guard will live for the 'static lifetime, as it keeps the Mutex alive by holding an Arc.

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 std::sync::Arc;
use tokio::sync::Mutex;

#[tokio::main]
async fn main() {
    let mutex =  Arc::new(Mutex::new(1));
    let lock = mutex.lock().await;

    let mutex1 = Arc::clone(&mutex);
    let blocking_task = tokio::task::spawn_blocking(move || {
        // This shall block until the `lock` is released.
        let mut n = mutex1.blocking_lock_owned();
        *n = 2;
    });

    assert_eq!(*lock, 1);
    // Release the lock.
    drop(lock);

    // Await the completion of the blocking task.
    blocking_task.await.unwrap();

    // Assert uncontended.
    let n = mutex.try_lock().unwrap();
    assert_eq!(*n, 2);
}

pub async fn lock_owned( self: Arc<Mutex<T>> ) -> impl Future<Output = 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].

This method is identical to Mutex::lock, except that the returned guard references the Mutex with an Arc rather than by borrowing it. Therefore, the Mutex must be wrapped in an Arc to call this method, and the guard will live for the 'static lifetime, as it keeps the Mutex alive by holding an Arc.

Cancel safety

This method uses a queue to fairly distribute locks in the order they were requested. Cancelling a call to lock_owned makes you lose your place in the queue.

Examples
use tokio::sync::Mutex;
use std::sync::Arc;

#[tokio::main]
async fn main() {
    let mutex = Arc::new(Mutex::new(1));

    let mut n = mutex.clone().lock_owned().await;
    *n = 2;
}

pub fn try_lock(&self) -> Result<MutexGuard<'_, T>, TryLockError>

Attempts to acquire the lock, and returns TryLockError if the lock is currently held somewhere else.

Examples
use tokio::sync::Mutex;

let mutex = Mutex::new(1);

let n = mutex.try_lock()?;
assert_eq!(*n, 1);

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 needs to take place – the mutable borrow statically guarantees no locks exist.

Examples
use tokio::sync::Mutex;

fn main() {
    let mut mutex = Mutex::new(1);

    let n = mutex.get_mut();
    *n = 2;
}

pub fn try_lock_owned( self: Arc<Mutex<T>> ) -> Result<OwnedMutexGuard<T>, TryLockError>

Attempts to acquire the lock, and returns TryLockError if the lock is currently held somewhere else.

This method is identical to Mutex::try_lock, except that the returned guard references the Mutex with an Arc rather than by borrowing it. Therefore, the Mutex must be wrapped in an Arc to call this method, and the guard will live for the 'static lifetime, as it keeps the Mutex alive by holding an Arc.

Examples
use tokio::sync::Mutex;
use std::sync::Arc;

let mutex = Arc::new(Mutex::new(1));

let n = mutex.clone().try_lock_owned()?;
assert_eq!(*n, 1);

pub fn into_inner(self) -> T

Consumes the mutex, returning the underlying data.

Examples
use tokio::sync::Mutex;

#[tokio::main]
async fn main() {
    let mutex = Mutex::new(1);

    let n = mutex.into_inner();
    assert_eq!(n, 1);
}

Trait Implementations§

§

impl<T> Debug for Mutex<T>where T: Debug + ?Sized,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<T> Default for Mutex<T>where T: Default,

§

fn default() -> Mutex<T>

Returns the “default value” for a type. Read more
§

impl<T> From<T> for Mutex<T>

§

fn from(s: T) -> Mutex<T>

Converts to this type from the input type.
§

impl<T> Send for Mutex<T>where T: Send + ?Sized,

§

impl<T> Sync for Mutex<T>where T: Send + ?Sized,

Auto Trait Implementations§

§

impl<T> !RefUnwindSafe for Mutex<T>

§

impl<T: ?Sized> Unpin for Mutex<T>where T: Unpin,

§

impl<T> !UnwindSafe for Mutex<T>

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32 ) -> TaggedParser<'a, Implicit, Self, E>

source§

impl<T> Borrow<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

const: unstable · source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<!> for T

const: unstable · source§

fn from(t: !) -> T

Converts to this type from the input type.
source§

impl<T> From<T> for T

const: unstable · source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for Twhere U: From<T>,

const: unstable · source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = mem::align_of::<T>()

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> Same<T> for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
const: unstable · source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
const: unstable · source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more