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:
Mutex | Feature Name | Notes |
---|---|---|
shared_bus::NullMutex | always available | For sharing within a single execution context. |
std::sync::Mutex | std | For platforms where std is available. |
cortex_m::interrupt::Mutex | cortex-m | For 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§
Required Methods§
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.