pub type FairMutex<T> = Mutex<RawFairMutex, T>;
Expand description

A mutual exclusive primitive that is always fair, useful for protecting shared data

This mutex will block threads waiting for the lock to become available. The mutex can be statically initialized or created by the 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.

The regular mutex provided by parking_lot uses eventual fairness (after some time it will default to the fair algorithm), but eventual fairness does not provide the same guarantees an always fair method would. Fair mutexes are generally slower, but sometimes needed.

In a fair mutex the waiters form a queue, and the lock is always granted to the next requester in the queue, in first-in first-out order. This ensures that one thread cannot starve others by quickly re-acquiring the lock after releasing it.

A fair mutex may not be interesting if threads have different priorities (this is known as priority inversion).

Differences from the standard library Mutex

  • No poisoning, the lock is released normally on panic.
  • Only requires 1 byte of space, whereas the standard library boxes the FairMutex due to platform limitations.
  • Can be statically constructed.
  • Does not require any drop glue when dropped.
  • Inline fast path for the uncontended case.
  • Efficient handling of micro-contention using adaptive spinning.
  • Allows raw locking & unlocking without a guard.

Examples

use parking_lot::FairMutex;
use std::sync::{Arc, mpsc::channel};
use std::thread;

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 = Arc::new(FairMutex::new(0));

let (tx, rx) = channel();
for _ in 0..10 {
    let (data, tx) = (Arc::clone(&data), tx.clone());
    thread::spawn(move || {
        // The shared state can only be accessed once the lock is held.
        // Our non-atomic increment is safe because we're the only thread
        // which can access the shared state when the lock is held.
        let mut data = data.lock();
        *data += 1;
        if *data == N {
            tx.send(()).unwrap();
        }
        // the lock is unlocked here when `data` goes out of scope.
    });
}

rx.recv().unwrap();

Aliased Type§

struct FairMutex<T> { /* private fields */ }

Implementations§

§

impl<R, T> Mutex<R, T>where R: RawMutex,

pub const fn new(val: T) -> Mutex<R, T>

Creates a new mutex in an unlocked state ready for use.

pub fn into_inner(self) -> T

Consumes this mutex, returning the underlying data.

§

impl<R, T> Mutex<R, T>

pub const fn const_new(raw_mutex: R, val: T) -> Mutex<R, T>

Creates a new mutex based on a pre-existing raw mutex.

This allows creating a mutex in a constant context on stable Rust.

§

impl<R, T> Mutex<R, T>where R: RawMutex, T: ?Sized,

pub fn lock(&self) -> MutexGuard<'_, R, 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 mutex 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.

Attempts to lock a mutex in the thread which already holds the lock will result in a deadlock.

pub fn try_lock(&self) -> Option<MutexGuard<'_, R, T>>

Attempts to acquire this lock.

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 does not block.

pub fn get_mut(&mut self) -> &mut T

Returns a mutable reference to the underlying data.

Since this call borrows the Mutex mutably, no actual locking needs to take place—the mutable borrow statically guarantees no locks exist.

pub fn is_locked(&self) -> bool

Checks whether the mutex is currently locked.

pub unsafe fn force_unlock(&self)

Forcibly unlocks the mutex.

This is useful when combined with mem::forget to hold a lock without the need to maintain a MutexGuard object alive, for example when dealing with FFI.

Safety

This method must only be called if the current thread logically owns a MutexGuard but that guard has been discarded using mem::forget. Behavior is undefined if a mutex is unlocked when not locked.

pub unsafe fn raw(&self) -> &R

Returns the underlying raw mutex object.

Note that you will most likely need to import the RawMutex trait from lock_api to be able to call functions on the raw mutex.

Safety

This method is unsafe because it allows unlocking a mutex while still holding a reference to a MutexGuard.

pub fn data_ptr(&self) -> *mut T

Returns a raw pointer to the underlying data.

This is useful when combined with mem::forget to hold a lock without the need to maintain a MutexGuard object alive, for example when dealing with FFI.

Safety

You must ensure that there are no data races when dereferencing the returned pointer, for example if the current thread logically owns a MutexGuard but that guard has been discarded using mem::forget.

§

impl<R, T> Mutex<R, T>where R: RawMutexFair, T: ?Sized,

pub unsafe fn force_unlock_fair(&self)

Forcibly unlocks the mutex using a fair unlock procotol.

This is useful when combined with mem::forget to hold a lock without the need to maintain a MutexGuard object alive, for example when dealing with FFI.

Safety

This method must only be called if the current thread logically owns a MutexGuard but that guard has been discarded using mem::forget. Behavior is undefined if a mutex is unlocked when not locked.

§

impl<R, T> Mutex<R, T>where R: RawMutexTimed, T: ?Sized,

pub fn try_lock_for( &self, timeout: <R as RawMutexTimed>::Duration ) -> Option<MutexGuard<'_, R, T>>

Attempts to acquire this lock until a timeout is reached.

If the lock could not be acquired before the timeout expired, then None is returned. Otherwise, an RAII guard is returned. The lock will be unlocked when the guard is dropped.

pub fn try_lock_until( &self, timeout: <R as RawMutexTimed>::Instant ) -> Option<MutexGuard<'_, R, T>>

Attempts to acquire this lock until a timeout is reached.

If the lock could not be acquired before the timeout expired, then None is returned. Otherwise, an RAII guard is returned. The lock will be unlocked when the guard is dropped.

Trait Implementations§

§

impl<R, T> Debug for Mutex<R, T>where R: RawMutex, T: Debug + ?Sized,

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl<R, T> Default for Mutex<R, T>where R: RawMutex, T: Default + ?Sized,

§

fn default() -> Mutex<R, T>

Returns the “default value” for a type. Read more
§

impl<R, T> From<T> for Mutex<R, T>where R: RawMutex,

§

fn from(t: T) -> Mutex<R, T>

Converts to this type from the input type.
§

impl<R, T> Send for Mutex<R, T>where R: RawMutex + Send, T: Send + ?Sized,

§

impl<R, T> Sync for Mutex<R, T>where R: RawMutex + Sync, T: Send + ?Sized,