rust-embedded / embedded-hal

A Hardware Abstraction Layer (HAL) for embedded systems
Apache License 2.0
2.01k stars 202 forks source link

Generic Mutex Trait #119

Open Rahix opened 5 years ago

Rahix commented 5 years ago

While writing shared-bus I was hit with the lack of a standardized Mutex type. std solves this by implementing the mutex type differently for all architectures it supports and this is what I currently do in shared-bus as well. However, this is not feasible in the long run, because we want to support all architectures that implement embedded-hal. In my opinion, embedded-hal needs a standardized mutex trait and I would propose it to look similar to the one I have in shared-bus right now:

pub trait BusMutex<T> {
    /// Create a new instance of this mutex type containing the value `v`.
    fn create(v: T) -> Self;

    /// Lock the mutex for the duration of the closure `f`.
    fn lock<R, F: FnOnce(&T) -> R>(&self, f: F) -> R;
}

As explanation:

cc @jamesmunns, @therealprof

eldruin commented 5 years ago

I would also like to use this type for synchronization of the accesses to the I/O pins in the pcf847x I/O expander crate when using the "virtual" pins after a split() and probably similarly in the xca9548a I2C switch crate. What do you guys think about the Bus in the name?

Rahix commented 5 years ago

Oh sorry, the name should probably be just Mutex, BusMutex is what it is called in shared-bus, I forgot to change it ...

therealprof commented 5 years ago

@Rahix seems like a good idea. shared-bus goes a long way towards solving #35 but this really should be more ubiquitous to apply to all applications and architectures and more readily available.

Is the idea of putting BusMutex in the hal traits that we can add additional traits which allow us to directly share busses without having to add extra crates and jump through hoops?

Rahix commented 5 years ago

Well, first of all I would just suggest to add a Mutex trait to embedded-hal that is implemented by each bsp. This allows drivers to have a generic synchronization primitive available.

As soon as that is the case, using shared-bus and the like would be much easier as you no longer have to specify which mutex you want to use via a feature flag. And as @eldruin mentioned, this is also of benefit for other drivers that need to synchronize peripheral accesses.

allow us to directly share busses

No, you will still need shared-bus for the manager and proxy types. We could think about moving them into the hal as well, but I am not sure if that is a good idea ... In my opinion it doesn't hurt to have a different crate for that. The reason it hurts right now is because the mutex type is not in hal.

jonas-schievink commented 4 years ago

This is now in https://github.com/rust-embedded/mutex-trait