pub struct Mutex<T: ?Sized> { /* private fields */ }
Expand description

A simple mutex.

This is mutual-exclusion primitive. It guarantees that only one thread at a time may access the data it protects. When multiple threads attempt to lock the same mutex, only one at a time is allowed to progress, the others will block (sleep) until the mutex is unlocked, at which point another thread will be allowed to wake up and make progress.

Examples


struct Example {
    a: u32,
    b: u32,
}

static EXAMPLE: Mutex<Example> = Mutex::new(Example { a: 10, b: 20 });

fn inc_a(example: &Mutex<Example>) {
    let mut guard = example.lock();
    guard.a += 1;
}

fn sum(example: &Mutex<Example>) -> u32 {
    let guard = example.lock();
    guard.a + guard.b
}

fn try_new(a: u32, b: u32) -> Result<Arc<Mutex<Example>>> {
    Arc::try_new(Mutex::new(Example { a, b }))
}

assert_eq!(EXAMPLE.lock().a, 10);
assert_eq!(sum(&EXAMPLE), 30);

inc_a(&EXAMPLE);

assert_eq!(EXAMPLE.lock().a, 11);
assert_eq!(sum(&EXAMPLE), 31);

Implementations

Creates a new instance of the mutex.

Locks the mutex and gives the caller access to the data protected by it. Only one thread at a time is allowed to access the protected data.

Trait Implementations

The type of the data protected by the lock.
The type of context, if any, that needs to be stored in the guard.
Acquires the lock, making the caller its owner.
Releases the lock, giving up ownership of the lock. Read more
Returns the data protected by the lock.
Reacquires the lock, making the caller its owner. Read more
The parametrised type of the mutual exclusion primitive that can be created by this factory.
Constructs a new instance of the mutual exclusion primitive. Read more
Initialises the lock instance so that it can be safely used.

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Initialises the type instance so that it can be safely used. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
This documentation is an old archive. Please see https://rust.docs.kernel.org instead.