Trait 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.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T> BusMutex for Mutex<T>

Source§

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>

Source§

type Bus = BUS

Source§

impl<T> BusMutex for NullMutex<T>

Source§

type Bus = T

Source§

impl<T> BusMutex for XtensaMutex<T>

Source§

type Bus = T

Source§

impl<T> BusMutex for CortexMMutex<T>

Source§

type Bus = T