forked from mirror/async-std
refactor: swap to swap_and_compare
This commit is contained in:
parent
b1ec1ea930
commit
2b44c1be2e
1 changed files with 5 additions and 5 deletions
|
@ -31,7 +31,7 @@ use crossbeam_utils::Backoff;
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Spinlock<T> {
|
pub struct Spinlock<T> {
|
||||||
flag: AtomicBool,
|
locked: AtomicBool,
|
||||||
value: UnsafeCell<T>,
|
value: UnsafeCell<T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -42,7 +42,7 @@ impl<T> Spinlock<T> {
|
||||||
/// Returns a new spinlock initialized with `value`.
|
/// Returns a new spinlock initialized with `value`.
|
||||||
pub const fn new(value: T) -> Spinlock<T> {
|
pub const fn new(value: T) -> Spinlock<T> {
|
||||||
Spinlock {
|
Spinlock {
|
||||||
flag: AtomicBool::new(false),
|
locked: AtomicBool::new(false),
|
||||||
value: UnsafeCell::new(value),
|
value: UnsafeCell::new(value),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -50,7 +50,7 @@ impl<T> Spinlock<T> {
|
||||||
/// Locks the spinlock.
|
/// Locks the spinlock.
|
||||||
pub fn lock(&self) -> SpinlockGuard<'_, T> {
|
pub fn lock(&self) -> SpinlockGuard<'_, T> {
|
||||||
let backoff = Backoff::new();
|
let backoff = Backoff::new();
|
||||||
while self.flag.swap(true, Ordering::Acquire) {
|
while self.locked.compare_and_swap(false, true, Ordering::Acquire) {
|
||||||
backoff.snooze();
|
backoff.snooze();
|
||||||
}
|
}
|
||||||
SpinlockGuard { parent: self }
|
SpinlockGuard { parent: self }
|
||||||
|
@ -58,7 +58,7 @@ impl<T> Spinlock<T> {
|
||||||
|
|
||||||
/// Attempts to lock the spinlock.
|
/// Attempts to lock the spinlock.
|
||||||
pub fn try_lock(&self) -> Option<SpinlockGuard<'_, T>> {
|
pub fn try_lock(&self) -> Option<SpinlockGuard<'_, T>> {
|
||||||
if self.flag.swap(true, Ordering::Acquire) {
|
if self.locked.swap(true, Ordering::Acquire) {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
Some(SpinlockGuard { parent: self })
|
Some(SpinlockGuard { parent: self })
|
||||||
|
@ -77,7 +77,7 @@ unsafe impl<T: Sync> Sync for SpinlockGuard<'_, T> {}
|
||||||
|
|
||||||
impl<'a, T> Drop for SpinlockGuard<'a, T> {
|
impl<'a, T> Drop for SpinlockGuard<'a, T> {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.parent.flag.store(false, Ordering::Release);
|
self.parent.locked.store(false, Ordering::Release);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue