aboutsummaryrefslogtreecommitdiff
path: root/embassy-sync/src/blocking_rwlock
diff options
context:
space:
mode:
authorAlix ANNERAUD <[email protected]>2025-03-16 21:45:25 +0100
committerAlix ANNERAUD <[email protected]>2025-03-16 21:45:25 +0100
commite557ca96065592d5ab6c11c0498a4dee32672635 (patch)
treebb2a3949327eb3ff692ffbdf39fd0beddef41e3c /embassy-sync/src/blocking_rwlock
parent82c0ab01f19bebc82f2edbf60b8edac7b17050d6 (diff)
Remove blocking read-write lock module and its references and refactor rwlock for a simpler approach
Diffstat (limited to 'embassy-sync/src/blocking_rwlock')
-rw-r--r--embassy-sync/src/blocking_rwlock/mod.rs221
-rw-r--r--embassy-sync/src/blocking_rwlock/raw.rs209
2 files changed, 0 insertions, 430 deletions
diff --git a/embassy-sync/src/blocking_rwlock/mod.rs b/embassy-sync/src/blocking_rwlock/mod.rs
deleted file mode 100644
index 88cd2164b..000000000
--- a/embassy-sync/src/blocking_rwlock/mod.rs
+++ /dev/null
@@ -1,221 +0,0 @@
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;
5
6use core::cell::UnsafeCell;
7
8use self::raw::RawRwLock;
9
10/// Blocking read-write lock (not async)
11///
12/// Provides a blocking read-write lock primitive backed by an implementation of [`raw::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::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::NoopRawRwLock, T>;
105
106impl<T> RwLock<raw::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::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::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::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::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}
diff --git a/embassy-sync/src/blocking_rwlock/raw.rs b/embassy-sync/src/blocking_rwlock/raw.rs
deleted file mode 100644
index 2fb9ce9d1..000000000
--- a/embassy-sync/src/blocking_rwlock/raw.rs
+++ /dev/null
@@ -1,209 +0,0 @@
1//! Read-Write Lock primitives.
2//!
3//! This module provides a trait for read-write locks that can be used in different contexts.
4use core::cell::RefCell;
5use core::marker::PhantomData;
6
7/// Raw read-write lock trait.
8///
9/// This read-write lock is "raw", which means it does not actually contain the protected data, it
10/// just implements the read-write lock mechanism. For most uses you should use [`super::RwLock`] instead,
11/// which is generic over a RawRwLock and contains the protected data.
12///
13/// Note that, unlike other read-write locks, implementations only guarantee no
14/// concurrent access from other threads: concurrent access from the current
15/// thread is allowed. For example, it's possible to lock the same read-write lock multiple times reentrantly.
16///
17/// Therefore, locking a `RawRwLock` is only enough to guarantee safe shared (`&`) access
18/// to the data, it is not enough to guarantee exclusive (`&mut`) access.
19///
20/// # Safety
21///
22/// RawRwLock implementations must ensure that, while locked, no other thread can lock
23/// the RawRwLock concurrently.
24///
25/// Unsafe code is allowed to rely on this fact, so incorrect implementations will cause undefined behavior.
26pub unsafe trait RawRwLock {
27 /// Create a new `RawRwLock` instance.
28 ///
29 /// This is a const instead of a method to allow creating instances in const context.
30 const INIT: Self;
31
32 /// Lock this `RawRwLock` for reading.
33 fn read_lock<R>(&self, f: impl FnOnce() -> R) -> R;
34
35 /// Lock this `RawRwLock` for writing.
36 fn write_lock<R>(&self, f: impl FnOnce() -> R) -> R;
37}
38
39/// A read-write lock that allows borrowing data across executors and interrupts.
40///
41/// # Safety
42///
43/// This read-write lock is safe to share between different executors and interrupts.
44pub struct CriticalSectionRawRwLock {
45 state: RefCell<isize>,
46}
47
48unsafe impl Send for CriticalSectionRawRwLock {}
49unsafe impl Sync for CriticalSectionRawRwLock {}
50
51impl CriticalSectionRawRwLock {
52 /// Creates a new [`CriticalSectionRawRwLock`].
53 pub const fn new() -> Self {
54 Self { state: RefCell::new(0) }
55 }
56
57 fn lock_read(&self) {
58 critical_section::with(|_| {
59 let mut state = self.state.borrow_mut();
60
61 while *state & WRITER != 0 {
62 // Spin until the writer releases the lock
63 }
64 *state += 1;
65 });
66 }
67
68 fn unlock_read(&self) {
69 critical_section::with(|_| {
70 *self.state.borrow_mut() -= 1;
71 });
72 }
73
74 fn lock_write(&self) {
75 critical_section::with(|_| {
76 let mut state = self.state.borrow_mut();
77
78 while *state != 0 {
79 // Spin until all readers and writers release the lock
80 }
81 *state = WRITER;
82 });
83 }
84
85 fn unlock_write(&self) {
86 critical_section::with(|_| {
87 *self.state.borrow_mut() = 0;
88 });
89 }
90}
91
92unsafe impl RawRwLock for CriticalSectionRawRwLock {
93 const INIT: Self = Self::new();
94
95 fn read_lock<R>(&self, f: impl FnOnce() -> R) -> R {
96 self.lock_read();
97 let result = f();
98 self.unlock_read();
99 result
100 }
101
102 fn write_lock<R>(&self, f: impl FnOnce() -> R) -> R {
103 self.lock_write();
104 let result = f();
105 self.unlock_write();
106 result
107 }
108}
109
110const WRITER: isize = -1;
111
112// ================
113
114/// A read-write lock that allows borrowing data in the context of a single executor.
115///
116/// # Safety
117///
118/// **This Read-Write Lock is only safe within a single executor.**
119pub struct NoopRawRwLock {
120 _phantom: PhantomData<*mut ()>,
121}
122
123unsafe impl Send for NoopRawRwLock {}
124
125impl NoopRawRwLock {
126 /// Create a new `NoopRawRwLock`.
127 pub const fn new() -> Self {
128 Self { _phantom: PhantomData }
129 }
130}
131
132unsafe impl RawRwLock for NoopRawRwLock {
133 const INIT: Self = Self::new();
134 fn read_lock<R>(&self, f: impl FnOnce() -> R) -> R {
135 f()
136 }
137
138 fn write_lock<R>(&self, f: impl FnOnce() -> R) -> R {
139 f()
140 }
141}
142
143// ================
144
145#[cfg(any(cortex_m, feature = "std"))]
146mod thread_mode {
147 use super::*;
148
149 /// A "read-write lock" that only allows borrowing from thread mode.
150 ///
151 /// # Safety
152 ///
153 /// **This Read-Write Lock is only safe on single-core systems.**
154 ///
155 /// On multi-core systems, a `ThreadModeRawRwLock` **is not sufficient** to ensure exclusive access.
156 pub struct ThreadModeRawRwLock {
157 _phantom: PhantomData<()>,
158 }
159
160 unsafe impl Send for ThreadModeRawRwLock {}
161 unsafe impl Sync for ThreadModeRawRwLock {}
162
163 impl ThreadModeRawRwLock {
164 /// Create a new `ThreadModeRawRwLock`.
165 pub const fn new() -> Self {
166 Self { _phantom: PhantomData }
167 }
168 }
169
170 unsafe impl RawRwLock for ThreadModeRawRwLock {
171 const INIT: Self = Self::new();
172 fn read_lock<R>(&self, f: impl FnOnce() -> R) -> R {
173 assert!(
174 in_thread_mode(),
175 "ThreadModeRwLock can only be locked from thread mode."
176 );
177
178 f()
179 }
180
181 fn write_lock<R>(&self, f: impl FnOnce() -> R) -> R {
182 assert!(
183 in_thread_mode(),
184 "ThreadModeRwLock can only be locked from thread mode."
185 );
186
187 f()
188 }
189 }
190
191 impl Drop for ThreadModeRawRwLock {
192 fn drop(&mut self) {
193 assert!(
194 in_thread_mode(),
195 "ThreadModeRwLock can only be dropped from thread mode."
196 );
197 }
198 }
199
200 pub(crate) fn in_thread_mode() -> bool {
201 #[cfg(feature = "std")]
202 return Some("main") == std::thread::current().name();
203
204 #[cfg(not(feature = "std"))]
205 return unsafe { (0xE000ED04 as *const u32).read_volatile() } & 0x1FF == 0;
206 }
207}
208#[cfg(any(cortex_m, feature = "std"))]
209pub use thread_mode::*;