[][src]Module embedded_hal::mutex

[]

Generic mutex traits

The traits in this module allow code to be generic over the mutex type used. The types implementing these traits must guarantee that access is always exclusive, even for a RoMutex.

Example Implementation

Std

The following code snippet is a possible implementation of the mutex traits for std's Mutex:

pub struct StdMutex<T>(std::sync::Mutex<T>);

impl<T> mutex::Mutex<T> for StdMutex<T> {
    type CreationError = void::Void;

    fn create(v: T) -> Result<Self, Self::CreationError> {
        Ok(StdMutex(std::sync::Mutex::new(v)))
    }
}

impl<T> mutex::RwMutex<T> for StdMutex<T> {
    type Error = ();

    fn lock_mut<R>(&self, f: impl FnOnce(&mut T) -> R) -> Result<R, Self::Error> {
        // Erase the error type in this example for simplicity
        let mut v = self.0.try_lock().or(Err(()))?;
        Ok(f(&mut v))
    }
}

// RoMutex is implemented automatically by adding the following:
impl<T> mutex::default::DefaultRo for StdMutex<T> { }

// Make use of the mutex:
use embedded_hal::mutex::{Mutex, RoMutex, RwMutex};

let m = StdMutex::create(123).unwrap();
m.lock_mut(|v| {
    assert_eq!(*v, 123);
    *v = 321;
}).unwrap();
m.lock(|v|
    assert_eq!(*v, 321)
).unwrap();

cortex-m

cortex-m uses the bare-metal mutex type, an implementation might look like this:

pub struct CortexMMutex<T>(cortex_m::interrupt::Mutex<T>);

impl<T> mutex::Mutex<T> for CortexMMutex<T> {
    type CreationError = void::Void;

    fn create(v: T) -> Result<Self, Self::CreationError> {
        Ok(CortexMMutex(cortex_m::interrupt::Mutex::new(v)))
    }
}

impl<T> mutex::RoMutex<T> for CortexMMutex<T> {
    type Error = void::Void;

    fn lock<R>(&self, f: impl FnOnce(&T) -> R) -> Result<R, Self::Error> {
        Ok(cortex_m::interrupt::free(|cs| {
            let v = self.0.borrow(cs);
            f(v)
        }))
    }
}

// Implement RwMutex for CortexMMutex<RefCell<T>> automatically:
impl<T> mutex::default::RefCellRw for CortexMMutex<T> { }

// Add a type alias for convenience
type CortexMMutexRw<T> = CortexMMutex<core::cell::RefCell<T>>;

Modules

default

Blanket implementations for RoMutex and RwMutex

Traits

Mutex

A generic mutex abstraction.

RoMutex

A read-only (immutable) mutex.

RwMutex

A read-write (mutable) mutex.