Skip to content
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

Simplify AtomicBool::fetch_nand #40563

Closed
wants to merge 2 commits into from
Closed
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
27 changes: 18 additions & 9 deletions src/libcore/sync/atomic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -512,17 +512,26 @@ impl AtomicBool {
// We can't use atomic_nand here because it can result in a bool with
// an invalid value. This happens because the atomic operation is done
// with an 8-bit integer internally, which would set the upper 7 bits.
// So we just use a compare-exchange loop instead, which is what the
// intrinsic actually expands to anyways on many platforms.
let mut old = self.load(Relaxed);
loop {
let new = !(old && val);
match self.compare_exchange_weak(old, new, order, Relaxed) {
Ok(_) => break,
Err(x) => old = x,
// So we simplify to fetch_xor or a swap.

// !(true && true) == false
// !(true && false) == true
// !(false && false) == true
// !(false && true) == true

// !(x && true) == !x
// !(x && false) == true
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would use & instead of && in these, seems clearer.

if val {
return self.fetch_xor(true, order);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Explicit return isn't needed.

} else {
// Use a compare exchange instead of a swap because it
// avoids a write in some cases which is good for caches.
match self.compare_exchange(false, true, order,
Ordering::Relaxed) {
Ok(_) => false,
Err(_) => true
}
}
old
}

/// Logical "or" with a boolean value.
Expand Down