Struct mcs::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.
Examples
use std::sync::Arc; use std::thread; use std::sync::mpsc::channel; use mcs::{Mutex, Slot}; 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 || { let mut slot = Slot::new(); // 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. // // We unwrap() the return value to assert that we are not expecting // threads to ever fail while holding the lock. let mut data = data.lock(&mut slot); *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]
const fn new(value: 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 try_lock<'a>(&'a self, slot: &'a mut Slot) -> Result<Guard<'a, 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 lock<'a>(&'a self, slot: &'a mut Slot) -> Guard<'a, 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.
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.