[src]

Struct sync::Mutex

pub struct Mutex<T> {
    // some fields omitted
}

A wrapper type which provides synchronized access to the underlying data, of type T. A mutex always provides exclusive access, and concurrent requests will block while the mutex is already locked.

Example

use sync::{Mutex, Arc};

let mutex = Arc::new(Mutex::new(1));
let mutex2 = mutex.clone();

spawn(proc() {
    let mut val = mutex2.lock();
    *val += 1;
    val.cond.signal();
});

let mut value = mutex.lock();
while *value != 2 {
    value.cond.wait();
}

Methods

impl<T: Send> Mutex<T>

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

Creates a new mutex to protect the user-supplied data.

fn new_with_condvars(user_data: T, num_condvars: uint) -> Mutex<T>

Create a new mutex, with a specified number of associated condvars.

This will allow calling wait_on/signal_on/broadcast_on with condvar IDs between 0 and num_condvars-1. (If num_condvars is 0, lock_cond will be allowed but any operations on the condvar will fail.)

fn lock<'a>(&'a self) -> MutexGuard<'a, T>

Access the underlying mutable data with mutual exclusion from other tasks. The returned value is an RAII guard which will unlock the mutex when dropped. All concurrent tasks attempting to lock the mutex will block while the returned value is still alive.

Failure

Failing while inside the Mutex will unlock the Mutex while unwinding, so that other tasks won't block forever. It will also poison the Mutex: any tasks that subsequently try to access it (including those already blocked on the mutex) will also fail immediately.