stdatomic
For purposes of ordering, is atomic read-modify-write one operation or two?
Not an answer at the level of the language standard, but some evidence that in practice, the answer can be “two”. And as I guessed in the question, this can happen even if the RMW is seq_cst. I haven’t been able to observe stores being reordered as in the original question, but here is an … Read more
When do I really need to use atomic instead of bool? [duplicate]
No type in C++ is “atomic by nature” unless it is an std::atomic*-something. That’s because the standard says so. In practice, the actual hardware instructions that are emitted to manipulate an std::atomic<bool> may (or may not) be the same as those for an ordinary bool, but being atomic is a larger concept with wider ramifications … Read more
Implementing 64 bit atomic counter with 32 bit atomics
This is a known pattern, called a SeqLock. https://en.wikipedia.org/wiki/Seqlock. (With the simplification that there’s only one writer so no extra support for excluding simultaneous writers is needed.) You don’t need or want the increment of the counter variable itself to use atomic RMW operations. (Unless you’re on a system that can do that cheaply with … Read more
Why don’t compilers merge redundant std::atomic writes?
The C++11 / C++14 standards as written do allow the three stores to be folded/coalesced into one store of the final value. Even in a case like this: y.store(1, order); y.store(2, order); y.store(3, order); // inlining + constant-folding could produce this in real code The standard does not guarantee that an observer spinning on y … Read more
Will two atomic writes to different locations in different threads always be seen in the same order by other threads?
This kind of reordering test is called IRIW (Independent Readers, Independent Writers), where we’re checking if two readers can see the same pair of stores appear in different orders. Related, maybe a duplicate: Acquire/release semantics with 4 threads The very weak C++11 memory model does not require that all threads agree on a global order … Read more