Skip to main content

modrt/shared/rt/
sync.rs

1// sync -- a spin lock for short critical sections (allocator-free, usable in statics)
2//
3//   SpinLock::new(value)        const
4//   lock.lock() -> guard        spins a little, then gives the time slice away
5//   lock.try_lock() -> Option   the guard only when the lock is free (crash paths)
6//
7// For data that several threads touch briefly (the environment overrides, the pool
8// queue); long waits belong on a semaphore (plat::Sem).
9
10use core::cell::UnsafeCell;
11use core::marker::PhantomData;
12use core::ops::{Deref, DerefMut};
13use core::sync::atomic::{AtomicBool, Ordering};
14
15pub struct SpinLock<T> {
16    locked: AtomicBool,
17    val: UnsafeCell<T>,
18}
19
20// SAFETY: the lock hands out one guard at a time, so T moves between threads only.
21unsafe impl<T: Send> Sync for SpinLock<T> {}
22unsafe impl<T: Send> Send for SpinLock<T> {}
23
24pub struct Guard<'a, T> {
25    lock: &'a SpinLock<T>,
26    // a shared guard hands out &T on every thread that holds a reference to it, so the guard
27    // may be Sync only when T is (as with &mut T); Send stays as it was (T: Send)
28    _t: PhantomData<&'a mut T>,
29}
30
31impl<T> SpinLock<T> {
32    pub const fn new(v: T) -> Self {
33        SpinLock { locked: AtomicBool::new(false), val: UnsafeCell::new(v) }
34    }
35
36    pub fn lock(&self) -> Guard<'_, T> {
37        let mut spins = 0u32;
38        while self.locked.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
39            spins += 1;
40            if spins < 64 {
41                core::hint::spin_loop();
42            } else {
43                crate::os::yield_now();
44            }
45        }
46        Guard { lock: self, _t: PhantomData }
47    }
48
49    /// the guard when the lock is free now, else None (never waits)
50    pub fn try_lock(&self) -> Option<Guard<'_, T>> {
51        // the guard only after the exchange succeeded: a guard built for a failed attempt
52        // (then_some evaluates its argument) would unlock the holder's lock when it drops
53        match self.locked.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) {
54            Ok(_) => Some(Guard { lock: self, _t: PhantomData }),
55            Err(_) => None,
56        }
57    }
58}
59
60impl<T> Deref for Guard<'_, T> {
61    type Target = T;
62    fn deref(&self) -> &T {
63        // SAFETY: the guard holds the lock.
64        unsafe { &*self.lock.val.get() }
65    }
66}
67
68impl<T> DerefMut for Guard<'_, T> {
69    fn deref_mut(&mut self) -> &mut T {
70        // SAFETY: the guard holds the lock.
71        unsafe { &mut *self.lock.val.get() }
72    }
73}
74
75impl<T> Drop for Guard<'_, T> {
76    fn drop(&mut self) {
77        self.lock.locked.store(false, Ordering::Release);
78    }
79}