[−][src]Type Definition parking_lot::FairMutex
type FairMutex<T> = Mutex<RawFairMutex, T>;
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 also be statically initialized or 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.
The regular mutex provided by parking_lot
uses eventual locking fairness
(after some time it will default to the fair algorithm), but eventual
fairness does not provide the same garantees a always fair method would.
Fair mutexes are generally slower, but sometimes needed. This wrapper was
created to avoid using a unfair protocol when it's forbidden by mistake.
In a fair mutex the lock is provided to whichever thread asked first, they form a queue and always follow the first-in first-out order. This means some thread in the queue won't be able to steal the lock and use it fast to increase throughput, at the cost of latency. Since the response time will grow for some threads that are waiting for the lock and losing to faster but later ones, but it may make sending more responses possible.
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 (requires the
const_fn
nightly feature). - 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();