Many possible implementations of Mutex, such as a ticket lock, require the guard type to hold state pertaining to the lock. Today, lock_api does not provide a way to store that state. A change to the API that solves this would look like:
pub unsafe trait RawMutex {
type Guard;
const INIT: Self;
// Required methods
fn lock(&self) -> Self::Guard;
fn try_lock(&self) -> Option<Self::Guard>;
// Takes `&mut Self::Guard` to comply with `Drop` requirements
unsafe fn unlock(&self, guard: &mut Self::Guard);
// Provided method
fn is_locked(&self) -> bool { ... }
}
This could even be implemented in a semver-compatible way with a separate trait and a blanket impl like so:
pub unsafe trait RawMutex2 {
type Guard;
const INIT: Self;
// Required methods
fn lock(&self) -> Self::Guard;
fn try_lock(&self) -> Option<Self::Guard>;
// Takes `&mut Self::Guard` to comply with `Drop` requirements
unsafe fn unlock(&self, guard: &mut Self::Guard);
// Provided method
fn is_locked(&self) -> bool { ... }
}
unsafe impl<M: RawMutex> RawMutex2 for M {
type Guard = PhantomData<M::GuardMarker>;
const INIT: Self = <M as RawMutex>::INIT;
fn lock(&self) -> Self::Guard { <Self as RawMutex>::lock(self); PhantomData }
fn try_lock(&self) -> Option<Self::Guard> { <Self as RawMutex>::try_lock(self).then_some(PhantomData) }
unsafe fn unlock(&self, _: &mut Self::Guard) { <Self as RawMutex>::unlock(self); }
fn is_locked(&self) -> bool { <Self as RawMutex>::is_locked(self) }
}
This also applies to the other raw traits in lock_api.
Edit: On reflection, a ticket lock is not the best example since it is possible to implement it without guard state. However, this is not true of its RwLock equivalent.
Many possible implementations of
Mutex, such as a ticket lock, require the guard type to hold state pertaining to the lock. Today,lock_apidoes not provide a way to store that state. A change to the API that solves this would look like:This could even be implemented in a semver-compatible way with a separate trait and a blanket impl like so:
This also applies to the other raw traits in
lock_api.Edit: On reflection, a ticket lock is not the best example since it is possible to implement it without guard state. However, this is not true of its
RwLockequivalent.