Skip to content

New scheduler #733

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Apr 7, 2020
10 changes: 5 additions & 5 deletions src/sync/spin_lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use crossbeam_utils::Backoff;
/// ```
#[derive(Debug)]
pub struct Spinlock<T> {
flag: AtomicBool,
locked: AtomicBool,
value: UnsafeCell<T>,
}

Expand All @@ -42,23 +42,23 @@ impl<T> Spinlock<T> {
/// Returns a new spinlock initialized with `value`.
pub const fn new(value: T) -> Spinlock<T> {
Spinlock {
flag: AtomicBool::new(false),
locked: AtomicBool::new(false),
value: UnsafeCell::new(value),
}
}

/// Locks the spinlock.
pub fn lock(&self) -> SpinlockGuard<'_, T> {
let backoff = Backoff::new();
while self.flag.swap(true, Ordering::Acquire) {
while self.locked.compare_and_swap(false, true, Ordering::Acquire) {
backoff.snooze();
}
SpinlockGuard { parent: self }
}

/// Attempts to lock the spinlock.
pub fn try_lock(&self) -> Option<SpinlockGuard<'_, T>> {
if self.flag.swap(true, Ordering::Acquire) {
if self.locked.swap(true, Ordering::Acquire) {
None
} else {
Some(SpinlockGuard { parent: self })
Expand All @@ -77,7 +77,7 @@ unsafe impl<T: Sync> Sync for SpinlockGuard<'_, T> {}

impl<'a, T> Drop for SpinlockGuard<'a, T> {
fn drop(&mut self) {
self.parent.flag.store(false, Ordering::Release);
self.parent.locked.store(false, Ordering::Release);
}
}

Expand Down