1use 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
20unsafe 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 _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 pub fn try_lock(&self) -> Option<Guard<'_, T>> {
51 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 unsafe { &*self.lock.val.get() }
65 }
66}
67
68impl<T> DerefMut for Guard<'_, T> {
69 fn deref_mut(&mut self) -> &mut T {
70 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}