diff options
| author | Ulf Lilleengen <[email protected]> | 2025-03-31 07:34:11 +0000 |
|---|---|---|
| committer | GitHub <[email protected]> | 2025-03-31 07:34:11 +0000 |
| commit | 154870b2c3475ecef9ef801035dce57ec3a6634a (patch) | |
| tree | 60d254c93d7303b9e5bbb4ee036e1bd0c0eaeccb /embassy-sync | |
| parent | aadd4e551327a0b3b08ab52b32f7b1017a093157 (diff) | |
| parent | 7a031eed66ef27e83b8582e7c1e7ca00d16ccf64 (diff) | |
Merge pull request #3978 from avsaase/blocking-mutex-lock-mut
embassy-sync: add `lock_mut` to `blocking_mutex::Mutex`
Diffstat (limited to 'embassy-sync')
| -rw-r--r-- | embassy-sync/src/blocking_mutex/mod.rs | 17 |
1 files changed, 17 insertions, 0 deletions
diff --git a/embassy-sync/src/blocking_mutex/mod.rs b/embassy-sync/src/blocking_mutex/mod.rs index beafdb43d..a41bc3569 100644 --- a/embassy-sync/src/blocking_mutex/mod.rs +++ b/embassy-sync/src/blocking_mutex/mod.rs | |||
| @@ -50,6 +50,23 @@ impl<R: RawMutex, T> Mutex<R, T> { | |||
| 50 | f(inner) | 50 | f(inner) |
| 51 | }) | 51 | }) |
| 52 | } | 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 | } | ||
| 53 | } | 70 | } |
| 54 | 71 | ||
| 55 | impl<R, T> Mutex<R, T> { | 72 | impl<R, T> Mutex<R, T> { |
