Do non-observable atomics synchronize memory?
atomic, c, c11, compiler-optimization, multithreading
Solution
First of all we have 6.2.6.1 p9
Loads and stores of objects with atomic types are done with `memory_order_seq_cst` semantics.
and the same holds for other operations on atomic objects.
So the stores in question have `memory_order_seq_cst` semantics. For these, it is then stated in 7.17.3 that they appear sequenced in a total order `S` of all such operations. All other modifications of objects that are in some ordering relation with events in `S` are constrained by that ordering.
The atomic objects themselves and the operations can be optimized out since the value is not observable. But the effect of `foo()` is that of a `memory_order_seq_cst` fence, and that fence should not be optimized out.
Problem
In general, C11 atomics not only guarantee the atomicity of the operation on the atomic object itself, but also provide memory synchronization for access to other (non-atomic) objects. However, I'm unclear whether this synchronization is a side-effect in itself that can be observed, in a strictly conforming program, independently of the atomic object, or if it is only meaningful when the atomic object performing the synchronization is accessed by all threads for which the synchronization needs to take place. In particular, given a function such as: ``` void foo() { _Atomic int x = 0; x++; } ``` does the compiler need to generate any code for this function? Or, since the lifetime of `x` ends immediately with no opportunity for it to participate in synchronization with other threads, can the compiler optimize out the whole function?