Skip to content

Commit 3e6e19c

Browse files
author
Austin Kiekintveld
authored
Implement try_lock_weak for use in lock loop (#4)
Allows use of `compare_exchange_weak`, which may fail spuriously but can be more efficient on certain platforms.
1 parent 03fc40c commit 3e6e19c

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

src/spinlock.rs

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,17 @@ pub struct RawSpinlock {
2626
locked: AtomicBool,
2727
}
2828

29+
impl RawSpinlock {
30+
// Can fail to lock even if the spinlock is not locked. May be more efficient than `try_lock`
31+
// when called in a loop.
32+
fn try_lock_weak(&self) -> bool {
33+
// The Orderings are the same as try_lock, and are still correct here.
34+
self.locked
35+
.compare_exchange_weak(false, true, Ordering::Acquire, Ordering::Relaxed)
36+
.is_ok()
37+
}
38+
}
39+
2940
unsafe impl RawMutex for RawSpinlock {
3041
const INIT: RawSpinlock = RawSpinlock {
3142
locked: AtomicBool::new(false),
@@ -35,7 +46,7 @@ unsafe impl RawMutex for RawSpinlock {
3546
type GuardMarker = GuardSend;
3647

3748
fn lock(&self) {
38-
while !self.try_lock() {
49+
while !self.try_lock_weak() {
3950
// Wait until the lock looks unlocked before retrying
4051
// Code from https://github.com/mvdnes/spin-rs/commit/d3e60d19adbde8c8e9d3199c7c51e51ee5a20bf6
4152
//

0 commit comments

Comments
 (0)