Skip to content

Commit 8c992d5

Browse files
committed
Add #[must_use] to compare_and_swap
`compare_and_swap` can fail if the value in memory has changed since it was last read by the writer. In these situations, users will usually want to retry or abort. While developers are usually aware of this aspect of CAS, the compiler might as well be helpful and remind the user if they forget to check if their swap actually occurred.
1 parent 5b52591 commit 8c992d5

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

src/libcore/sync/atomic.rs

+4
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,7 @@ impl AtomicBool {
403403
#[inline]
404404
#[stable(feature = "rust1", since = "1.0.0")]
405405
#[cfg(any(stage0, target_has_atomic = "cas"))]
406+
#[must_use = "if compare_and_swap does not return `current`, the stored value was not changed"]
406407
pub fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool {
407408
match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
408409
Ok(x) => x,
@@ -824,6 +825,7 @@ impl<T> AtomicPtr<T> {
824825
#[inline]
825826
#[stable(feature = "rust1", since = "1.0.0")]
826827
#[cfg(any(stage0, target_has_atomic = "cas"))]
828+
#[must_use = "if compare_and_swap does not return `current`, the stored value was not changed"]
827829
pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T {
828830
match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
829831
Ok(x) => x,
@@ -1182,6 +1184,8 @@ assert_eq!(some_var.load(Ordering::Relaxed), 10);
11821184
#[inline]
11831185
#[$stable]
11841186
#[cfg(any(stage0, target_has_atomic = "cas"))]
1187+
#[must_use = "if compare_and_swap does not return `current`, \
1188+
the stored value was not changed"]
11851189
pub fn compare_and_swap(&self,
11861190
current: $int_type,
11871191
new: $int_type,

0 commit comments

Comments
 (0)