C++ Logo

std-discussion

Advanced search

Re: Ordering semantics of compare_exchange_weak on spurious failure

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Tue, 31 Mar 2026 10:55:16 +0300
On 31 Mar 2026 07:11, Nate Eldredge via Std-Discussion wrote:
> I was looking at the description of `std::atomic::compare_exchange_weak`
> in [atomics.types.operations p21-28] (https://eel.is/c++draft/
> atomics.types.operations#21 <https://eel.is/c++draft/
> atomics.types.operations#21>), and it seems to be a bit ambiguous on the
> ordering semantics of spurious failure.
>
> Recall that `compare_exchange_weak` can be passed two `memory_order`
> arguments, `success` and `failure`. From the naming, I presume that in
> case of spurious failure, the `failure` ordering is meant to be applied.
> (Example of clang doing so: https://godbolt.org/z/613P4WMhd.) However,
> this is not actually stated.
>
> Ordering is only mentioned in p23 ("Effects"), which although it
> supposedly applies to both compare_exchange_strong and
> compare_exchange_weak, actually only describes the strong semantics. It
> does not allow for spurious failures, which are carved out later by p27
> ("Remarks"). Paragraph p23 says:
>
> "If and only if the comparison is true, memory is affected according to
> the value of success, and if the comparison is false, memory is affected
> according to the value of failure."
>
> If we read this literally, then spurious failure ought to follow the
> success ordering, because the comparison is true in that case, and p27
> doesn't say anything to contradict it. But that doesn't seem to be
> what's intended.

Consider what is referred to as a "spurious failure", which is defined
in p27 (https://eel.is/c++draft/atomics.types.operations#27):

  Remarks: A weak compare-and-exchange operation may fail spuriously.
  That is, even when the contents of memory referred to by expected and
  this are equal, it may return false and store back to expected the
  same memory contents that were originally there.

So, the behavior in the case of a spurious failure would be equivalent
to that of when the comparison legitimately returns false.

Received on 2026-03-31 07:55:22