Struct parking_lot::Mutex [] [src]

pub struct Mutex<T: ?Sized> {
    // some 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.

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 Mutex due to platform limitations.
  • A MutexGuard can be sent to another thread and unlocked there.
  • 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.

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]

fn new(val: T) -> Mutex<T>

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

fn into_inner(self) -> T

Consumes this mutex, returning the underlying data.

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

fn lock(&self) -> 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 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 is a deadlock.

fn try_lock(&self) -> Option<MutexGuard<T>>

Attempts to acquire this lock.

If the lock could not be acquired at this time, then Err is returned. Otherwise, an RAII guard is returned. The lock will be unlocked when the guard is dropped.

This function does not block.

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.

Trait Implementations

impl<T: Send> Send for Mutex<T>
[src]

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

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

fn default() -> Mutex<T>

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

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

fn fmt(&self, f: &mut Formatter) -> Result

Formats the value using the given formatter.