4 ms·
The type is named atomic, but atomicity is not its only useful property. The atomic types also give control over the memory ordering, defaulting to sequentially
by kbolino 1y ago
The type is named atomic, but atomicity is not its only useful property. The atomic types also give control over the memory ordering, defaulting to sequentially consistent (seq_cst, the strongest).
Without memory order guarantees enforced by memory barriers, a write to the boolean in thread A is not guaranteed to be observed by thread B. That matters both after initialization--where thread A sets the boolean to false but thread B may observe true, false, or invalid--and also after the transition--where thread B may fail to observe that the boolean has flipped from false to true.
[edit: I'm not sure the above reasoning actually matters; as stated already by parent, "It's a CPU, not an FPGA"; modern multicore shared-memory CPUs have coherent caches]
- CamperBob2 1y agoWell, it'll be observed the next time through the loop. If that matters, then it's true that this technique isn't desirable.
- manwe150 1y agoWithout atomic, the compiler won’t bother with there being a next time and just infinite loop (in the old days, you’d mark it volatile instead)
- CamperBob2 1y agoTrue enough, but volatile still works, of course.
- adwn 1y ago> Without memory order guarantees enforced by memory barriers, a write to the boolean in thread A is not guaranteed to be observed by thread B. No, that's not correct. Memory ordering doesn't influence how fast a write is propagated to other cores, that's what cache coherency is for. Memory ordering of an access only matters in relation to accesses on other memory locations. There's a great introduction to this topic by Mara Bos: https://marabos.nl/atomics/memory-ordering.html https://marabos.nl/atomics/memory-ordering.html
- kbolino 1y agoIndeed. I started to figure this out, hence my edit. Thanks for the link. There are hypothetical, historical, and special-purpose architectures which don't have cache coherency (or implement it differently enough to matter here), but for all practical purposes, it seems that all modern, general-purpose architectures implement it.