Oh, I see. I managed to confuse the semantic monikers.

'memory_order_seq_cst' is actually the _strongest_ semantics that guarantees 
the total ordering, not "weaker" semantics, as I incorrectly assumed in my 
previous reply. 'memory_order_seq_cst' is what we get from locked instructions, 
e.g. 'xchg'.

Meanwhile, 'mov' on x86 only provides us with release semantics (for free). And 
that is not sufficient to satisfy the standard requirements wrt atomic 
assignment. 

That is why the compiler insists on 'xchg'.

> On 09/25/2026 10:50 AM PDT LIU Hao <[email protected]> wrote:
> 
>  
> 在 2026-9-26 00:33, Andrey Tarasevich via Gcc 写道:
> > I see. Thank you.
> > 
> > I presume your answer is intended to state the same thing as Martin's 
> > answer. However, I'm a bit perplexed by
> > the code snippet you supplied. Both variables are declared '_Atomic' in 
> > your code. Which means that the
> > compiler (GCC x86-64 at least) will generate an 'xchg' (with an implied 
> > 'lock') in response to a simple
> > assignment. This is what originally prompted my question. With locked 
> > 'xchg' the memory ordering issue you
> > describe cannot occur, can it? Only if we remove the '_Atomic' qualifiers 
> > from your declarations, the compiler
> > will resort to using 'mov' to implement simple assignment, which has weaker 
> > ordering semantics
> > ('memory_order_seq_cst', i.e. just 'release' in this particular case), and 
> > which can lead to
> > different observers seeing different orders of 'x' and 'y' modifications.
> > 
> > Is my above interpretation of your answer correct? Or am I still missing 
> > something?
> 
> The reason is that the C standard requires that stores to an `_Atomic` object 
> have 
> sequentially-consistent semantics. In order to get `mov`, you should specify 
> release semantics 
> explicitly, like `atomic_store_explicit(&x, 1, memory_order_release)`.
> 
> Removing `_Atomic` makes the store non-atomic. It has no release semantics, 
> but it happens to work on x86 
> since most store instructions have release semantics. (notable exceptions are 
> `movnt*` which have relaxed 
> semantics.)
> 
> 
> -- 
> Best regards,
> LIU Hao

Reply via email to