Struct Mutex
struct Mutex<T: ?Sized> { ... }
A mutual exclusion primitive useful for protecting shared data
This mutex will block threads waiting for the lock to become available. The
mutex can be created via a new constructor. Each mutex has a type parameter
which represents the data that it is protecting. The data can only be accessed
through the RAII guards returned from lock and try_lock, which
guarantees that the data is only ever accessed when the mutex is locked.
Poisoning
The mutexes in this module implement a strategy called "poisoning" where a mutex becomes poisoned if it recognizes that the thread holding it has panicked.
Once a mutex is poisoned, all other threads are unable to access the data by
default as it is likely tainted (some invariant is not being upheld). For a
mutex, this means that the lock and try_lock methods return a
Result which indicates whether a mutex has been poisoned or not. Most
usage of a mutex will simply unwrap() these results, propagating panics
among threads to ensure that a possibly invalid invariant is not witnessed.
Poisoning is only advisory: the PoisonError type has an into_inner
method which will return the guard that would have otherwise been returned
on a successful lock. This allows access to the data, despite the lock being
poisoned.
In addition, the panic detection is not ideal, so even unpoisoned mutexes need to be handled with care, since certain panics may have been skipped. Here is a non-exhaustive list of situations where this might occur:
-
If a mutex is locked while a panic is underway, e.g. within a
Dropimplementation or a panic hook, panicking for the second time while the lock is held will leave the mutex unpoisoned. Note that while double panic usually aborts the program,catch_unwindcan prevent this. -
Locking and unlocking the mutex across different panic contexts, e.g. by storing the guard to a
CellwithinDrop::dropand accessing it outside, or vice versa, can affect poisoning status in an unexpected way. -
Foreign exceptions do not currently trigger poisoning even in absence of other panics.
While this rarely happens in realistic code, unsafe code cannot rely on
poisoning for soundness, since the behavior of poisoning can depend on
outside context. Here's an example of incorrect use of poisoning:
use Mutex;
Examples
use ;
use thread;
use channel;
const N: usize = 10;
// Spawn a few threads to increment a shared variable (non-atomically), and
// let the main thread know once all increments are done.
//
// Here we're using an Arc to share memory among threads, and the data inside
// the Arc is protected with a mutex.
let data = new;
let = channel;
for _ in 0..N
rx.recv.unwrap;
To recover from a poisoned mutex:
use ;
use thread;
let lock = new;
let lock2 = clone;
let _ = spawn.join;
// The lock is poisoned by this point, but the returned result can be
// pattern matched on to return the underlying guard on both branches.
let mut guard = match lock.lock ;
*guard += 1;
To unlock a mutex guard sooner than the end of the enclosing scope, either create an inner scope or drop the guard manually.
use ;
use thread;
const N: usize = 3;
let data_mutex = new;
let res_mutex = new;
let mut threads = Vecwith_capacity;
.for_each;
let mut data = data_mutex.lock.unwrap;
// This is the result of some important and long-ish work.
let result = data.iter.fold;
data.push;
// We drop the `data` explicitly because it's not necessary anymore and the
// thread still has work to do. This allows other threads to start working on
// the data immediately, without waiting for the rest of the unrelated work
// to be done here.
//
// It's even more important here than in the threads because we `.join` the
// threads after that. If we had not dropped the mutex guard, a thread could
// be waiting forever for it, causing a deadlock.
// As in the threads, a block could have been used instead of calling the
// `drop` function.
drop;
// Here the mutex guard is not assigned to a variable and so, even if the
// scope does not end after this line, the mutex is still released: there is
// no deadlock.
*res_mutex.lock.unwrap += result;
threads.into_iter.for_each;
assert_eq!;
Implementations
impl<T> Mutex<T>
const fn new(t: T) -> Mutex<T>Creates a new mutex in an unlocked state ready for use.
Examples
use Mutex; let mutex = new;fn get_cloned(self: &Self) -> Result<T, PoisonError<()>> where T: CloneReturns the contained value by cloning it.
Errors
If another user of this mutex panicked while holding the mutex, then this call will return an error instead.
Examples
use Mutex; let mut mutex = new; assert_eq!;fn set(self: &Self, value: T) -> Result<(), PoisonError<T>>Sets the contained value.
Errors
If another user of this mutex panicked while holding the mutex, then this call will return an error containing the provided
valueinstead.Examples
use Mutex; let mut mutex = new; assert_eq!; mutex.set.unwrap; assert_eq!;fn replace(self: &Self, value: T) -> LockResult<T>Replaces the contained value with
value, and returns the old contained value.Errors
If another user of this mutex panicked while holding the mutex, then this call will return an error containing the provided
valueinstead.Examples
use Mutex; let mut mutex = new; assert_eq!; assert_eq!;
impl<T: ?Sized> Mutex<T>
fn lock(self: &Self) -> LockResult<MutexGuard<'_, T>>Acquires a mutex, blocking the current thread until it is able to do so.
This function will block the local thread until it is available to acquire the mutex. Upon returning, the thread is the only thread with the lock held. An RAII guard is returned to allow scoped unlock of the lock. When the guard goes out of scope, the mutex will be unlocked.
The exact behavior on locking a mutex in the thread which already holds the lock is left unspecified. However, this function will not return on the second call (it might panic or deadlock, for example).
Errors
If another user of this mutex panicked while holding the mutex, then this call will return an error once the mutex is acquired. The acquired mutex guard will be contained in the returned error.
Panics
This function might panic when called if the lock is already held by the current thread.
Examples
use ; use thread; let mutex = new; let c_mutex = clone; spawn.join.expect; assert_eq!;fn try_lock(self: &Self) -> TryLockResult<MutexGuard<'_, T>>Attempts to acquire this lock.
If the lock could not be acquired at this time, then
Erris returned. Otherwise, an RAII guard is returned. The lock will be unlocked when the guard is dropped.This function does not block.
Errors
If another user of this mutex panicked while holding the mutex, then this call will return the
Poisonederror if the mutex would otherwise be acquired. An acquired lock guard will be contained in the returned error.If the mutex could not be acquired because it is already locked, then this call will return the
WouldBlockerror.Examples
use ; use thread; let mutex = new; let c_mutex = clone; spawn.join.expect; assert_eq!;fn is_poisoned(self: &Self) -> boolDetermines whether the mutex is poisoned.
If another thread is active, the mutex can still become poisoned at any time. You should not trust a
falsevalue for program correctness without additional synchronization.Examples
use ; use thread; let mutex = new; let c_mutex = clone; let _ = spawn.join; assert_eq!;fn clear_poison(self: &Self)Clear the poisoned state from a mutex.
If the mutex is poisoned, it will remain poisoned until this function is called. This allows recovering from a poisoned state and marking that it has recovered. For example, if the value is overwritten by a known-good value, then the mutex can be marked as un-poisoned. Or possibly, the value could be inspected to determine if it is in a consistent state, and if so the poison is removed.
Examples
use ; use thread; let mutex = new; let c_mutex = clone; let _ = spawn.join; assert_eq!; let x = mutex.lock.unwrap_or_else; assert_eq!; assert_eq!;fn into_inner(self: Self) -> LockResult<T> where T: SizedConsumes this mutex, returning the underlying data.
Errors
If another user of this mutex panicked while holding the mutex, then this call will return an error containing the underlying data instead.
Examples
use Mutex; let mutex = new; assert_eq!;fn get_mut(self: &mut Self) -> LockResult<&mut T>Returns a mutable reference to the underlying data.
Since this call borrows the
Mutexmutably, no actual locking needs to take place -- the mutable borrow statically guarantees no new locks can be acquired while this reference exists. Note that this method does not clear any previous abandoned locks (e.g., viaforget()on aMutexGuard).Errors
If another user of this mutex panicked while holding the mutex, then this call will return an error containing a mutable reference to the underlying data instead.
Examples
use Mutex; let mut mutex = new; *mutex.get_mut.unwrap = 10; assert_eq!;const fn data_ptr(self: &Self) -> *mut TReturns a raw pointer to the underlying data.
The returned pointer is always non-null and properly aligned, but it is the user's responsibility to ensure that any reads and writes through it are properly synchronized to avoid data races, and that it is not read or written through after the mutex is dropped.
impl<T> Any for Mutex<T>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Mutex<T>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Mutex<T>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> Freeze for Mutex<T>
impl<T> From for Mutex<T>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> From for Mutex<T>
fn from(t: T) -> SelfCreates a new mutex in an unlocked state ready for use. This is equivalent to
Mutex::new.
impl<T> From for Mutex<T>
fn from(t: never) -> T
impl<T> Unpin for Mutex<T>
impl<T> UnsafeUnpin for Mutex<T>
impl<T, U> Into for Mutex<T>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Mutex<T>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Mutex<T>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>
impl<T: ?Sized + Send> Send for Mutex<T>
impl<T: ?Sized + Send> Sync for Mutex<T>
impl<T: ?Sized + fmt::Debug> Debug for Mutex<T>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl<T: ?Sized> RefUnwindSafe for Mutex<T>
impl<T: ?Sized> UnwindSafe for Mutex<T>
impl<T: Default> Default for Mutex<T>
fn default() -> Mutex<T>Creates a
Mutex<T>, with theDefaultvalue for T.