Many CPUs guarantee that reads and writes of common size are atomic. E.g. x86 guarantees that a read or write of an aligned 32 bit val is atomic.
Many, many, many programs rely on this (knowingly or unknowingly) and do not use any type of atomic
coding other than that.
However, it's considered best C++ practice, especially when portability is important, to not rely on the behavior of the CPU like this, and instead use explicit C++, such as atomic
. What is the cost of that? E.g. On x86, what is the cost of atomic int vs regular int?
I imagine that most std::atomic
implementations would be smart enough to look at the underlying CPU. Even then, there's probably some cost, as atomics might insert barriers (or, at the least, compile-time barriers), and probably more barriers than are strictly needed for correctness.