Remove the LockMode enum and dispatch

This commit is contained in:
John Kåre Alsaker 2023-09-08 09:27:25 +02:00
parent 61cc00d238
commit 9690142bef
3 changed files with 81 additions and 109 deletions

View File

@ -1,7 +1,7 @@
use crate::fx::{FxHashMap, FxHasher}; use crate::fx::{FxHashMap, FxHasher};
#[cfg(parallel_compiler)] #[cfg(parallel_compiler)]
use crate::sync::{is_dyn_thread_safe, CacheAligned}; use crate::sync::{is_dyn_thread_safe, CacheAligned};
use crate::sync::{Assume, Lock, LockGuard}; use crate::sync::{Lock, LockGuard, Mode};
#[cfg(parallel_compiler)] #[cfg(parallel_compiler)]
use itertools::Either; use itertools::Either;
use std::borrow::Borrow; use std::borrow::Borrow;
@ -84,7 +84,7 @@ pub fn lock_shard_by_value<K: Hash + ?Sized>(&self, _val: &K) -> LockGuard<'_, T
// SAFETY: We know `is_dyn_thread_safe` was false when creating the lock thus // SAFETY: We know `is_dyn_thread_safe` was false when creating the lock thus
// `might_be_dyn_thread_safe` was also false. // `might_be_dyn_thread_safe` was also false.
unsafe { single.lock_assume(Assume::NoSync) } unsafe { single.lock_assume(Mode::NoSync) }
} }
#[cfg(parallel_compiler)] #[cfg(parallel_compiler)]
Self::Shards(..) => self.lock_shard_by_hash(make_hash(_val)), Self::Shards(..) => self.lock_shard_by_hash(make_hash(_val)),
@ -107,7 +107,7 @@ pub fn lock_shard_by_index(&self, _i: usize) -> LockGuard<'_, T> {
// SAFETY: We know `is_dyn_thread_safe` was false when creating the lock thus // SAFETY: We know `is_dyn_thread_safe` was false when creating the lock thus
// `might_be_dyn_thread_safe` was also false. // `might_be_dyn_thread_safe` was also false.
unsafe { single.lock_assume(Assume::NoSync) } unsafe { single.lock_assume(Mode::NoSync) }
} }
#[cfg(parallel_compiler)] #[cfg(parallel_compiler)]
Self::Shards(shards) => { Self::Shards(shards) => {
@ -118,7 +118,7 @@ pub fn lock_shard_by_index(&self, _i: usize) -> LockGuard<'_, T> {
// always inbounds. // always inbounds.
// SAFETY (lock_assume_sync): We know `is_dyn_thread_safe` was true when creating // SAFETY (lock_assume_sync): We know `is_dyn_thread_safe` was true when creating
// the lock thus `might_be_dyn_thread_safe` was also true. // the lock thus `might_be_dyn_thread_safe` was also true.
unsafe { shards.get_unchecked(_i & (SHARDS - 1)).0.lock_assume(Assume::Sync) } unsafe { shards.get_unchecked(_i & (SHARDS - 1)).0.lock_assume(Mode::Sync) }
} }
} }
} }

View File

@ -49,7 +49,7 @@
use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe}; use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
mod lock; mod lock;
pub use lock::{Assume, Lock, LockGuard}; pub use lock::{Lock, LockGuard, Mode};
mod worker_local; mod worker_local;
pub use worker_local::{Registry, WorkerLocal}; pub use worker_local::{Registry, WorkerLocal};

View File

@ -7,19 +7,19 @@
use std::fmt; use std::fmt;
#[cfg(not(parallel_compiler))]
pub use disabled::*;
#[cfg(parallel_compiler)] #[cfg(parallel_compiler)]
pub use enabled::*; pub use maybe_sync::*;
#[cfg(not(parallel_compiler))]
pub use no_sync::*;
#[derive(Clone, Copy, PartialEq)] #[derive(Clone, Copy, PartialEq)]
pub enum Assume { pub enum Mode {
NoSync, NoSync,
Sync, Sync,
} }
mod enabled { mod maybe_sync {
use super::Assume; use super::Mode;
use crate::sync::mode; use crate::sync::mode;
#[cfg(parallel_compiler)] #[cfg(parallel_compiler)]
use crate::sync::{DynSend, DynSync}; use crate::sync::{DynSend, DynSync};
@ -27,9 +27,9 @@ mod enabled {
use parking_lot::RawMutex; use parking_lot::RawMutex;
use std::cell::Cell; use std::cell::Cell;
use std::cell::UnsafeCell; use std::cell::UnsafeCell;
use std::hint::unreachable_unchecked;
use std::intrinsics::unlikely; use std::intrinsics::unlikely;
use std::marker::PhantomData; use std::marker::PhantomData;
use std::mem::ManuallyDrop;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
/// A guard holding mutable access to a `Lock` which is in a locked state. /// A guard holding mutable access to a `Lock` which is in a locked state.
@ -40,7 +40,7 @@ pub struct LockGuard<'a, T> {
/// The syncronization mode of the lock. This is explicitly passed to let LLVM relate it /// The syncronization mode of the lock. This is explicitly passed to let LLVM relate it
/// to the original lock operation. /// to the original lock operation.
assume: Assume, mode: Mode,
} }
impl<'a, T: 'a> Deref for LockGuard<'a, T> { impl<'a, T: 'a> Deref for LockGuard<'a, T> {
@ -64,61 +64,54 @@ fn deref_mut(&mut self) -> &mut T {
impl<'a, T: 'a> Drop for LockGuard<'a, T> { impl<'a, T: 'a> Drop for LockGuard<'a, T> {
#[inline] #[inline]
fn drop(&mut self) { fn drop(&mut self) {
// SAFETY (dispatch): We get `self.assume` from the lock operation so it is consistent // SAFETY (union access): We get `self.mode` from the lock operation so it is consistent
// with the lock state. // with the `lock.mode` state. This means we access the right union fields.
// SAFETY (unlock): We know that the lock is locked as this type is a proof of that. match self.mode {
unsafe { Mode::NoSync => {
self.lock.dispatch( let cell = unsafe { &self.lock.mode_union.no_sync };
self.assume, debug_assert_eq!(cell.get(), true);
|cell| { cell.set(false);
debug_assert_eq!(cell.get(), true); }
cell.set(false); // SAFETY (unlock): We know that the lock is locked as this type is a proof of that.
Some(()) Mode::Sync => unsafe { self.lock.mode_union.sync.unlock() },
},
|lock| lock.unlock(),
);
};
}
}
enum LockMode {
NoSync(Cell<bool>),
Sync(RawMutex),
}
impl LockMode {
#[inline(always)]
fn to_assume(&self) -> Assume {
match self {
LockMode::NoSync(..) => Assume::NoSync,
LockMode::Sync(..) => Assume::Sync,
} }
} }
} }
union ModeUnion {
/// Indicates if the cell is locked. Only used if `Lock.mode` is `NoSync`.
no_sync: ManuallyDrop<Cell<bool>>,
/// A lock implementation that's only used if `Lock.mode` is `Sync`.
sync: ManuallyDrop<RawMutex>,
}
/// The value representing a locked state for the `Cell`. /// The value representing a locked state for the `Cell`.
const LOCKED: bool = true; const LOCKED: bool = true;
/// A lock which only uses synchronization if `might_be_dyn_thread_safe` is true. /// A lock which only uses synchronization if `might_be_dyn_thread_safe` is true.
/// It implements `DynSend` and `DynSync` instead of the typical `Send` and `Sync`. /// It implements `DynSend` and `DynSync` instead of the typical `Send` and `Sync`.
pub struct Lock<T> { pub struct Lock<T> {
mode: LockMode, /// Indicates if synchronization is used via `mode_union.sync` if it's `Sync`, or if a
/// not thread safe cell is used via `mode_union.no_sync` if it's `NoSync`.
/// This is set on initialization and never changed.
mode: Mode,
mode_union: ModeUnion,
data: UnsafeCell<T>, data: UnsafeCell<T>,
} }
impl<T> Lock<T> { impl<T> Lock<T> {
#[inline(always)] #[inline(always)]
pub fn new(inner: T) -> Self { pub fn new(inner: T) -> Self {
Lock { let (mode, mode_union) = if unlikely(mode::might_be_dyn_thread_safe()) {
mode: if unlikely(mode::might_be_dyn_thread_safe()) { // Create the lock with synchronization enabled using the `RawMutex` type.
// Create the lock with synchronization enabled using the `RawMutex` type. (Mode::Sync, ModeUnion { sync: ManuallyDrop::new(RawMutex::INIT) })
LockMode::Sync(RawMutex::INIT) } else {
} else { // Create the lock with synchronization disabled.
// Create the lock with synchronization disabled. (Mode::NoSync, ModeUnion { no_sync: ManuallyDrop::new(Cell::new(!LOCKED)) })
LockMode::NoSync(Cell::new(!LOCKED)) };
}, Lock { mode, mode_union, data: UnsafeCell::new(inner) }
data: UnsafeCell::new(inner),
}
} }
#[inline(always)] #[inline(always)]
@ -131,20 +124,32 @@ pub fn get_mut(&mut self) -> &mut T {
self.data.get_mut() self.data.get_mut()
} }
/// This dispatches on the `LockMode` and gives access to its variants depending on #[inline(always)]
/// `assume`. If `no_sync` returns `None` this will panic. pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
let mode = self.mode;
// SAFETY: This is safe since the union fields are used in accordance with `self.mode`.
match mode {
Mode::NoSync => {
let cell = unsafe { &self.mode_union.no_sync };
let was_unlocked = cell.get() != LOCKED;
if was_unlocked {
cell.set(LOCKED);
}
was_unlocked
}
Mode::Sync => unsafe { self.mode_union.sync.try_lock() },
}
.then(|| LockGuard { lock: self, marker: PhantomData, mode })
}
/// This acquires the lock assuming syncronization is in a specific mode.
/// ///
/// Safety /// Safety
/// This method must only be called if `might_be_dyn_thread_safe` on lock creation matches /// This method must only be called with `Mode::Sync` if `might_be_dyn_thread_safe` was
/// matches the `assume` argument. /// true on lock creation.
#[inline(always)] #[inline(always)]
#[track_caller] #[track_caller]
unsafe fn dispatch<R>( pub unsafe fn lock_assume(&self, mode: Mode) -> LockGuard<'_, T> {
&self,
assume: Assume,
no_sync: impl FnOnce(&Cell<bool>) -> Option<R>,
sync: impl FnOnce(&RawMutex) -> R,
) -> R {
#[inline(never)] #[inline(never)]
#[track_caller] #[track_caller]
#[cold] #[cold]
@ -152,58 +157,25 @@ fn lock_held() -> ! {
panic!("lock was already held") panic!("lock was already held")
} }
match assume { // SAFETY: This is safe since the union fields are used in accordance with `mode`
Assume::NoSync => { // which also must match `self.mode` due to the safety precondition.
let LockMode::NoSync(cell) = &self.mode else { unsafe {
unsafe { unreachable_unchecked() } match mode {
}; Mode::NoSync => {
if let Some(v) = no_sync(cell) { if unlikely(self.mode_union.no_sync.replace(LOCKED) == LOCKED) {
v lock_held()
} else { }
// Call this here instead of in `no_sync` so `track_caller` gets properly
// passed along.
lock_held()
} }
} Mode::Sync => self.mode_union.sync.lock(),
Assume::Sync => {
let LockMode::Sync(lock) = &self.mode else {
unsafe { unreachable_unchecked() }
};
sync(lock)
} }
} }
} LockGuard { lock: self, marker: PhantomData, mode }
#[inline(always)]
pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
let assume = self.mode.to_assume();
unsafe {
self.dispatch(
assume,
|cell| Some((cell.get() != LOCKED).then(|| cell.set(LOCKED)).is_some()),
RawMutex::try_lock,
)
.then(|| LockGuard { lock: self, marker: PhantomData, assume })
}
}
#[inline(always)]
#[track_caller]
pub unsafe fn lock_assume(&self, assume: Assume) -> LockGuard<'_, T> {
unsafe {
self.dispatch(
assume,
|cell| (cell.replace(LOCKED) != LOCKED).then(|| ()),
RawMutex::lock,
);
LockGuard { lock: self, marker: PhantomData, assume }
}
} }
#[inline(always)] #[inline(always)]
#[track_caller] #[track_caller]
pub fn lock(&self) -> LockGuard<'_, T> { pub fn lock(&self) -> LockGuard<'_, T> {
unsafe { self.lock_assume(self.mode.to_assume()) } unsafe { self.lock_assume(self.mode) }
} }
} }
@ -213,8 +185,8 @@ unsafe impl<T: DynSend> DynSend for Lock<T> {}
unsafe impl<T: DynSend> DynSync for Lock<T> {} unsafe impl<T: DynSend> DynSync for Lock<T> {}
} }
mod disabled { mod no_sync {
use super::Assume; use super::Mode;
use std::cell::RefCell; use std::cell::RefCell;
pub use std::cell::RefMut as LockGuard; pub use std::cell::RefMut as LockGuard;
@ -245,7 +217,7 @@ pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
#[inline(always)] #[inline(always)]
#[track_caller] #[track_caller]
// This is unsafe to match the API for the `parallel_compiler` case. // This is unsafe to match the API for the `parallel_compiler` case.
pub unsafe fn lock_assume(&self, _assume: Assume) -> LockGuard<'_, T> { pub unsafe fn lock_assume(&self, _mode: Mode) -> LockGuard<'_, T> {
self.0.borrow_mut() self.0.borrow_mut()
} }