x86 instructions: atomic vs non-atomic assignment in C
LIU Hao
lh_mouse@126.com
Fri Sep 25 17:50:19 GMT 2026
在 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
-------------- next part --------------
A non-text attachment was scrubbed...
Name: OpenPGP_signature.asc
Type: application/pgp-signature
Size: 840 bytes
Desc: OpenPGP digital signature
URL: <https://gcc.gnu.org/pipermail/gcc/attachments/20260926/7981b904/attachment.sig>
More information about the Gcc
mailing list