diff options
Diffstat (limited to 'embassy-sync/src/blocking_mutex/mod.rs')
| -rw-r--r-- | embassy-sync/src/blocking_mutex/mod.rs | 189 |
1 files changed, 189 insertions, 0 deletions
diff --git a/embassy-sync/src/blocking_mutex/mod.rs b/embassy-sync/src/blocking_mutex/mod.rs new file mode 100644 index 000000000..8a4a4c642 --- /dev/null +++ b/embassy-sync/src/blocking_mutex/mod.rs | |||
| @@ -0,0 +1,189 @@ | |||
| 1 | //! Blocking mutex. | ||
| 2 | //! | ||
| 3 | //! This module provides a blocking mutex that can be used to synchronize data. | ||
| 4 | pub mod raw; | ||
| 5 | |||
| 6 | use core::cell::UnsafeCell; | ||
| 7 | |||
| 8 | use self::raw::RawMutex; | ||
| 9 | |||
| 10 | /// Blocking mutex (not async) | ||
| 11 | /// | ||
| 12 | /// Provides a blocking mutual exclusion primitive backed by an implementation of [`raw::RawMutex`]. | ||
| 13 | /// | ||
| 14 | /// Which implementation you select depends on the context in which you're using the mutex, and you can choose which kind | ||
| 15 | /// of interior mutability fits your use case. | ||
| 16 | /// | ||
| 17 | /// Use [`CriticalSectionMutex`] when data can be shared between threads and interrupts. | ||
| 18 | /// | ||
| 19 | /// Use [`NoopMutex`] when data is only shared between tasks running on the same executor. | ||
| 20 | /// | ||
| 21 | /// Use [`ThreadModeMutex`] when data is shared between tasks running on the same executor but you want a global singleton. | ||
| 22 | /// | ||
| 23 | /// In all cases, the blocking mutex is intended to be short lived and not held across await points. | ||
| 24 | /// Use the async [`Mutex`](crate::mutex::Mutex) if you need a lock that is held across await points. | ||
| 25 | pub struct Mutex<R, T: ?Sized> { | ||
| 26 | // NOTE: `raw` must be FIRST, so when using ThreadModeMutex the "can't drop in non-thread-mode" gets | ||
| 27 | // to run BEFORE dropping `data`. | ||
| 28 | raw: R, | ||
| 29 | data: UnsafeCell<T>, | ||
| 30 | } | ||
| 31 | |||
| 32 | unsafe impl<R: RawMutex + Send, T: ?Sized + Send> Send for Mutex<R, T> {} | ||
| 33 | unsafe impl<R: RawMutex + Sync, T: ?Sized + Send> Sync for Mutex<R, T> {} | ||
| 34 | |||
| 35 | impl<R: RawMutex, T> Mutex<R, T> { | ||
| 36 | /// Creates a new mutex in an unlocked state ready for use. | ||
| 37 | #[inline] | ||
| 38 | pub const fn new(val: T) -> Mutex<R, T> { | ||
| 39 | Mutex { | ||
| 40 | raw: R::INIT, | ||
| 41 | data: UnsafeCell::new(val), | ||
| 42 | } | ||
| 43 | } | ||
| 44 | |||
| 45 | /// Creates a critical section and grants temporary access to the protected data. | ||
| 46 | pub fn lock<U>(&self, f: impl FnOnce(&T) -> U) -> U { | ||
| 47 | self.raw.lock(|| { | ||
| 48 | let ptr = self.data.get() as *const T; | ||
| 49 | let inner = unsafe { &*ptr }; | ||
| 50 | f(inner) | ||
| 51 | }) | ||
| 52 | } | ||
| 53 | } | ||
| 54 | |||
| 55 | impl<R, T> Mutex<R, T> { | ||
| 56 | /// Creates a new mutex based on a pre-existing raw mutex. | ||
| 57 | /// | ||
| 58 | /// This allows creating a mutex in a constant context on stable Rust. | ||
| 59 | #[inline] | ||
| 60 | pub const fn const_new(raw_mutex: R, val: T) -> Mutex<R, T> { | ||
| 61 | Mutex { | ||
| 62 | raw: raw_mutex, | ||
| 63 | data: UnsafeCell::new(val), | ||
| 64 | } | ||
| 65 | } | ||
| 66 | |||
| 67 | /// Consumes this mutex, returning the underlying data. | ||
| 68 | #[inline] | ||
| 69 | pub fn into_inner(self) -> T { | ||
| 70 | self.data.into_inner() | ||
| 71 | } | ||
| 72 | |||
| 73 | /// Returns a mutable reference to the underlying data. | ||
| 74 | /// | ||
| 75 | /// Since this call borrows the `Mutex` mutably, no actual locking needs to | ||
| 76 | /// take place---the mutable borrow statically guarantees no locks exist. | ||
| 77 | #[inline] | ||
| 78 | pub fn get_mut(&mut self) -> &mut T { | ||
| 79 | unsafe { &mut *self.data.get() } | ||
| 80 | } | ||
| 81 | } | ||
| 82 | |||
| 83 | /// A mutex that allows borrowing data across executors and interrupts. | ||
| 84 | /// | ||
| 85 | /// # Safety | ||
| 86 | /// | ||
| 87 | /// This mutex is safe to share between different executors and interrupts. | ||
| 88 | pub type CriticalSectionMutex<T> = Mutex<raw::CriticalSectionRawMutex, T>; | ||
| 89 | |||
| 90 | /// A mutex that allows borrowing data in the context of a single executor. | ||
| 91 | /// | ||
| 92 | /// # Safety | ||
| 93 | /// | ||
| 94 | /// **This Mutex is only safe within a single executor.** | ||
| 95 | pub type NoopMutex<T> = Mutex<raw::NoopRawMutex, T>; | ||
| 96 | |||
| 97 | impl<T> Mutex<raw::CriticalSectionRawMutex, T> { | ||
| 98 | /// Borrows the data for the duration of the critical section | ||
| 99 | pub fn borrow<'cs>(&'cs self, _cs: critical_section::CriticalSection<'cs>) -> &'cs T { | ||
| 100 | let ptr = self.data.get() as *const T; | ||
| 101 | unsafe { &*ptr } | ||
| 102 | } | ||
| 103 | } | ||
| 104 | |||
| 105 | impl<T> Mutex<raw::NoopRawMutex, T> { | ||
| 106 | /// Borrows the data | ||
| 107 | pub fn borrow(&self) -> &T { | ||
| 108 | let ptr = self.data.get() as *const T; | ||
| 109 | unsafe { &*ptr } | ||
| 110 | } | ||
| 111 | } | ||
| 112 | |||
| 113 | // ThreadModeMutex does NOT use the generic mutex from above because it's special: | ||
| 114 | // it's Send+Sync even if T: !Send. There's no way to do that without specialization (I think?). | ||
| 115 | // | ||
| 116 | // There's still a ThreadModeRawMutex for use with the generic Mutex (handy with Channel, for example), | ||
| 117 | // but that will require T: Send even though it shouldn't be needed. | ||
| 118 | |||
| 119 | #[cfg(any(cortex_m, feature = "std"))] | ||
| 120 | pub use thread_mode_mutex::*; | ||
| 121 | #[cfg(any(cortex_m, feature = "std"))] | ||
| 122 | mod thread_mode_mutex { | ||
| 123 | use super::*; | ||
| 124 | |||
| 125 | /// A "mutex" that only allows borrowing from thread mode. | ||
| 126 | /// | ||
| 127 | /// # Safety | ||
| 128 | /// | ||
| 129 | /// **This Mutex is only safe on single-core systems.** | ||
| 130 | /// | ||
| 131 | /// On multi-core systems, a `ThreadModeMutex` **is not sufficient** to ensure exclusive access. | ||
| 132 | pub struct ThreadModeMutex<T: ?Sized> { | ||
| 133 | inner: UnsafeCell<T>, | ||
| 134 | } | ||
| 135 | |||
| 136 | // NOTE: ThreadModeMutex only allows borrowing from one execution context ever: thread mode. | ||
| 137 | // Therefore it cannot be used to send non-sendable stuff between execution contexts, so it can | ||
| 138 | // be Send+Sync even if T is not Send (unlike CriticalSectionMutex) | ||
| 139 | unsafe impl<T: ?Sized> Sync for ThreadModeMutex<T> {} | ||
| 140 | unsafe impl<T: ?Sized> Send for ThreadModeMutex<T> {} | ||
| 141 | |||
| 142 | impl<T> ThreadModeMutex<T> { | ||
| 143 | /// Creates a new mutex | ||
| 144 | pub const fn new(value: T) -> Self { | ||
| 145 | ThreadModeMutex { | ||
| 146 | inner: UnsafeCell::new(value), | ||
| 147 | } | ||
| 148 | } | ||
| 149 | } | ||
| 150 | |||
| 151 | impl<T: ?Sized> ThreadModeMutex<T> { | ||
| 152 | /// Lock the `ThreadModeMutex`, granting access to the data. | ||
| 153 | /// | ||
| 154 | /// # Panics | ||
| 155 | /// | ||
| 156 | /// This will panic if not currently running in thread mode. | ||
| 157 | pub fn lock<R>(&self, f: impl FnOnce(&T) -> R) -> R { | ||
| 158 | f(self.borrow()) | ||
| 159 | } | ||
| 160 | |||
| 161 | /// Borrows the data | ||
| 162 | /// | ||
| 163 | /// # Panics | ||
| 164 | /// | ||
| 165 | /// This will panic if not currently running in thread mode. | ||
| 166 | pub fn borrow(&self) -> &T { | ||
| 167 | assert!( | ||
| 168 | raw::in_thread_mode(), | ||
| 169 | "ThreadModeMutex can only be borrowed from thread mode." | ||
| 170 | ); | ||
| 171 | unsafe { &*self.inner.get() } | ||
| 172 | } | ||
| 173 | } | ||
| 174 | |||
| 175 | impl<T: ?Sized> Drop for ThreadModeMutex<T> { | ||
| 176 | fn drop(&mut self) { | ||
| 177 | // Only allow dropping from thread mode. Dropping calls drop on the inner `T`, so | ||
| 178 | // `drop` needs the same guarantees as `lock`. `ThreadModeMutex<T>` is Send even if | ||
| 179 | // T isn't, so without this check a user could create a ThreadModeMutex in thread mode, | ||
| 180 | // send it to interrupt context and drop it there, which would "send" a T even if T is not Send. | ||
| 181 | assert!( | ||
| 182 | raw::in_thread_mode(), | ||
| 183 | "ThreadModeMutex can only be dropped from thread mode." | ||
| 184 | ); | ||
| 185 | |||
| 186 | // Drop of the inner `T` happens after this. | ||
| 187 | } | ||
| 188 | } | ||
| 189 | } | ||
