Skip to main content

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::ops::{Deref, DerefMut};
12use core::sync::atomic::{AtomicBool, Ordering};
13
14pub struct SpinLock<T> {
15    locked: AtomicBool,
16    val: UnsafeCell<T>,
17}
18
19// SAFETY: the lock hands out one guard at a time, so T moves between threads only.
20unsafe impl<T: Send> Sync for SpinLock<T> {}
21unsafe impl<T: Send> Send for SpinLock<T> {}
22
23pub struct Guard<'a, T> {
24    lock: &'a SpinLock<T>,
25}
26
27impl<T> SpinLock<T> {
28    pub const fn new(v: T) -> Self {
29        SpinLock { locked: AtomicBool::new(false), val: UnsafeCell::new(v) }
30    }
31
32    pub fn lock(&self) -> Guard<'_, T> {
33        let mut spins = 0u32;
34        while self.locked.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed).is_err() {
35            spins += 1;
36            if spins < 64 {
37                core::hint::spin_loop();
38            } else {
39                crate::os::yield_now();
40            }
41        }
42        Guard { lock: self }
43    }
44
45    /// the guard when the lock is free now, else None (never waits)
46    pub fn try_lock(&self) -> Option<Guard<'_, T>> {
47        self.locked.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed).is_ok().then_some(Guard { lock: self })
48    }
49}
50
51impl<T> Deref for Guard<'_, T> {
52    type Target = T;
53    fn deref(&self) -> &T {
54        // SAFETY: the guard holds the lock.
55        unsafe { &*self.lock.val.get() }
56    }
57}
58
59impl<T> DerefMut for Guard<'_, T> {
60    fn deref_mut(&mut self) -> &mut T {
61        // SAFETY: the guard holds the lock.
62        unsafe { &mut *self.lock.val.get() }
63    }
64}
65
66impl<T> Drop for Guard<'_, T> {
67    fn drop(&mut self) {
68        self.lock.locked.store(false, Ordering::Release);
69    }
70}