Trait shared_bus::BusMutex

source ·
pub trait BusMutex {
    type Bus;

    // Required methods
    fn create(v: Self::Bus) -> Self;
    fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R;
}
Expand description

Common interface for mutex implementations.

shared-bus needs a mutex to ensure only a single device can access the bus at the same time in concurrent situations. shared-bus already implements this trait for a number of existing mutex types. Most of them are guarded by a feature that needs to be enabled. Here is an overview:

MutexFeature NameNotes
shared_bus::NullMutexalways availableFor sharing within a single execution context.
std::sync::MutexstdFor platforms where std is available.
cortex_m::interrupt::Mutexcortex-mFor Cortex-M platforms; Uses a critcal section (i.e. turns off interrupts during bus transactions).

For other mutex types, a custom implementation is needed. Due to the orphan rule, it might be necessary to wrap it in a newtype. As an example, this is what such a custom implementation might look like:

struct MyMutex<T>(std::sync::Mutex<T>);

impl<T> shared_bus::BusMutex for MyMutex<T> {
    type Bus = T;

    fn create(v: T) -> Self {
        Self(std::sync::Mutex::new(v))
    }

    fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R {
        let mut v = self.0.lock().unwrap();
        f(&mut v)
    }
}

// It is also beneficial to define a type alias for the BusManager
type BusManagerCustom<BUS> = shared_bus::BusManager<MyMutex<BUS>>;

Required Associated Types§

source

type Bus

The actual bus that is wrapped inside this mutex.

Required Methods§

source

fn create(v: Self::Bus) -> Self

Create a new mutex of this type.

source

fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R

Lock the mutex and give a closure access to the bus inside.

Object Safety§

This trait is not object safe.

Implementations on Foreign Types§

source§

impl<T> BusMutex for Mutex<T>

§

type Bus = T

source§

fn create(v: Self::Bus) -> Self

source§

fn lock<R, F: FnOnce(&mut Self::Bus) -> R>(&self, f: F) -> R

Implementors§

source§

impl<BUS> BusMutex for AtomicCheckMutex<BUS>

§

type Bus = BUS

source§

impl<T> BusMutex for NullMutex<T>

§

type Bus = T

source§

impl<T> BusMutex for XtensaMutex<T>

§

type Bus = T

source§

impl<T> BusMutex for CortexMMutex<T>

§

type Bus = T