Skip to content

Implement try_lock_weak for use in lock loop #4

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 1 commit into from Jul 6, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion src/spinlock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,17 @@ pub struct RawSpinlock {
locked: AtomicBool,
}

impl RawSpinlock {
// Can fail to lock even if the spinlock is not locked. May be more efficient than `try_lock`
// when called in a loop.
fn try_lock_weak(&self) -> bool {
// The Orderings are the same as try_lock, and are still correct here.
self.locked
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
.is_ok()
}
}

unsafe impl RawMutex for RawSpinlock {
const INIT: RawSpinlock = RawSpinlock {
locked: AtomicBool::new(false),
Expand All @@ -35,7 +46,7 @@ unsafe impl RawMutex for RawSpinlock {
type GuardMarker = GuardSend;

fn lock(&self) {
while !self.try_lock() {
while !self.try_lock_weak() {
// Wait until the lock looks unlocked before retrying
// Code from https://github.com/mvdnes/spin-rs/commit/d3e60d19adbde8c8e9d3199c7c51e51ee5a20bf6
//
Expand Down