1use 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
19unsafe 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 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 unsafe { &*self.lock.val.get() }
56 }
57}
58
59impl<T> DerefMut for Guard<'_, T> {
60 fn deref_mut(&mut self) -> &mut T {
61 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}