Rust Reference ยท Standard Library Modules
Rust Mutex<T> type
Reference for std::sync::Mutex<T>: lock and try_lock, MutexGuard and unlocking on drop, lock poisoning, Arc sharing, deadlock rules and when to prefer atomics.
std::sync::Mutex<T> is a mutual-exclusion lock that owns the data it protects. The only way to reach the T is to call lock(), which waits until no other thread holds the lock and then returns a MutexGuard<T>. The guard dereferences to the data, and the lock is released when the guard is dropped. Because the data lives inside the mutex, the compiler makes it impossible to touch it without holding the lock.
A Mutex<T> is Sync when T: Send, so it can be shared between threads, usually inside an Arc or by borrowing in scoped threads.
use std::sync::Mutex; let counter = Mutex::new(0); *counter.lock().unwrap() += 1;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> Mutex<T> { pub const fn new(t: T) -> Mutex<T>; pub fn lock(&self) -> LockResult<MutexGuard<'_, T>>; pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>>; pub fn is_poisoned(&self) -> bool; pub fn clear_poison(&self); pub fn into_inner(self) -> LockResult<T>; pub fn get_mut(&mut self) -> LockResult<&mut T>; }
| Name | Description |
|---|---|
t |
The initial value to protect. new is const, so a static M: Mutex<T> needs no lazy wrapper. |
MutexGuard<'_, T> |
Dereferences to T; releases the lock on drop. |
Returns. LockResult<G> is Result<G, PoisonError<G>>. TryLockResult<G> is Result<G, TryLockError<G>>, where TryLockError is either Poisoned(PoisonError<G>) or WouldBlock. into_inner and get_mut need no locking: ownership or an exclusive borrow already guarantees nobody else has access.
Errors and panics.
- An error from
lockmeans a previous holder panicked while holding the guard (the mutex is poisoned). The error still carries the guard: callPoisonError::into_innerto use the data anyway. - Locking a mutex the current thread already holds may deadlock or panic. The behavior is not specified.
lockblocks without a timeout. The standardMutexhas nolock_timeout.
Usage notes
- Keep critical sections short. Hold the guard for the least time possible. Do not do I/O, sleep, or call unknown code while locked.
- Name the guard, or use a block.
*m.lock().unwrap() += 1;unlocks at the end of the statement. Alet guard = ...stays locked until the end of its scope, or until you calldrop(guard). - Lock order. If two threads take locks A and B in opposite orders, they can deadlock. Pick one global order and stick to it.
- Never hold a guard across
.awaitin async code.MutexGuardis notSend, so such futures do not compile on a multi-threaded executor. Use an async-aware mutex from your runtime or restructure the code. - Poisoning is a safeguard, not a requirement. Many programs just call
.unwrap()so the panic spreads. Servers often recover withunwrap_or_else(|e| e.into_inner()). - Use atomics for single numbers. For a plain counter or flag, atomics are cheaper than a mutex.
- Many readers? If reads vastly outnumber writes,
RwLock<T>lets readers share the lock. Mutexis not reentrant and has no fairness guarantee. Since Rust 1.62 it uses a small futex-based implementation on Linux and does not allocate.- Waiting for a condition (queue not empty, job finished) belongs to a
Condvar, which works together with aMutexGuard.
Related
RwLock<T>,Condvar, Atomics,Arc<T>,RefCell<T>- Lessons: Mutex and RwLock, Threads, Send and Sync