pub struct Mutex<T> { /* private fields */ }
Expand description
A spinlock-based mutual exclusion lock for protecting shared data
This mutex will spin with an exponential backoff while waiting for the lock
to become available. 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.
§Fairness
This is not a fair mutex.
§Loom-specific behavior
When cfg(loom)
is enabled, this mutex will use Loom’s simulated atomics,
checked UnsafeCell
, and simulated spin loop hints.
Implementations§
Source§impl<T> Mutex<T>
impl<T> Mutex<T>
Sourcepub const fn new(data: T) -> Self
pub const fn new(data: T) -> Self
Returns a new Mutex
protecting the provided data
.
The returned Mutex
is in an unlocked state, ready for use.
§Examples
use maitake_sync::spin::Mutex;
let mutex = Mutex::new(0);
Sourcepub fn try_lock(&self) -> Option<MutexGuard<'_, T>>
pub fn try_lock(&self) -> Option<MutexGuard<'_, T>>
Attempts to acquire this lock without spinning
If the lock could not be acquired at this time, then None
is returned.
Otherwise, an RAII guard is returned. The lock will be unlocked when the
guard is dropped.
This function will never spin.
Sourcepub fn lock(&self) -> MutexGuard<'_, T>
pub fn lock(&self) -> MutexGuard<'_, T>
Acquires a mutex, spinning until it is locked.
This function will spin until the mutex is available to lock. 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.
Sourcepub unsafe fn force_unlock(&self)
pub unsafe fn force_unlock(&self)
Forcibly unlock the mutex.
If a lock is currently held, it will be released, regardless of who’s holding it. Of course, this is outrageously, disgustingly unsafe and you should never do it.
§Safety
This deliberately violates mutual exclusion.
Only call this method when it is guaranteed that no stack frame that has previously locked the mutex will ever continue executing. Essentially, this is only okay to call when the kernel is oopsing and all code running on other cores has already been killed.