Mutex<T> (Rust)

Mutex<T> guards data behind a lock so only one thread can access it at a time. In Rust the data lives inside the mutex, so the type system makes it impossible to touch the data without locking first.

Rust

A Mutex ('mutual exclusion') protects shared mutable state. You call .lock(), which blocks until the lock is free and returns a guard; the guard derefs to the inner data, and when it goes out of scope the lock is released automatically. There is no way to forget to unlock.

Because Rust stores the data inside the Mutex, you literally cannot read or write it without acquiring the lock — the compiler enforces correct usage. To share a Mutex across threads it must be wrapped in an Arc: Arc<Mutex<T>> is the canonical shared-mutable-state pattern.

Mutex prevents data races but not deadlocks — locking two mutexes in different orders on different threads can still hang. Keep critical sections short, and consider RwLock when reads vastly outnumber writes.

Syntax

use std::sync::Mutex;
let m = Mutex::new(0);
*m.lock().unwrap() += 1;

Examples

Rust

use std::sync::Mutex;

fn main() {
    let counter = Mutex::new(0);
    {
        let mut n = counter.lock().unwrap();
        *n += 10;
    }
    println!("{}", *counter.lock().unwrap());
}

Output:

10

Learn it in a lesson

See also

Back to the Dictionary