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