Skip to content

Commit 5c5a518

Browse files
author
Stjepan Glavina
committed
Optimize AtomicBool::fetch_nand
1 parent 4c59c92 commit 5c5a518

File tree

2 files changed

+27
-10
lines changed

2 files changed

+27
-10
lines changed

src/libcore/sync/atomic.rs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -539,17 +539,21 @@ impl AtomicBool {
539539
// We can't use atomic_nand here because it can result in a bool with
540540
// an invalid value. This happens because the atomic operation is done
541541
// with an 8-bit integer internally, which would set the upper 7 bits.
542-
// So we just use a compare-exchange loop instead, which is what the
543-
// intrinsic actually expands to anyways on many platforms.
544-
let mut old = self.load(Relaxed);
545-
loop {
546-
let new = !(old && val);
547-
match self.compare_exchange_weak(old, new, order, Relaxed) {
548-
Ok(_) => break,
549-
Err(x) => old = x,
542+
// So we just use fetch_xor or compare_exchange instead.
543+
if val {
544+
// !(x & true) == !x
545+
// We must invert the bool.
546+
self.fetch_xor(true, order)
547+
} else {
548+
// !(x & false) == true
549+
// We must set the bool to true. Instead of delegating to swap or fetch_or, use
550+
// compare_exchange instead in order to avoid unnecessary writes to memory, which
551+
// might minimize cache-coherence traffic.
552+
match self.compare_exchange(false, true, order, Ordering::Relaxed) {
553+
Ok(_) => false,
554+
Err(_) => true,
550555
}
551556
}
552-
old
553557
}
554558

555559
/// Logical "or" with a boolean value.

src/libcore/tests/atomic.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,23 @@ fn bool_() {
2424
#[test]
2525
fn bool_and() {
2626
let a = AtomicBool::new(true);
27-
assert_eq!(a.fetch_and(false, SeqCst),true);
27+
assert_eq!(a.fetch_and(false, SeqCst), true);
2828
assert_eq!(a.load(SeqCst),false);
2929
}
3030

31+
#[test]
32+
fn bool_nand() {
33+
let a = AtomicBool::new(false);
34+
assert_eq!(a.fetch_nand(false, SeqCst), false);
35+
assert_eq!(a.load(SeqCst), true);
36+
assert_eq!(a.fetch_nand(false, SeqCst), true);
37+
assert_eq!(a.load(SeqCst), true);
38+
assert_eq!(a.fetch_nand(true, SeqCst), true);
39+
assert_eq!(a.load(SeqCst), false);
40+
assert_eq!(a.fetch_nand(true, SeqCst), false);
41+
assert_eq!(a.load(SeqCst), true);
42+
}
43+
3144
#[test]
3245
fn uint_and() {
3346
let x = AtomicUsize::new(0xf731);

0 commit comments

Comments
 (0)