Mutex

Struct Mutex 

Source
pub struct Mutex<T> {
    t: UnsafeCell<T>,
    waiters: SpinLock<VecDeque<ParkHandle>>,
}
Expand description

A mutual exclusion primitive useful for protecting shared data

This mutex will block threads waiting for the lock to become available. The mutex can be created via a new constructor. Each spinlock has a type parameter which represents the data that it is protecting. The data can only be accessed through the guards returned from lock and try_lock, which guarantees that the data is only ever accessed when the mutex is locked.

§Examples

use alloc::sync::Arc;
use keos::sync::Mutex;
use keos::thread;

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));

for _ in 0..N {
    let data = Arc::clone(&data);
    thread::ThreadBuilder::new("work").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.
        //
        // 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().unwrap();
        *data += 1;
        // the lock must be "explicitly" unlocked.
        data.unlock();
    });
}

Fields§

§t: UnsafeCell<T>§waiters: SpinLock<VecDeque<ParkHandle>>

Implementations§

Source§

impl<T> Mutex<T>

Source

pub const fn new(t: T) -> Mutex<T>

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

§Examples
use keos::sync::Mutex;

let mutex = Mutex::new(0);
Source§

impl<T> Mutex<T>

Source

pub 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 lock held. An guard is returned to allow scoped unlock of the lock. When the guard goes out of scope, the mutex will be unlocked.

The exact behavior on locking a mutex in the thread which already holds the lock is left unspecified. However, this function will not return on the second call (it might panic or deadlock, for example).

§Examples
use alloc::sync::Arc;
use keos::sync::Mutex;
use keos::thread;

let mutex = Arc::new(Mutex::new(0));
let c_mutex = Arc::clone(&spinlock);

thread::spawn(move || {
    *c_mutex.lock().unwrap() = 10;
}).join().expect("thread::spawn failed");
assert_eq!(*mutex.lock().unwrap(), 10);
Source

pub fn try_lock(&self) -> Result<MutexGuard<'_, T>, WouldBlock>

Attempts to acquire this lock.

If the lock could not be acquired at this time, then [Err] is returned. Otherwise, an guard is returned.

This function does not block.

§Errors

If the mutex could not be acquired because it is already locked, then this call will return the WouldBlock error.

§Examples
use keos::sync::Mutex;
use alloc::sync::Arc;
use keos::thread;

let mutex = Arc::new(Mutex::new(0));
let c_mutex = Arc::clone(&spinlock);

thread::spawn(move || {
    let mut lock = c_mutex.try_lock();
    if let Ok(ref mut mutex) = lock {
        **mutex = 10;
    } else {
        println!("try_lock failed");
    }
}).join().expect("thread::spawn failed");
assert_eq!(*mutex.lock().unwrap(), 10);
Source

pub fn into_inner(self) -> T
where T: Sized,

Consumes this mutex, returning the underlying data.

§Examples
use keos::sync::Mutex;

let mutex = Mutex::new(0);
assert_eq!(mutex.into_inner().unwrap(), 0);

Trait Implementations§

Source§

impl<T: Default> Default for Mutex<T>

Source§

fn default() -> Mutex<T>

Creates a Mutex<T>, with the Default value for T.

Source§

impl<T: Send> Send for Mutex<T>

Source§

impl<T: Send> Sync for Mutex<T>

Auto Trait Implementations§

§

impl<T> !Freeze for Mutex<T>

§

impl<T> !RefUnwindSafe for Mutex<T>

§

impl<T> Unpin for Mutex<T>
where T: Unpin,

§

impl<T> !UnwindSafe for Mutex<T>

Blanket Implementations§

§

impl<T> Any for T
where T: 'static + ?Sized,

§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> Borrow<T> for T
where T: ?Sized,

§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
§

impl<T> BorrowMut<T> for T
where T: ?Sized,

§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> From<T> for T

§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T, U> Into<U> for T
where U: From<T>,

§

fn into(self) -> U

Calls U::from(self).

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

§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.