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

An asynchronous Mutex-like type.

This type acts similarly to an asynchronous std::sync::Mutex, with one major difference: lock does not block and the lock guard can 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. This section will help you decide on which kind of mutex you should use.

The primary use case of the async mutex is to provide shared mutable access to IO resources such as a database connection. If the data stored behind the mutex is just data, it is often better to use a blocking mutex such as the one in the standard library or parking_lot. This is because the feature that the async mutex offers over the blocking mutex is that it is possible to keep the mutex locked across an .await point, which is rarely necessary for data.

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 _ in 0..5 {
        let my_count = Arc::clone(&count);
        tokio::spawn(async move {
            for _ in 0..10 {
                let mut lock = my_count.lock().await;
                *lock += 1;
                println!("{}", 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. This is why the output of the program above is an in-order count to 50. 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. 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

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

Examples
use tokio::sync::Mutex;

let lock = Mutex::new(5);

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.

Examples
use tokio::sync::Mutex;

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

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

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.

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;
}

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);

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);

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

Formats the value using the given formatter. Read more

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

Performs the conversion.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Performs the conversion.

Returns the argument unchanged.

Calls U::from(self).

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

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.