| 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: *const T = self.data.get() as *const T; |
| 49 | let inner: &T = 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: *const T = self.data.get() as *const T; |
| 101 | unsafe { &*ptr } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | impl<T> Mutex<raw::NoopRawMutex, T> { |
| 106 | /// Borrows the data |
| 107 | #[allow (clippy::should_implement_trait)] |
| 108 | pub fn borrow(&self) -> &T { |
| 109 | let ptr: *const T = self.data.get() as *const T; |
| 110 | unsafe { &*ptr } |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | // ThreadModeMutex does NOT use the generic mutex from above because it's special: |
| 115 | // it's Send+Sync even if T: !Send. There's no way to do that without specialization (I think?). |
| 116 | // |
| 117 | // There's still a ThreadModeRawMutex for use with the generic Mutex (handy with Channel, for example), |
| 118 | // but that will require T: Send even though it shouldn't be needed. |
| 119 | |
| 120 | #[cfg (any(cortex_m, feature = "std" ))] |
| 121 | pub use thread_mode_mutex::*; |
| 122 | #[cfg (any(cortex_m, feature = "std" ))] |
| 123 | mod thread_mode_mutex { |
| 124 | use super::*; |
| 125 | |
| 126 | /// A "mutex" that only allows borrowing from thread mode. |
| 127 | /// |
| 128 | /// # Safety |
| 129 | /// |
| 130 | /// **This Mutex is only safe on single-core systems.** |
| 131 | /// |
| 132 | /// On multi-core systems, a `ThreadModeMutex` **is not sufficient** to ensure exclusive access. |
| 133 | pub struct ThreadModeMutex<T: ?Sized> { |
| 134 | inner: UnsafeCell<T>, |
| 135 | } |
| 136 | |
| 137 | // NOTE: ThreadModeMutex only allows borrowing from one execution context ever: thread mode. |
| 138 | // Therefore it cannot be used to send non-sendable stuff between execution contexts, so it can |
| 139 | // be Send+Sync even if T is not Send (unlike CriticalSectionMutex) |
| 140 | unsafe impl<T: ?Sized> Sync for ThreadModeMutex<T> {} |
| 141 | unsafe impl<T: ?Sized> Send for ThreadModeMutex<T> {} |
| 142 | |
| 143 | impl<T> ThreadModeMutex<T> { |
| 144 | /// Creates a new mutex |
| 145 | pub const fn new(value: T) -> Self { |
| 146 | ThreadModeMutex { |
| 147 | inner: UnsafeCell::new(value), |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | impl<T: ?Sized> ThreadModeMutex<T> { |
| 153 | /// Lock the `ThreadModeMutex`, granting access to the data. |
| 154 | /// |
| 155 | /// # Panics |
| 156 | /// |
| 157 | /// This will panic if not currently running in thread mode. |
| 158 | pub fn lock<R>(&self, f: impl FnOnce(&T) -> R) -> R { |
| 159 | f(self.borrow()) |
| 160 | } |
| 161 | |
| 162 | /// Borrows the data |
| 163 | /// |
| 164 | /// # Panics |
| 165 | /// |
| 166 | /// This will panic if not currently running in thread mode. |
| 167 | pub fn borrow(&self) -> &T { |
| 168 | assert!( |
| 169 | raw::in_thread_mode(), |
| 170 | "ThreadModeMutex can only be borrowed from thread mode." |
| 171 | ); |
| 172 | unsafe { &*self.inner.get() } |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | impl<T: ?Sized> Drop for ThreadModeMutex<T> { |
| 177 | fn drop(&mut self) { |
| 178 | // Only allow dropping from thread mode. Dropping calls drop on the inner `T`, so |
| 179 | // `drop` needs the same guarantees as `lock`. `ThreadModeMutex<T>` is Send even if |
| 180 | // T isn't, so without this check a user could create a ThreadModeMutex in thread mode, |
| 181 | // send it to interrupt context and drop it there, which would "send" a T even if T is not Send. |
| 182 | assert!( |
| 183 | raw::in_thread_mode(), |
| 184 | "ThreadModeMutex can only be dropped from thread mode." |
| 185 | ); |
| 186 | |
| 187 | // Drop of the inner `T` happens after this. |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | |