embassy_sync/blocking_mutex/
mod.rs

1//! Blocking mutex.
2//!
3//! This module provides a blocking mutex that can be used to synchronize data.
4pub mod raw;
5
6use core::cell::UnsafeCell;
7
8use 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.
25pub 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
32unsafe impl<R: RawMutex + Send, T: ?Sized + Send> Send for Mutex<R, T> {}
33unsafe impl<R: RawMutex + Sync, T: ?Sized + Send> Sync for Mutex<R, T> {}
34
35impl<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    /// Creates a critical section and grants temporary mutable access to the protected data.
55    ///
56    /// # Safety
57    ///
58    /// This method is marked unsafe because calling this method re-entrantly, i.e. within
59    /// another `lock_mut` or `lock` closure, violates Rust's aliasing rules. Calling this
60    /// method at the same time from different tasks is safe. For a safe alternative with
61    /// mutable access that never causes UB, use a `RefCell` in a `Mutex`.
62    pub unsafe fn lock_mut<U>(&self, f: impl FnOnce(&mut T) -> U) -> U {
63        self.raw.lock(|| {
64            let ptr = self.data.get() as *mut T;
65            // Safety: we have exclusive access to the data, as long as this mutex is not locked re-entrantly
66            let inner = unsafe { &mut *ptr };
67            f(inner)
68        })
69    }
70}
71
72impl<R, T> Mutex<R, T> {
73    /// Creates a new mutex based on a pre-existing raw mutex.
74    ///
75    /// This allows creating a mutex in a constant context on stable Rust.
76    #[inline]
77    pub const fn const_new(raw_mutex: R, val: T) -> Mutex<R, T> {
78        Mutex {
79            raw: raw_mutex,
80            data: UnsafeCell::new(val),
81        }
82    }
83
84    /// Consumes this mutex, returning the underlying data.
85    #[inline]
86    pub fn into_inner(self) -> T {
87        self.data.into_inner()
88    }
89
90    /// Returns a mutable reference to the underlying data.
91    ///
92    /// Since this call borrows the `Mutex` mutably, no actual locking needs to
93    /// take place---the mutable borrow statically guarantees no locks exist.
94    #[inline]
95    pub fn get_mut(&mut self) -> &mut T {
96        unsafe { &mut *self.data.get() }
97    }
98}
99
100/// A mutex that allows borrowing data across executors and interrupts.
101///
102/// # Safety
103///
104/// This mutex is safe to share between different executors and interrupts.
105pub type CriticalSectionMutex<T> = Mutex<raw::CriticalSectionRawMutex, T>;
106
107/// A mutex that allows borrowing data in the context of a single executor.
108///
109/// # Safety
110///
111/// **This Mutex is only safe within a single executor.**
112pub type NoopMutex<T> = Mutex<raw::NoopRawMutex, T>;
113
114impl<T> Mutex<raw::CriticalSectionRawMutex, T> {
115    /// Borrows the data for the duration of the critical section
116    pub fn borrow<'cs>(&'cs self, _cs: critical_section::CriticalSection<'cs>) -> &'cs T {
117        let ptr = self.data.get() as *const T;
118        unsafe { &*ptr }
119    }
120}
121
122impl<T> Mutex<raw::NoopRawMutex, T> {
123    /// Borrows the data
124    #[allow(clippy::should_implement_trait)]
125    pub fn borrow(&self) -> &T {
126        let ptr = self.data.get() as *const T;
127        unsafe { &*ptr }
128    }
129}
130
131// ThreadModeMutex does NOT use the generic mutex from above because it's special:
132// it's Send+Sync even if T: !Send. There's no way to do that without specialization (I think?).
133//
134// There's still a ThreadModeRawMutex for use with the generic Mutex (handy with Channel, for example),
135// but that will require T: Send even though it shouldn't be needed.
136
137#[cfg(any(cortex_m, feature = "std"))]
138pub use thread_mode_mutex::*;
139#[cfg(any(cortex_m, feature = "std"))]
140mod thread_mode_mutex {
141    use super::*;
142
143    /// A "mutex" that only allows borrowing from thread mode.
144    ///
145    /// # Safety
146    ///
147    /// **This Mutex is only safe on single-core systems.**
148    ///
149    /// On multi-core systems, a `ThreadModeMutex` **is not sufficient** to ensure exclusive access.
150    pub struct ThreadModeMutex<T: ?Sized> {
151        inner: UnsafeCell<T>,
152    }
153
154    // NOTE: ThreadModeMutex only allows borrowing from one execution context ever: thread mode.
155    // Therefore it cannot be used to send non-sendable stuff between execution contexts, so it can
156    // be Send+Sync even if T is not Send (unlike CriticalSectionMutex)
157    unsafe impl<T: ?Sized> Sync for ThreadModeMutex<T> {}
158    unsafe impl<T: ?Sized> Send for ThreadModeMutex<T> {}
159
160    impl<T> ThreadModeMutex<T> {
161        /// Creates a new mutex
162        pub const fn new(value: T) -> Self {
163            ThreadModeMutex {
164                inner: UnsafeCell::new(value),
165            }
166        }
167    }
168
169    impl<T: ?Sized> ThreadModeMutex<T> {
170        /// Lock the `ThreadModeMutex`, granting access to the data.
171        ///
172        /// # Panics
173        ///
174        /// This will panic if not currently running in thread mode.
175        pub fn lock<R>(&self, f: impl FnOnce(&T) -> R) -> R {
176            f(self.borrow())
177        }
178
179        /// Borrows the data
180        ///
181        /// # Panics
182        ///
183        /// This will panic if not currently running in thread mode.
184        pub fn borrow(&self) -> &T {
185            assert!(
186                raw::in_thread_mode(),
187                "ThreadModeMutex can only be borrowed from thread mode."
188            );
189            unsafe { &*self.inner.get() }
190        }
191    }
192
193    impl<T: ?Sized> Drop for ThreadModeMutex<T> {
194        fn drop(&mut self) {
195            // Only allow dropping from thread mode. Dropping calls drop on the inner `T`, so
196            // `drop` needs the same guarantees as `lock`. `ThreadModeMutex<T>` is Send even if
197            // T isn't, so without this check a user could create a ThreadModeMutex in thread mode,
198            // send it to interrupt context and drop it there, which would "send" a T even if T is not Send.
199            assert!(
200                raw::in_thread_mode(),
201                "ThreadModeMutex can only be dropped from thread mode."
202            );
203
204            // Drop of the inner `T` happens after this.
205        }
206    }
207}