From 412586c2f63e320099443e97de21ada2d3722f0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Flemstr=C3=B6m?= Date: Mon, 13 Jan 2025 11:26:00 +0100 Subject: [PATCH] lock_api: Add MappedArcMutexGuard to mirror MappedMutexGuard --- lock_api/src/mutex.rs | 146 ++++++++++++++++++++++++++++++++++++++++++ src/mutex.rs | 9 +++ 2 files changed, 155 insertions(+) diff --git a/lock_api/src/mutex.rs b/lock_api/src/mutex.rs index 09177024..1fdc8518 100644 --- a/lock_api/src/mutex.rs +++ b/lock_api/src/mutex.rs @@ -962,3 +962,149 @@ impl<'a, R: RawMutex + 'a, T: fmt::Display + ?Sized + 'a> fmt::Display #[cfg(feature = "owning_ref")] unsafe impl<'a, R: RawMutex + 'a, T: ?Sized + 'a> StableAddress for MappedMutexGuard<'a, R, T> {} + +/// An RAII mutex guard returned by `ArcMutexGuard::map`, which can point to a +/// subfield of the protected data. +/// +/// The main difference between `MappedArcMutexGuard` and `ArcMutexGuard` is that the +/// former doesn't support temporarily unlocking and re-locking, since that +/// could introduce soundness issues if the locked object is modified by another +/// thread. +#[cfg(feature = "arc_lock")] +#[clippy::has_significant_drop] +#[must_use = "if unused the Mutex will immediately unlock"] +pub struct MappedArcMutexGuard { + raw: Arc, + data: *mut T, + marker: PhantomData, +} + +#[cfg(feature = "arc_lock")] +unsafe impl Sync for MappedArcMutexGuard {} +#[cfg(feature = "arc_lock")] +unsafe impl Send for MappedArcMutexGuard where + R::GuardMarker: Send +{ +} + +#[cfg(feature = "arc_lock")] +impl MappedArcMutexGuard { + /// Makes a new `MappedArcMutexGuard` for a component of the locked data. + /// + /// This operation cannot fail as the `MappedArcMutexGuard` passed + /// in already locked the mutex. + /// + /// This is an associated function that needs to be + /// used as `MappedArcMutexGuard::map(...)`. A method would interfere with methods of + /// the same name on the contents of the locked data. + #[inline] + pub fn map(s: Self, f: F) -> MappedArcMutexGuard + where + F: FnOnce(&mut T) -> &mut U, + { + let raw = Arc::clone(&s.raw); + let data = f(unsafe { &mut *s.data }); + mem::forget(s); + MappedArcMutexGuard { + raw, + data, + marker: PhantomData, + } + } + + /// Attempts to make a new `MappedArcMutexGuard` for a component of the + /// locked data. The original guard is returned if the closure returns `None`. + /// + /// This operation cannot fail as the `MappedArcMutexGuard` passed + /// in already locked the mutex. + /// + /// This is an associated function that needs to be + /// used as `MappedArcMutexGuard::try_map(...)`. A method would interfere with methods of + /// the same name on the contents of the locked data. + #[inline] + pub fn try_map(s: Self, f: F) -> Result, Self> + where + F: FnOnce(&mut T) -> Option<&mut U>, + { + let raw = Arc::clone(&s.raw); + let data = match f(unsafe { &mut *s.data }) { + Some(data) => data, + None => return Err(s), + }; + mem::forget(s); + Ok(MappedArcMutexGuard { + raw, + data, + marker: PhantomData, + }) + } +} + +#[cfg(feature = "arc_lock")] +impl MappedArcMutexGuard { + /// Unlocks the mutex using a fair unlock protocol. + /// + /// By default, mutexes are unfair and allow the current thread to re-lock + /// the mutex before another has the chance to acquire the lock, even if + /// that thread has been blocked on the mutex for a long time. This is the + /// default because it allows much higher throughput as it avoids forcing a + /// context switch on every mutex unlock. This can result in one thread + /// acquiring a mutex many more times than other threads. + /// + /// However, in some cases it can be beneficial to ensure fairness by forcing + /// the lock to pass on to a waiting thread if there is one. This is done by + /// using this method instead of dropping the `MutexGuard` normally. + #[inline] + pub fn unlock_fair(s: Self) { + // Safety: A MutexGuard always holds the lock. + unsafe { + s.raw.unlock_fair(); + } + mem::forget(s); + } +} + +#[cfg(feature = "arc_lock")] +impl Deref for MappedArcMutexGuard { + type Target = T; + #[inline] + fn deref(&self) -> &T { + unsafe { &*self.data } + } +} + +#[cfg(feature = "arc_lock")] +impl DerefMut for MappedArcMutexGuard { + #[inline] + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut *self.data } + } +} + +#[cfg(feature = "arc_lock")] +impl Drop for MappedArcMutexGuard { + #[inline] + fn drop(&mut self) { + // Safety: A MappedArcMutexGuard always holds the lock. + unsafe { + self.raw.unlock(); + } + } +} + +#[cfg(feature = "arc_lock")] +impl fmt::Debug for MappedArcMutexGuard { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[cfg(feature = "arc_lock")] +impl fmt::Display for MappedArcMutexGuard { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + (**self).fmt(f) + } +} + +#[cfg(all(feature = "arc_lock", feature = "owning_ref"))] +unsafe impl StableAddress for MappedArcMutexGuard {} diff --git a/src/mutex.rs b/src/mutex.rs index ac953127..4127222a 100644 --- a/src/mutex.rs +++ b/src/mutex.rs @@ -108,6 +108,15 @@ pub type MutexGuard<'a, T> = lock_api::MutexGuard<'a, RawMutex, T>; /// thread. pub type MappedMutexGuard<'a, T> = lock_api::MappedMutexGuard<'a, RawMutex, T>; +/// An RAII mutex guard returned by `ArcMutexGuard::map`, which can point to a +/// subfield of the protected data. +/// +/// The main difference between `MappedArcMutexGuard` and `ArcMutexGuard` is that the +/// former doesn't support temporarily unlocking and re-locking, since that +/// could introduce soundness issues if the locked object is modified by another +/// thread. +pub type MappedArcMutexGuard = lock_api::MappedArcMutexGuard; + #[cfg(test)] mod tests { use crate::{Condvar, Mutex};