Struct parking_lot::Mutex[][src]

pub struct Mutex<T: ?Sized> { /* fields omitted */ }

A mutual exclusion primitive 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.

Fairness

A typical unfair lock can often end up in a situation where a single thread quickly acquires and releases the same mutex in succession, which can starve other threads waiting to acquire the mutex. While this improves performance because it doesn't force a context switch when a thread tries to re-acquire a mutex it has just released, this can starve other threads.

This mutex uses eventual fairness to ensure that the lock will be fair on average without sacrificing performance. This is done by forcing a fair unlock on average every 0.5ms, which will force the lock to go to the next thread waiting for the mutex.

Additionally, any critical section longer than 1ms will always use a fair unlock, which has a negligible performance impact compared to the length of the critical section.

You can also force a fair unlock by calling MutexGuard::unlock_fair when unlocking a mutex instead of simply dropping the MutexGuard.

Differences from the standard library Mutex

Examples

use std::sync::Arc;
use parking_lot::Mutex;
use std::thread;
use std::sync::mpsc::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 = Arc::new(Mutex::new(0));

let (tx, rx) = channel();
for _ in 0..10 {
    let (data, tx) = (data.clone(), 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();

Methods

impl<T> Mutex<T>
[src]

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

Consumes this mutex, returning the underlying data.

impl<T: ?Sized> Mutex<T>
[src]

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.

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.

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.

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.

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.

Releases the mutex.

Safety

This function must only be called if the mutex was locked using raw_lock or raw_try_lock, or if a MutexGuard from this mutex was leaked (e.g. with mem::forget). The mutex must be locked.

Releases the mutex using a fair unlock protocol.

See MutexGuard::unlock_fair.

Safety

This function must only be called if the mutex was locked using raw_lock or raw_try_lock, or if a MutexGuard from this mutex was leaked (e.g. with mem::forget). The mutex must be locked.

impl Mutex<()>
[src]

Acquires a mutex, blocking the current thread until it is able to do so.

This is similar to lock, except that a MutexGuard is not returned. Instead you will need to call raw_unlock to release the mutex.

Attempts to acquire this lock.

This is similar to try_lock, except that a MutexGuard is not returned. Instead you will need to call raw_unlock to release the mutex.

Trait Implementations

impl<T: ?Sized + Send> Send for Mutex<T>
[src]

impl<T: ?Sized + Send> Sync for Mutex<T>
[src]

impl<T: ?Sized + Default> Default for Mutex<T>
[src]

Returns the "default value" for a type. Read more

impl<T: ?Sized + Debug> Debug for Mutex<T>
[src]

Formats the value using the given formatter. Read more