use core::hint;
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
use crate::sync::{AtomicBool, Ordering, UnsafeCell, yield_now};
#[cfg(not(loom))]
const SPINS: u32 = 40;
#[cfg(loom)]
const SPINS: u32 = 0;
pub struct Lock<T> {
held: AtomicBool,
#[cfg(debug_assertions)]
owner: core::sync::atomic::AtomicU64,
value: UnsafeCell<T>,
}
unsafe impl<T: Send> Sync for Lock<T> {}
unsafe impl<T: Send> Send for Lock<T> {}
impl<T> Lock<T> {
#[cfg(not(loom))]
pub const fn new(value: T) -> Self {
Self {
held: AtomicBool::new(false),
#[cfg(debug_assertions)]
owner: core::sync::atomic::AtomicU64::new(0),
value: UnsafeCell::new(value),
}
}
#[cfg(loom)]
pub fn new(value: T) -> Self {
Self {
held: AtomicBool::new(false),
#[cfg(debug_assertions)]
owner: core::sync::atomic::AtomicU64::new(0),
value: UnsafeCell::new(value),
}
}
#[inline]
pub fn lock(&self) -> Held<'_, T> {
if !self.take() {
self.wait();
}
self.claim();
Held {
lock: self,
stays: PhantomData,
}
}
#[inline]
pub fn try_lock(&self) -> Option<Held<'_, T>> {
if !self.take() {
return None;
}
self.claim();
Some(Held {
lock: self,
stays: PhantomData,
})
}
#[inline]
pub fn get_mut(&mut self) -> &mut T {
self.value.get_mut()
}
pub fn into_inner(self) -> T {
self.value.into_inner()
}
#[inline]
pub fn is_held(&self) -> bool {
self.held.load(Ordering::Relaxed)
}
#[inline]
fn take(&self) -> bool {
self.held
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_ok()
}
#[cold]
fn wait(&self) {
self.mine_already();
let mut spins = 0;
loop {
while self.held.load(Ordering::Relaxed) {
if spins < SPINS {
spins += 1;
hint::spin_loop();
} else {
yield_now();
}
}
if self.take() {
return;
}
}
}
#[inline]
fn claim(&self) {
#[cfg(debug_assertions)]
self.owner.store(me(), Ordering::Relaxed);
}
#[inline]
fn disclaim(&self) {
#[cfg(debug_assertions)]
self.owner.store(0, Ordering::Relaxed);
}
#[inline]
fn mine_already(&self) {
#[cfg(debug_assertions)]
assert!(
self.owner.load(Ordering::Relaxed) != me(),
"this thread already holds this lock, and waiting for itself will \
never end"
);
}
}
impl<T: Default> Default for Lock<T> {
fn default() -> Self {
Self::new(T::default())
}
}
pub struct Held<'a, T> {
lock: &'a Lock<T>,
stays: PhantomData<*const ()>,
}
unsafe impl<T: Sync> Sync for Held<'_, T> {}
impl<T> Deref for Held<'_, T> {
type Target = T;
#[inline]
fn deref(&self) -> &T {
self.lock.value.with(|p| unsafe { &*p })
}
}
impl<T> DerefMut for Held<'_, T> {
#[inline]
fn deref_mut(&mut self) -> &mut T {
self.lock.value.with(|p| unsafe { &mut *p })
}
}
impl<T> Drop for Held<'_, T> {
#[inline]
fn drop(&mut self) {
self.lock.disclaim();
self.lock.held.store(false, Ordering::Release);
}
}
#[cfg(debug_assertions)]
fn me() -> u64 {
use core::cell::Cell;
use core::sync::atomic::AtomicU64;
static NEXT: AtomicU64 = AtomicU64::new(1);
thread_local! {
static ME: Cell<u64> = const { Cell::new(0) };
}
ME.try_with(|slot| {
let mut id = slot.get();
if id == 0 {
id = NEXT.fetch_add(1, Ordering::Relaxed);
slot.set(id);
}
id
})
.unwrap_or(u64::MAX)
}
#[cfg(test)]
mod tests {
use super::*;
const HANDS: u64 = 4;
#[cfg(miri)]
const ROUNDS: u64 = 20;
#[cfg(not(miri))]
const ROUNDS: u64 = 250;
#[cfg(miri)]
const HOLDS: u64 = 3;
#[cfg(not(miri))]
const HOLDS: u64 = 20;
#[cfg(miri)]
const INSIDE: u64 = 50;
#[cfg(not(miri))]
const INSIDE: u64 = 2_000;
#[test]
fn what_goes_in_is_what_comes_out_the_next_time_it_is_taken() {
let lock = Lock::new(Vec::new());
lock.lock().push(1u8);
lock.lock().push(2);
assert_eq!(*lock.lock(), vec![1, 2]);
assert_eq!(lock.into_inner(), vec![1, 2]);
}
#[test]
fn a_held_lock_cannot_be_taken_and_a_dropped_one_can() {
let lock = Lock::new(0u32);
let held = lock.lock();
assert!(lock.is_held());
assert!(lock.try_lock().is_none());
drop(held);
assert!(!lock.is_held());
assert!(lock.try_lock().is_some());
}
#[test]
fn an_owner_with_an_exclusive_reference_pays_nothing() {
let mut lock = Lock::new(0u32);
*lock.get_mut() = 7;
assert_eq!(*lock.lock(), 7);
}
#[test]
fn every_increment_from_every_thread_lands() {
let lock = Lock::new(0u64);
std::thread::scope(|s| {
for _ in 0..HANDS {
s.spawn(|| {
for _ in 0..ROUNDS {
*lock.lock() += 1;
}
});
}
});
assert_eq!(lock.into_inner(), HANDS * ROUNDS);
}
#[test]
fn a_waiter_that_runs_out_of_spins_still_gets_the_lock() {
let lock = Lock::new(0u64);
std::thread::scope(|s| {
for _ in 0..HANDS {
s.spawn(|| {
for _ in 0..HOLDS {
let mut held = lock.lock();
for _ in 0..INSIDE {
*held += 1;
hint::spin_loop();
}
}
});
}
});
assert_eq!(lock.into_inner(), HANDS * HOLDS * INSIDE);
}
#[cfg(debug_assertions)]
#[test]
#[should_panic(expected = "already holds this lock")]
fn taking_it_twice_on_one_thread_says_so_instead_of_hanging() {
let lock = Lock::new(0u32);
let _first = lock.lock();
let _second = lock.lock();
}
#[cfg(debug_assertions)]
#[test]
fn trying_it_twice_on_one_thread_just_fails() {
let lock = Lock::new(0u32);
let _first = lock.lock();
assert!(lock.try_lock().is_none());
}
}
#[cfg(all(loom, test))]
mod loom_tests {
use super::*;
type Guarded = loom::cell::UnsafeCell<usize>;
fn bump(lock: &Lock<Guarded>) {
let held = lock.lock();
held.with_mut(|p| unsafe { *p += 1 });
}
fn read(lock: &Lock<Guarded>) -> usize {
let held = lock.lock();
held.with(|p| unsafe { *p })
}
#[test]
fn two_threads_cannot_both_be_inside() {
loom::model(|| {
let lock = loom::sync::Arc::new(Lock::new(Guarded::new(0)));
let other = lock.clone();
let hand = loom::thread::spawn(move || bump(&other));
bump(&lock);
hand.join().unwrap();
assert_eq!(read(&lock), 2, "an increment was lost");
});
}
#[test]
fn what_the_last_holder_wrote_is_what_the_next_one_sees() {
loom::model(|| {
let lock = loom::sync::Arc::new(Lock::new(Guarded::new(0)));
let other = lock.clone();
let hand = loom::thread::spawn(move || bump(&other));
let seen = read(&lock);
assert!(seen == 0 || seen == 1, "read a value nobody wrote");
hand.join().unwrap();
assert_eq!(read(&lock), 1);
});
}
#[test]
fn a_take_that_fails_changes_nothing() {
loom::model(|| {
let lock = loom::sync::Arc::new(Lock::new(Guarded::new(0)));
let other = lock.clone();
let hand = loom::thread::spawn(move || {
if let Some(held) = other.try_lock() {
held.with_mut(|p| unsafe { *p += 1 });
}
});
bump(&lock);
hand.join().unwrap();
let count = read(&lock);
assert!(count == 1 || count == 2, "count is {count}");
});
}
}