# Struct ethcore_util::standard::Mutex [−]

    pub struct Mutex<T> where 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`

- 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.
- Allows raw locking & unlocking without a guard.
- Supports eventual fairness so that the mutex is fair on average.
- Optionally allows making the mutex fair by calling `MutexGuard::unlock_fair`.

# 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>`

#### `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> Mutex<T> where T: ?Sized`

#### `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 in 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 `None` is returned. Otherwise, an RAII guard is returned. The lock will be unlocked when the guard is dropped.

This function does not block.

#### `fn try_lock_for(&self, timeout: Duration) -> Option<MutexGuard<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.

#### `fn try_lock_until(&self, timeout: Instant) -> Option<MutexGuard<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.

#### `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.

#### `unsafe fn raw_unlock(&self)`

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.

#### `unsafe fn raw_unlock_fair(&self)`

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<()>`

#### `fn raw_lock(&self)`

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.

#### `fn raw_try_lock(&self) -> bool`

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> Default for Mutex<T> where T: Default + ?Sized`

#### `fn default() -> Mutex<T>`

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

### `impl<T> Sync for Mutex<T> where T: Send`

### `impl<T> Debug for Mutex<T> where T: Debug + ?Sized`

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

Formats the value using the given formatter.

### `impl<T> Send for Mutex<T> where T: Send`

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)