|
| 1 | +use std::cell::UnsafeCell; |
| 2 | +use std::ops::{Deref, DerefMut}; |
| 3 | +use std::sync::atomic::{AtomicBool, Ordering}; |
| 4 | + |
| 5 | +use crossbeam_utils::Backoff; |
| 6 | + |
| 7 | +/// A simple spinlock. |
| 8 | +/// |
| 9 | +/// ``` |
| 10 | +/// # async_std::task::block_on(async { |
| 11 | +/// # |
| 12 | +/// use async_std::sync::{Arc, Spinlock}; |
| 13 | +/// use async_std::task; |
| 14 | +/// |
| 15 | +/// let m = Arc::new(Spinlock::new(0)); |
| 16 | +/// let mut tasks = vec![]; |
| 17 | +/// |
| 18 | +/// for _ in 0..10 { |
| 19 | +/// let m = m.clone(); |
| 20 | +/// tasks.push(task::spawn(async move { |
| 21 | +/// *m.lock() += 1; |
| 22 | +/// })); |
| 23 | +/// } |
| 24 | +/// |
| 25 | +/// for t in tasks { |
| 26 | +/// t.await; |
| 27 | +/// } |
| 28 | +/// assert_eq!(*m.lock(), 10); |
| 29 | +/// # |
| 30 | +/// # }) |
| 31 | +/// ``` |
| 32 | +#[derive(Debug)] |
| 33 | +pub struct Spinlock<T> { |
| 34 | + flag: AtomicBool, |
| 35 | + value: UnsafeCell<T>, |
| 36 | +} |
| 37 | + |
| 38 | +unsafe impl<T: Send> Send for Spinlock<T> {} |
| 39 | +unsafe impl<T: Send> Sync for Spinlock<T> {} |
| 40 | + |
| 41 | +impl<T> Spinlock<T> { |
| 42 | + /// Returns a new spinlock initialized with `value`. |
| 43 | + pub const fn new(value: T) -> Spinlock<T> { |
| 44 | + Spinlock { |
| 45 | + flag: AtomicBool::new(false), |
| 46 | + value: UnsafeCell::new(value), |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + /// Locks the spinlock. |
| 51 | + pub fn lock(&self) -> SpinlockGuard<'_, T> { |
| 52 | + let backoff = Backoff::new(); |
| 53 | + while self.flag.swap(true, Ordering::Acquire) { |
| 54 | + backoff.snooze(); |
| 55 | + } |
| 56 | + SpinlockGuard { parent: self } |
| 57 | + } |
| 58 | + |
| 59 | + /// Attempts to lock the spinlock. |
| 60 | + pub fn try_lock(&self) -> Option<SpinlockGuard<'_, T>> { |
| 61 | + if self.flag.swap(true, Ordering::Acquire) { |
| 62 | + None |
| 63 | + } else { |
| 64 | + Some(SpinlockGuard { parent: self }) |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +/// A guard holding a spinlock locked. |
| 70 | +#[derive(Debug)] |
| 71 | +pub struct SpinlockGuard<'a, T> { |
| 72 | + parent: &'a Spinlock<T>, |
| 73 | +} |
| 74 | + |
| 75 | +unsafe impl<T: Send> Send for SpinlockGuard<'_, T> {} |
| 76 | +unsafe impl<T: Sync> Sync for SpinlockGuard<'_, T> {} |
| 77 | + |
| 78 | +impl<'a, T> Drop for SpinlockGuard<'a, T> { |
| 79 | + fn drop(&mut self) { |
| 80 | + self.parent.flag.store(false, Ordering::Release); |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +impl<'a, T> Deref for SpinlockGuard<'a, T> { |
| 85 | + type Target = T; |
| 86 | + |
| 87 | + fn deref(&self) -> &T { |
| 88 | + unsafe { &*self.parent.value.get() } |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +impl<'a, T> DerefMut for SpinlockGuard<'a, T> { |
| 93 | + fn deref_mut(&mut self) -> &mut T { |
| 94 | + unsafe { &mut *self.parent.value.get() } |
| 95 | + } |
| 96 | +} |
0 commit comments