expression

Async mutual exclusion with Tokio Mutex

Await exclusive access without blocking an executor thread while waiting. The guard releases on drop. Keep critical sections small; even an async mutex can deadlock if dependency cycles occur. Prefer an ordinary mutex for short synchronous sections when appropriate. Tokio is an external dependency; see the proposed Cargo manifest. Expected stdout (not executed): 7 Common mistake: Trying to acquire the same non-reentrant lock twice while retaining the first guard.

Formal Syntax & Structure

rust syntaxrust
mutex.lock().await -> MutexGuard<T>

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() {    let lock = tokio::sync::Mutex::new(4);    {        let mut guard = lock.lock().await;        *guard += 3;    }    println!("{}", *lock.lock().await);}
Rust Reference