blocking_mutex: refactor to work on stable. No GATs, and can be constructed in const.

This commit is contained in:
Dario Nieuwenhuis 2022-02-11 23:25:30 +01:00
parent 5ae4e20f86
commit 6c925b2342
11 changed files with 289 additions and 173 deletions

View File

@ -2,6 +2,7 @@ use core::cell::Cell;
use core::sync::atomic::{compiler_fence, AtomicU32, AtomicU8, Ordering}; use core::sync::atomic::{compiler_fence, AtomicU32, AtomicU8, Ordering};
use core::{mem, ptr}; use core::{mem, ptr};
use critical_section::CriticalSection; use critical_section::CriticalSection;
use embassy::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy::blocking_mutex::CriticalSectionMutex as Mutex; use embassy::blocking_mutex::CriticalSectionMutex as Mutex;
use embassy::interrupt::{Interrupt, InterruptExt}; use embassy::interrupt::{Interrupt, InterruptExt};
use embassy::time::driver::{AlarmHandle, Driver}; use embassy::time::driver::{AlarmHandle, Driver};
@ -94,7 +95,7 @@ const ALARM_STATE_NEW: AlarmState = AlarmState::new();
embassy::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver { embassy::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver {
period: AtomicU32::new(0), period: AtomicU32::new(0),
alarm_count: AtomicU8::new(0), alarm_count: AtomicU8::new(0),
alarms: Mutex::new([ALARM_STATE_NEW; ALARM_COUNT]), alarms: Mutex::const_new(CriticalSectionRawMutex::new(), [ALARM_STATE_NEW; ALARM_COUNT]),
}); });
impl RtcDriver { impl RtcDriver {

View File

@ -1,7 +1,8 @@
use atomic_polyfill::{AtomicU8, Ordering}; use atomic_polyfill::{AtomicU8, Ordering};
use core::cell::Cell; use core::cell::Cell;
use critical_section::CriticalSection; use critical_section::CriticalSection;
use embassy::blocking_mutex::CriticalSectionMutex as Mutex; use embassy::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy::blocking_mutex::Mutex;
use embassy::interrupt::{Interrupt, InterruptExt}; use embassy::interrupt::{Interrupt, InterruptExt};
use embassy::time::driver::{AlarmHandle, Driver}; use embassy::time::driver::{AlarmHandle, Driver};
@ -20,12 +21,12 @@ const DUMMY_ALARM: AlarmState = AlarmState {
}; };
struct TimerDriver { struct TimerDriver {
alarms: Mutex<[AlarmState; ALARM_COUNT]>, alarms: Mutex<CriticalSectionRawMutex, [AlarmState; ALARM_COUNT]>,
next_alarm: AtomicU8, next_alarm: AtomicU8,
} }
embassy::time_driver_impl!(static DRIVER: TimerDriver = TimerDriver{ embassy::time_driver_impl!(static DRIVER: TimerDriver = TimerDriver{
alarms: Mutex::new([DUMMY_ALARM; ALARM_COUNT]), alarms: Mutex::const_new(CriticalSectionRawMutex::new(), [DUMMY_ALARM; ALARM_COUNT]),
next_alarm: AtomicU8::new(0), next_alarm: AtomicU8::new(0),
}); });

View File

@ -3,13 +3,15 @@ use core::cell::Cell;
use core::convert::TryInto; use core::convert::TryInto;
use core::sync::atomic::{compiler_fence, Ordering}; use core::sync::atomic::{compiler_fence, Ordering};
use core::{mem, ptr}; use core::{mem, ptr};
use embassy::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy::blocking_mutex::Mutex;
use embassy::interrupt::InterruptExt; use embassy::interrupt::InterruptExt;
use embassy::time::driver::{AlarmHandle, Driver}; use embassy::time::driver::{AlarmHandle, Driver};
use embassy::time::TICKS_PER_SECOND; use embassy::time::TICKS_PER_SECOND;
use stm32_metapac::timer::regs; use stm32_metapac::timer::regs;
use crate::interrupt; use crate::interrupt;
use crate::interrupt::{CriticalSection, Interrupt, Mutex}; use crate::interrupt::{CriticalSection, Interrupt};
use crate::pac::timer::{vals, TimGp16}; use crate::pac::timer::{vals, TimGp16};
use crate::peripherals; use crate::peripherals;
use crate::rcc::sealed::RccPeripheral; use crate::rcc::sealed::RccPeripheral;
@ -95,7 +97,7 @@ struct RtcDriver {
period: AtomicU32, period: AtomicU32,
alarm_count: AtomicU8, alarm_count: AtomicU8,
/// Timestamp at which to fire alarm. u64::MAX if no alarm is scheduled. /// Timestamp at which to fire alarm. u64::MAX if no alarm is scheduled.
alarms: Mutex<[AlarmState; ALARM_COUNT]>, alarms: Mutex<CriticalSectionRawMutex, [AlarmState; ALARM_COUNT]>,
} }
const ALARM_STATE_NEW: AlarmState = AlarmState::new(); const ALARM_STATE_NEW: AlarmState = AlarmState::new();
@ -103,7 +105,7 @@ const ALARM_STATE_NEW: AlarmState = AlarmState::new();
embassy::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver { embassy::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver {
period: AtomicU32::new(0), period: AtomicU32::new(0),
alarm_count: AtomicU8::new(0), alarm_count: AtomicU8::new(0),
alarms: Mutex::new([ALARM_STATE_NEW; ALARM_COUNT]), alarms: Mutex::const_new(CriticalSectionRawMutex::new(), [ALARM_STATE_NEW; ALARM_COUNT]),
}); });
impl RtcDriver { impl RtcDriver {

View File

@ -1,20 +0,0 @@
pub trait MutexKind {
type Mutex<T>: super::Mutex<Data = T>;
}
pub enum CriticalSection {}
impl MutexKind for CriticalSection {
type Mutex<T> = super::CriticalSectionMutex<T>;
}
#[cfg(any(cortex_m, feature = "std"))]
pub enum ThreadMode {}
#[cfg(any(cortex_m, feature = "std"))]
impl MutexKind for ThreadMode {
type Mutex<T> = super::ThreadModeMutex<T>;
}
pub enum Noop {}
impl MutexKind for Noop {
type Mutex<T> = super::NoopMutex<T>;
}

View File

@ -1,66 +1,106 @@
//! Blocking mutex (not async) //! Blocking mutex (not async)
pub mod kind; pub mod raw;
use self::raw::RawMutex;
use core::cell::UnsafeCell; use core::cell::UnsafeCell;
use critical_section::CriticalSection;
/// Any object implementing this trait guarantees exclusive access to the data contained /// Any object implementing this trait guarantees exclusive access to the data contained
/// within the mutex for the duration of the lock. /// within the mutex for the duration of the lock.
/// Adapted from <https://github.com/rust-embedded/mutex-trait>. /// Adapted from <https://github.com/rust-embedded/mutex-trait>.
pub trait Mutex { pub struct Mutex<R, T: ?Sized> {
/// Data protected by the mutex. // NOTE: `raw` must be FIRST, so when using ThreadModeMutex the "can't drop in non-thread-mode" gets
type Data; // to run BEFORE dropping `data`.
raw: R,
data: UnsafeCell<T>,
}
fn new(data: Self::Data) -> Self; unsafe impl<R: RawMutex + Send, T: ?Sized + Send> Send for Mutex<R, T> {}
unsafe impl<R: RawMutex + Sync, T: ?Sized + Send> Sync for Mutex<R, T> {}
impl<R: RawMutex, T> Mutex<R, T> {
/// Creates a new mutex in an unlocked state ready for use.
#[cfg(feature = "nightly")]
#[inline]
pub const fn new(val: T) -> Mutex<R, T> {
Mutex {
raw: R::INIT,
data: UnsafeCell::new(val),
}
}
/// Creates a new mutex in an unlocked state ready for use.
#[cfg(not(feature = "nightly"))]
#[inline]
pub fn new(val: T) -> Mutex<R, T> {
Mutex {
raw: R::INIT,
data: UnsafeCell::new(val),
}
}
/// Creates a critical section and grants temporary access to the protected data. /// Creates a critical section and grants temporary access to the protected data.
fn lock<R>(&self, f: impl FnOnce(&Self::Data) -> R) -> R; pub fn lock<U>(&self, f: impl FnOnce(&T) -> U) -> U {
self.raw.lock(|| {
let ptr = self.data.get() as *const T;
let inner = unsafe { &*ptr };
f(inner)
})
}
} }
/// A "mutex" based on critical sections impl<R, T> Mutex<R, T> {
/// Creates a new mutex based on a pre-existing raw mutex.
/// ///
/// # Safety /// This allows creating a mutex in a constant context on stable Rust.
#[inline]
pub const fn const_new(raw_mutex: R, val: T) -> Mutex<R, T> {
Mutex {
raw: raw_mutex,
data: UnsafeCell::new(val),
}
}
/// Consumes this mutex, returning the underlying data.
#[inline]
pub fn into_inner(self) -> T {
self.data.into_inner()
}
/// Returns a mutable reference to the underlying data.
/// ///
/// **This Mutex is only safe on single-core systems.** /// Since this call borrows the `Mutex` mutably, no actual locking needs to
/// /// take place---the mutable borrow statically guarantees no locks exist.
/// On multi-core systems, a `CriticalSection` **is not sufficient** to ensure exclusive access. #[inline]
pub struct CriticalSectionMutex<T> { pub fn get_mut(&mut self) -> &mut T {
inner: UnsafeCell<T>, unsafe { &mut *self.data.get() }
}
// NOTE: A `CriticalSectionMutex` can be used as a channel so the protected data must be `Send`
// to prevent sending non-Sendable stuff (e.g. access tokens) across different
// execution contexts (e.g. interrupts)
unsafe impl<T> Sync for CriticalSectionMutex<T> where T: Send {}
impl<T> CriticalSectionMutex<T> {
/// Creates a new mutex
pub const fn new(value: T) -> Self {
CriticalSectionMutex {
inner: UnsafeCell::new(value),
}
} }
} }
impl<T> CriticalSectionMutex<T> { pub type CriticalSectionMutex<T> = Mutex<raw::CriticalSectionRawMutex, T>;
pub type NoopMutex<T> = Mutex<raw::NoopRawMutex, T>;
impl<T> Mutex<raw::CriticalSectionRawMutex, T> {
/// Borrows the data for the duration of the critical section /// Borrows the data for the duration of the critical section
pub fn borrow<'cs>(&'cs self, _cs: CriticalSection<'cs>) -> &'cs T { pub fn borrow<'cs>(&'cs self, _cs: critical_section::CriticalSection<'cs>) -> &'cs T {
unsafe { &*self.inner.get() } let ptr = self.data.get() as *const T;
unsafe { &*ptr }
} }
} }
impl<T> Mutex for CriticalSectionMutex<T> { impl<T> Mutex<raw::NoopRawMutex, T> {
type Data = T; /// Borrows the data
pub fn borrow(&self) -> &T {
fn new(data: T) -> Self { let ptr = self.data.get() as *const T;
Self::new(data) unsafe { &*ptr }
}
} }
fn lock<R>(&self, f: impl FnOnce(&Self::Data) -> R) -> R { // ThreadModeMutex does NOT use the generic mutex from above because it's special:
critical_section::with(|cs| f(self.borrow(cs))) // it's Send+Sync even if T: !Send. There's no way to do that without specialization (I think?).
} //
} // There's still a ThreadModeRawMutex for use with the generic Mutex (handy with Channel, for example),
// but that will require T: Send even though it shouldn't be needed.
#[cfg(any(cortex_m, feature = "std"))] #[cfg(any(cortex_m, feature = "std"))]
pub use thread_mode_mutex::*; pub use thread_mode_mutex::*;
@ -75,15 +115,15 @@ mod thread_mode_mutex {
/// **This Mutex is only safe on single-core systems.** /// **This Mutex is only safe on single-core systems.**
/// ///
/// On multi-core systems, a `ThreadModeMutex` **is not sufficient** to ensure exclusive access. /// On multi-core systems, a `ThreadModeMutex` **is not sufficient** to ensure exclusive access.
pub struct ThreadModeMutex<T> { pub struct ThreadModeMutex<T: ?Sized> {
inner: UnsafeCell<T>, inner: UnsafeCell<T>,
} }
// NOTE: ThreadModeMutex only allows borrowing from one execution context ever: thread mode. // NOTE: ThreadModeMutex only allows borrowing from one execution context ever: thread mode.
// Therefore it cannot be used to send non-sendable stuff between execution contexts, so it can // Therefore it cannot be used to send non-sendable stuff between execution contexts, so it can
// be Send+Sync even if T is not Send (unlike CriticalSectionMutex) // be Send+Sync even if T is not Send (unlike CriticalSectionMutex)
unsafe impl<T> Sync for ThreadModeMutex<T> {} unsafe impl<T: ?Sized> Sync for ThreadModeMutex<T> {}
unsafe impl<T> Send for ThreadModeMutex<T> {} unsafe impl<T: ?Sized> Send for ThreadModeMutex<T> {}
impl<T> ThreadModeMutex<T> { impl<T> ThreadModeMutex<T> {
/// Creates a new mutex /// Creates a new mutex
@ -92,79 +132,35 @@ mod thread_mode_mutex {
inner: UnsafeCell::new(value), inner: UnsafeCell::new(value),
} }
} }
}
impl<T: ?Sized> ThreadModeMutex<T> {
pub fn lock<R>(&self, f: impl FnOnce(&T) -> R) -> R {
f(self.borrow())
}
/// Borrows the data /// Borrows the data
pub fn borrow(&self) -> &T { pub fn borrow(&self) -> &T {
assert!( assert!(
in_thread_mode(), raw::in_thread_mode(),
"ThreadModeMutex can only be borrowed from thread mode." "ThreadModeMutex can only be borrowed from thread mode."
); );
unsafe { &*self.inner.get() } unsafe { &*self.inner.get() }
} }
} }
impl<T> Mutex for ThreadModeMutex<T> { impl<T: ?Sized> Drop for ThreadModeMutex<T> {
type Data = T;
fn new(data: T) -> Self {
Self::new(data)
}
fn lock<R>(&self, f: impl FnOnce(&Self::Data) -> R) -> R {
f(self.borrow())
}
}
impl<T> Drop for ThreadModeMutex<T> {
fn drop(&mut self) { fn drop(&mut self) {
// Only allow dropping from thread mode. Dropping calls drop on the inner `T`, so // Only allow dropping from thread mode. Dropping calls drop on the inner `T`, so
// `drop` needs the same guarantees as `lock`. `ThreadModeMutex<T>` is Send even if // `drop` needs the same guarantees as `lock`. `ThreadModeMutex<T>` is Send even if
// T isn't, so without this check a user could create a ThreadModeMutex in thread mode, // T isn't, so without this check a user could create a ThreadModeMutex in thread mode,
// send it to interrupt context and drop it there, which would "send" a T even if T is not Send. // send it to interrupt context and drop it there, which would "send" a T even if T is not Send.
assert!( assert!(
in_thread_mode(), raw::in_thread_mode(),
"ThreadModeMutex can only be dropped from thread mode." "ThreadModeMutex can only be dropped from thread mode."
); );
// Drop of the inner `T` happens after this. // Drop of the inner `T` happens after this.
} }
} }
pub fn in_thread_mode() -> bool {
#[cfg(feature = "std")]
return Some("main") == std::thread::current().name();
#[cfg(not(feature = "std"))]
return cortex_m::peripheral::SCB::vect_active()
== cortex_m::peripheral::scb::VectActive::ThreadMode;
}
}
/// A "mutex" that does nothing and cannot be shared between threads.
pub struct NoopMutex<T> {
inner: T,
}
impl<T> NoopMutex<T> {
pub const fn new(value: T) -> Self {
NoopMutex { inner: value }
}
}
impl<T> NoopMutex<T> {
pub fn borrow(&self) -> &T {
&self.inner
}
}
impl<T> Mutex for NoopMutex<T> {
type Data = T;
fn new(data: T) -> Self {
Self::new(data)
}
fn lock<R>(&self, f: impl FnOnce(&Self::Data) -> R) -> R {
f(self.borrow())
}
} }

View File

@ -0,0 +1,112 @@
use core::marker::PhantomData;
pub trait RawMutex {
const INIT: Self;
fn lock<R>(&self, f: impl FnOnce() -> R) -> R;
}
pub struct CriticalSectionRawMutex {
_phantom: PhantomData<()>,
}
unsafe impl Send for CriticalSectionRawMutex {}
unsafe impl Sync for CriticalSectionRawMutex {}
impl CriticalSectionRawMutex {
pub const fn new() -> Self {
Self {
_phantom: PhantomData,
}
}
}
impl RawMutex for CriticalSectionRawMutex {
const INIT: Self = Self::new();
fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
critical_section::with(|_| f())
}
}
// ================
pub struct NoopRawMutex {
_phantom: PhantomData<*mut ()>,
}
unsafe impl Send for NoopRawMutex {}
impl NoopRawMutex {
pub const fn new() -> Self {
Self {
_phantom: PhantomData,
}
}
}
impl RawMutex for NoopRawMutex {
const INIT: Self = Self::new();
fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
f()
}
}
// ================
#[cfg(any(cortex_m, feature = "std"))]
mod thread_mode {
use super::*;
pub struct ThreadModeRawMutex {
_phantom: PhantomData<()>,
}
unsafe impl Send for ThreadModeRawMutex {}
unsafe impl Sync for ThreadModeRawMutex {}
impl ThreadModeRawMutex {
pub const fn new() -> Self {
Self {
_phantom: PhantomData,
}
}
}
impl RawMutex for ThreadModeRawMutex {
const INIT: Self = Self::new();
fn lock<R>(&self, f: impl FnOnce() -> R) -> R {
assert!(
in_thread_mode(),
"ThreadModeMutex can only be locked from thread mode."
);
f()
}
}
impl Drop for ThreadModeRawMutex {
fn drop(&mut self) {
// Only allow dropping from thread mode. Dropping calls drop on the inner `T`, so
// `drop` needs the same guarantees as `lock`. `ThreadModeMutex<T>` is Send even if
// T isn't, so without this check a user could create a ThreadModeMutex in thread mode,
// send it to interrupt context and drop it there, which would "send" a T even if T is not Send.
assert!(
in_thread_mode(),
"ThreadModeMutex can only be dropped from thread mode."
);
// Drop of the inner `T` happens after this.
}
}
pub(crate) fn in_thread_mode() -> bool {
#[cfg(feature = "std")]
return Some("main") == std::thread::current().name();
#[cfg(not(feature = "std"))]
return cortex_m::peripheral::SCB::vect_active()
== cortex_m::peripheral::scb::VectActive::ThreadMode;
}
}
#[cfg(any(cortex_m, feature = "std"))]
pub use thread_mode::*;

View File

@ -47,7 +47,7 @@ use core::task::Waker;
use futures::Future; use futures::Future;
use heapless::Deque; use heapless::Deque;
use crate::blocking_mutex::kind::MutexKind; use crate::blocking_mutex::raw::RawMutex;
use crate::blocking_mutex::Mutex; use crate::blocking_mutex::Mutex;
use crate::waitqueue::WakerRegistration; use crate::waitqueue::WakerRegistration;
@ -56,7 +56,7 @@ use crate::waitqueue::WakerRegistration;
/// Instances are created by the [`split`](split) function. /// Instances are created by the [`split`](split) function.
pub struct Sender<'ch, M, T, const N: usize> pub struct Sender<'ch, M, T, const N: usize>
where where
M: MutexKind, M: RawMutex,
{ {
channel: &'ch Channel<M, T, N>, channel: &'ch Channel<M, T, N>,
} }
@ -66,7 +66,7 @@ where
/// Instances are created by the [`split`](split) function. /// Instances are created by the [`split`](split) function.
pub struct Receiver<'ch, M, T, const N: usize> pub struct Receiver<'ch, M, T, const N: usize>
where where
M: MutexKind, M: RawMutex,
{ {
channel: &'ch Channel<M, T, N>, channel: &'ch Channel<M, T, N>,
} }
@ -99,7 +99,7 @@ pub fn split<M, T, const N: usize>(
channel: &mut Channel<M, T, N>, channel: &mut Channel<M, T, N>,
) -> (Sender<M, T, N>, Receiver<M, T, N>) ) -> (Sender<M, T, N>, Receiver<M, T, N>)
where where
M: MutexKind, M: RawMutex,
{ {
let sender = Sender { channel }; let sender = Sender { channel };
let receiver = Receiver { channel }; let receiver = Receiver { channel };
@ -112,7 +112,7 @@ where
impl<'ch, M, T, const N: usize> Receiver<'ch, M, T, N> impl<'ch, M, T, const N: usize> Receiver<'ch, M, T, N>
where where
M: MutexKind, M: RawMutex,
{ {
/// Receives the next value for this receiver. /// Receives the next value for this receiver.
/// ///
@ -161,7 +161,7 @@ where
impl<'ch, M, T, const N: usize> Drop for Receiver<'ch, M, T, N> impl<'ch, M, T, const N: usize> Drop for Receiver<'ch, M, T, N>
where where
M: MutexKind, M: RawMutex,
{ {
fn drop(&mut self) { fn drop(&mut self) {
self.channel.lock(|c| c.deregister_receiver()) self.channel.lock(|c| c.deregister_receiver())
@ -170,14 +170,14 @@ where
pub struct RecvFuture<'ch, M, T, const N: usize> pub struct RecvFuture<'ch, M, T, const N: usize>
where where
M: MutexKind, M: RawMutex,
{ {
channel: &'ch Channel<M, T, N>, channel: &'ch Channel<M, T, N>,
} }
impl<'ch, M, T, const N: usize> Future for RecvFuture<'ch, M, T, N> impl<'ch, M, T, const N: usize> Future for RecvFuture<'ch, M, T, N>
where where
M: MutexKind, M: RawMutex,
{ {
type Output = Option<T>; type Output = Option<T>;
@ -193,7 +193,7 @@ where
impl<'ch, M, T, const N: usize> Sender<'ch, M, T, N> impl<'ch, M, T, const N: usize> Sender<'ch, M, T, N>
where where
M: MutexKind, M: RawMutex,
{ {
/// Sends a value, waiting until there is capacity. /// Sends a value, waiting until there is capacity.
/// ///
@ -268,7 +268,7 @@ where
pub struct SendFuture<'ch, M, T, const N: usize> pub struct SendFuture<'ch, M, T, const N: usize>
where where
M: MutexKind, M: RawMutex,
{ {
channel: &'ch Channel<M, T, N>, channel: &'ch Channel<M, T, N>,
message: Option<T>, message: Option<T>,
@ -276,7 +276,7 @@ where
impl<'ch, M, T, const N: usize> Future for SendFuture<'ch, M, T, N> impl<'ch, M, T, const N: usize> Future for SendFuture<'ch, M, T, N>
where where
M: MutexKind, M: RawMutex,
{ {
type Output = Result<(), SendError<T>>; type Output = Result<(), SendError<T>>;
@ -295,18 +295,18 @@ where
} }
} }
impl<'ch, M, T, const N: usize> Unpin for SendFuture<'ch, M, T, N> where M: MutexKind {} impl<'ch, M, T, const N: usize> Unpin for SendFuture<'ch, M, T, N> where M: RawMutex {}
struct CloseFuture<'ch, M, T, const N: usize> struct CloseFuture<'ch, M, T, const N: usize>
where where
M: MutexKind, M: RawMutex,
{ {
channel: &'ch Channel<M, T, N>, channel: &'ch Channel<M, T, N>,
} }
impl<'ch, M, T, const N: usize> Future for CloseFuture<'ch, M, T, N> impl<'ch, M, T, const N: usize> Future for CloseFuture<'ch, M, T, N>
where where
M: MutexKind, M: RawMutex,
{ {
type Output = (); type Output = ();
@ -321,7 +321,7 @@ where
impl<'ch, M, T, const N: usize> Drop for Sender<'ch, M, T, N> impl<'ch, M, T, const N: usize> Drop for Sender<'ch, M, T, N>
where where
M: MutexKind, M: RawMutex,
{ {
fn drop(&mut self) { fn drop(&mut self) {
self.channel.lock(|c| c.deregister_sender()) self.channel.lock(|c| c.deregister_sender())
@ -330,7 +330,7 @@ where
impl<'ch, M, T, const N: usize> Clone for Sender<'ch, M, T, N> impl<'ch, M, T, const N: usize> Clone for Sender<'ch, M, T, N>
where where
M: MutexKind, M: RawMutex,
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
self.channel.lock(|c| c.register_sender()); self.channel.lock(|c| c.register_sender());
@ -546,30 +546,50 @@ impl<T, const N: usize> ChannelState<T, N> {
/// All data sent will become available in the same order as it was sent. /// All data sent will become available in the same order as it was sent.
pub struct Channel<M, T, const N: usize> pub struct Channel<M, T, const N: usize>
where where
M: MutexKind, M: RawMutex,
{ {
inner: M::Mutex<RefCell<ChannelState<T, N>>>, inner: Mutex<M, RefCell<ChannelState<T, N>>>,
} }
impl<M, T, const N: usize> Channel<M, T, N> impl<M, T, const N: usize> Channel<M, T, N>
where where
M: MutexKind, M: RawMutex,
{ {
/// Establish a new bounded channel. For example, to create one with a NoopMutex: /// Establish a new bounded channel. For example, to create one with a NoopMutex:
/// ///
/// ``` /// ```
/// use embassy::channel::mpsc; /// use embassy::channel::mpsc;
/// use embassy::blocking_mutex::kind::Noop; /// use embassy::blocking_mutex::raw::NoopRawMutex;
/// use embassy::channel::mpsc::Channel; /// use embassy::channel::mpsc::Channel;
/// ///
/// // Declare a bounded channel of 3 u32s. /// // Declare a bounded channel of 3 u32s.
/// let mut channel = Channel::<Noop, u32, 3>::new(); /// let mut channel = Channel::<NoopRawMutex, u32, 3>::new();
/// // once we have a channel, obtain its sender and receiver /// // once we have a channel, obtain its sender and receiver
/// let (sender, receiver) = mpsc::split(&mut channel); /// let (sender, receiver) = mpsc::split(&mut channel);
/// ``` /// ```
#[cfg(feature = "nightly")]
pub const fn new() -> Self {
Self {
inner: Mutex::new(RefCell::new(ChannelState::new())),
}
}
/// Establish a new bounded channel. For example, to create one with a NoopMutex:
///
/// ```
/// use embassy::channel::mpsc;
/// use embassy::blocking_mutex::raw::NoopRawMutex;
/// use embassy::channel::mpsc::Channel;
///
/// // Declare a bounded channel of 3 u32s.
/// let mut channel = Channel::<NoopRawMutex, u32, 3>::new();
/// // once we have a channel, obtain its sender and receiver
/// let (sender, receiver) = mpsc::split(&mut channel);
/// ```
#[cfg(not(feature = "nightly"))]
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
inner: M::Mutex::new(RefCell::new(ChannelState::new())), inner: Mutex::new(RefCell::new(ChannelState::new())),
} }
} }
@ -586,7 +606,7 @@ mod tests {
use futures_executor::ThreadPool; use futures_executor::ThreadPool;
use futures_timer::Delay; use futures_timer::Delay;
use crate::blocking_mutex::kind::{CriticalSection, Noop}; use crate::blocking_mutex::raw::{CriticalSectionRawMutex, NoopRawMutex};
use crate::util::Forever; use crate::util::Forever;
use super::*; use super::*;
@ -655,7 +675,7 @@ mod tests {
#[test] #[test]
fn simple_send_and_receive() { fn simple_send_and_receive() {
let mut c = Channel::<Noop, u32, 3>::new(); let mut c = Channel::<NoopRawMutex, u32, 3>::new();
let (s, r) = split(&mut c); let (s, r) = split(&mut c);
assert!(s.clone().try_send(1).is_ok()); assert!(s.clone().try_send(1).is_ok());
assert_eq!(r.try_recv().unwrap(), 1); assert_eq!(r.try_recv().unwrap(), 1);
@ -663,7 +683,7 @@ mod tests {
#[test] #[test]
fn should_close_without_sender() { fn should_close_without_sender() {
let mut c = Channel::<Noop, u32, 3>::new(); let mut c = Channel::<NoopRawMutex, u32, 3>::new();
let (s, r) = split(&mut c); let (s, r) = split(&mut c);
drop(s); drop(s);
match r.try_recv() { match r.try_recv() {
@ -674,7 +694,7 @@ mod tests {
#[test] #[test]
fn should_close_once_drained() { fn should_close_once_drained() {
let mut c = Channel::<Noop, u32, 3>::new(); let mut c = Channel::<NoopRawMutex, u32, 3>::new();
let (s, r) = split(&mut c); let (s, r) = split(&mut c);
assert!(s.try_send(1).is_ok()); assert!(s.try_send(1).is_ok());
drop(s); drop(s);
@ -687,7 +707,7 @@ mod tests {
#[test] #[test]
fn should_reject_send_when_receiver_dropped() { fn should_reject_send_when_receiver_dropped() {
let mut c = Channel::<Noop, u32, 3>::new(); let mut c = Channel::<NoopRawMutex, u32, 3>::new();
let (s, r) = split(&mut c); let (s, r) = split(&mut c);
drop(r); drop(r);
match s.try_send(1) { match s.try_send(1) {
@ -698,7 +718,7 @@ mod tests {
#[test] #[test]
fn should_reject_send_when_channel_closed() { fn should_reject_send_when_channel_closed() {
let mut c = Channel::<Noop, u32, 3>::new(); let mut c = Channel::<NoopRawMutex, u32, 3>::new();
let (s, mut r) = split(&mut c); let (s, mut r) = split(&mut c);
assert!(s.try_send(1).is_ok()); assert!(s.try_send(1).is_ok());
r.close(); r.close();
@ -714,7 +734,7 @@ mod tests {
async fn receiver_closes_when_sender_dropped_async() { async fn receiver_closes_when_sender_dropped_async() {
let executor = ThreadPool::new().unwrap(); let executor = ThreadPool::new().unwrap();
static CHANNEL: Forever<Channel<CriticalSection, u32, 3>> = Forever::new(); static CHANNEL: Forever<Channel<CriticalSectionRawMutex, u32, 3>> = Forever::new();
let c = CHANNEL.put(Channel::new()); let c = CHANNEL.put(Channel::new());
let (s, mut r) = split(c); let (s, mut r) = split(c);
assert!(executor assert!(executor
@ -729,7 +749,7 @@ mod tests {
async fn receiver_receives_given_try_send_async() { async fn receiver_receives_given_try_send_async() {
let executor = ThreadPool::new().unwrap(); let executor = ThreadPool::new().unwrap();
static CHANNEL: Forever<Channel<CriticalSection, u32, 3>> = Forever::new(); static CHANNEL: Forever<Channel<CriticalSectionRawMutex, u32, 3>> = Forever::new();
let c = CHANNEL.put(Channel::new()); let c = CHANNEL.put(Channel::new());
let (s, mut r) = split(c); let (s, mut r) = split(c);
assert!(executor assert!(executor
@ -742,7 +762,7 @@ mod tests {
#[futures_test::test] #[futures_test::test]
async fn sender_send_completes_if_capacity() { async fn sender_send_completes_if_capacity() {
let mut c = Channel::<CriticalSection, u32, 1>::new(); let mut c = Channel::<CriticalSectionRawMutex, u32, 1>::new();
let (s, mut r) = split(&mut c); let (s, mut r) = split(&mut c);
assert!(s.send(1).await.is_ok()); assert!(s.send(1).await.is_ok());
assert_eq!(r.recv().await, Some(1)); assert_eq!(r.recv().await, Some(1));
@ -750,7 +770,7 @@ mod tests {
#[futures_test::test] #[futures_test::test]
async fn sender_send_completes_if_closed() { async fn sender_send_completes_if_closed() {
static CHANNEL: Forever<Channel<CriticalSection, u32, 1>> = Forever::new(); static CHANNEL: Forever<Channel<CriticalSectionRawMutex, u32, 1>> = Forever::new();
let c = CHANNEL.put(Channel::new()); let c = CHANNEL.put(Channel::new());
let (s, r) = split(c); let (s, r) = split(c);
drop(r); drop(r);
@ -764,7 +784,7 @@ mod tests {
async fn senders_sends_wait_until_capacity() { async fn senders_sends_wait_until_capacity() {
let executor = ThreadPool::new().unwrap(); let executor = ThreadPool::new().unwrap();
static CHANNEL: Forever<Channel<CriticalSection, u32, 1>> = Forever::new(); static CHANNEL: Forever<Channel<CriticalSectionRawMutex, u32, 1>> = Forever::new();
let c = CHANNEL.put(Channel::new()); let c = CHANNEL.put(Channel::new());
let (s0, mut r) = split(c); let (s0, mut r) = split(c);
assert!(s0.try_send(1).is_ok()); assert!(s0.try_send(1).is_ok());
@ -784,7 +804,7 @@ mod tests {
#[futures_test::test] #[futures_test::test]
async fn sender_close_completes_if_closing() { async fn sender_close_completes_if_closing() {
static CHANNEL: Forever<Channel<CriticalSection, u32, 1>> = Forever::new(); static CHANNEL: Forever<Channel<CriticalSectionRawMutex, u32, 1>> = Forever::new();
let c = CHANNEL.put(Channel::new()); let c = CHANNEL.put(Channel::new());
let (s, mut r) = split(c); let (s, mut r) = split(c);
r.close(); r.close();
@ -793,7 +813,7 @@ mod tests {
#[futures_test::test] #[futures_test::test]
async fn sender_close_completes_if_closed() { async fn sender_close_completes_if_closed() {
static CHANNEL: Forever<Channel<CriticalSection, u32, 1>> = Forever::new(); static CHANNEL: Forever<Channel<CriticalSectionRawMutex, u32, 1>> = Forever::new();
let c = CHANNEL.put(Channel::new()); let c = CHANNEL.put(Channel::new());
let (s, r) = split(c); let (s, r) = split(c);
drop(r); drop(r);

View File

@ -2,7 +2,8 @@ use core::cell::Cell;
use core::mem; use core::mem;
use core::task::Waker; use core::task::Waker;
use crate::blocking_mutex::CriticalSectionMutex as Mutex; use crate::blocking_mutex::raw::CriticalSectionRawMutex;
use crate::blocking_mutex::Mutex;
/// Utility struct to register and wake a waker. /// Utility struct to register and wake a waker.
#[derive(Debug)] #[derive(Debug)]
@ -50,13 +51,13 @@ impl WakerRegistration {
/// Utility struct to register and wake a waker. /// Utility struct to register and wake a waker.
pub struct AtomicWaker { pub struct AtomicWaker {
waker: Mutex<Cell<Option<Waker>>>, waker: Mutex<CriticalSectionRawMutex, Cell<Option<Waker>>>,
} }
impl AtomicWaker { impl AtomicWaker {
pub const fn new() -> Self { pub const fn new() -> Self {
Self { Self {
waker: Mutex::new(Cell::new(None)), waker: Mutex::const_new(CriticalSectionRawMutex::new(), Cell::new(None)),
} }
} }

View File

@ -6,7 +6,7 @@
mod example_common; mod example_common;
use defmt::unwrap; use defmt::unwrap;
use embassy::blocking_mutex::kind::Noop; use embassy::blocking_mutex::raw::NoopRawMutex;
use embassy::channel::mpsc::{self, Channel, Sender, TryRecvError}; use embassy::channel::mpsc::{self, Channel, Sender, TryRecvError};
use embassy::executor::Spawner; use embassy::executor::Spawner;
use embassy::time::{Duration, Timer}; use embassy::time::{Duration, Timer};
@ -19,10 +19,10 @@ enum LedState {
Off, Off,
} }
static CHANNEL: Forever<Channel<Noop, LedState, 1>> = Forever::new(); static CHANNEL: Forever<Channel<NoopRawMutex, LedState, 1>> = Forever::new();
#[embassy::task(pool_size = 1)] #[embassy::task(pool_size = 1)]
async fn my_task(sender: Sender<'static, Noop, LedState, 1>) { async fn my_task(sender: Sender<'static, NoopRawMutex, LedState, 1>) {
loop { loop {
let _ = sender.send(LedState::On).await; let _ = sender.send(LedState::On).await;
Timer::after(Duration::from_secs(1)).await; Timer::after(Duration::from_secs(1)).await;

View File

@ -6,7 +6,7 @@
mod example_common; mod example_common;
use example_common::*; use example_common::*;
use embassy::blocking_mutex::kind::Noop; use embassy::blocking_mutex::raw::NoopRawMutex;
use embassy::channel::mpsc::{self, Channel, Sender}; use embassy::channel::mpsc::{self, Channel, Sender};
use embassy::executor::Spawner; use embassy::executor::Spawner;
use embassy::util::Forever; use embassy::util::Forever;
@ -15,7 +15,7 @@ use embassy_nrf::peripherals::UARTE0;
use embassy_nrf::uarte::UarteRx; use embassy_nrf::uarte::UarteRx;
use embassy_nrf::{interrupt, uarte, Peripherals}; use embassy_nrf::{interrupt, uarte, Peripherals};
static CHANNEL: Forever<Channel<Noop, [u8; 8], 1>> = Forever::new(); static CHANNEL: Forever<Channel<NoopRawMutex, [u8; 8], 1>> = Forever::new();
#[embassy::main] #[embassy::main]
async fn main(spawner: Spawner, p: Peripherals) { async fn main(spawner: Spawner, p: Peripherals) {
@ -57,7 +57,7 @@ async fn main(spawner: Spawner, p: Peripherals) {
} }
#[embassy::task] #[embassy::task]
async fn reader(mut rx: UarteRx<'static, UARTE0>, s: Sender<'static, Noop, [u8; 8], 1>) { async fn reader(mut rx: UarteRx<'static, UARTE0>, s: Sender<'static, NoopRawMutex, [u8; 8], 1>) {
let mut buf = [0; 8]; let mut buf = [0; 8];
loop { loop {
info!("reading..."); info!("reading...");

View File

@ -12,7 +12,7 @@
#[path = "../example_common.rs"] #[path = "../example_common.rs"]
mod example_common; mod example_common;
use embassy::blocking_mutex::kind::Noop; use embassy::blocking_mutex::raw::NoopRawMutex;
use embassy::channel::mpsc::{self, Channel, Receiver, Sender}; use embassy::channel::mpsc::{self, Channel, Receiver, Sender};
use embassy::executor::Spawner; use embassy::executor::Spawner;
use embassy::time::{with_timeout, Duration, Timer}; use embassy::time::{with_timeout, Duration, Timer};
@ -77,7 +77,7 @@ enum ButtonEvent {
Hold, Hold,
} }
static BUTTON_EVENTS_QUEUE: Forever<Channel<Noop, ButtonEvent, 4>> = Forever::new(); static BUTTON_EVENTS_QUEUE: Forever<Channel<NoopRawMutex, ButtonEvent, 4>> = Forever::new();
#[embassy::main] #[embassy::main]
async fn main(spawner: Spawner, p: Peripherals) { async fn main(spawner: Spawner, p: Peripherals) {
@ -103,7 +103,10 @@ async fn main(spawner: Spawner, p: Peripherals) {
} }
#[embassy::task] #[embassy::task]
async fn led_blinker(mut leds: Leds<'static>, queue: Receiver<'static, Noop, ButtonEvent, 4>) { async fn led_blinker(
mut leds: Leds<'static>,
queue: Receiver<'static, NoopRawMutex, ButtonEvent, 4>,
) {
loop { loop {
leds.blink().await; leds.blink().await;
match queue.try_recv() { match queue.try_recv() {
@ -121,7 +124,7 @@ async fn led_blinker(mut leds: Leds<'static>, queue: Receiver<'static, Noop, But
#[embassy::task] #[embassy::task]
async fn button_waiter( async fn button_waiter(
mut button: ExtiInput<'static, PA0>, mut button: ExtiInput<'static, PA0>,
queue: Sender<'static, Noop, ButtonEvent, 4>, queue: Sender<'static, NoopRawMutex, ButtonEvent, 4>,
) { ) {
const DOUBLE_CLICK_DELAY: u64 = 250; const DOUBLE_CLICK_DELAY: u64 = 250;
const HOLD_DELAY: u64 = 1000; const HOLD_DELAY: u64 = 1000;