When writing cross platform C++, you only have atomic behavior when using std::atomic<>
.
It is true that on certain platforms, like Intel 64bit, the processor guarantees that inc
is atomic. However, please don't write code that depends on this! As your future debugger, I would like to know which data is intended to be shared over threads and which isn't.
Using std::atomic<int>
might be a bit more work to write, however, it does guarantee that everything behaves atomically (on every platform) by either falling back to the platform requirements (std::atomic::is_lock_free), or by explicitly putting a lock around the access. It as well insert guards in order to make sure that the caches of the other processor cores are invalidated (if the platform requires this).
In practice for Intel 64bit, this should give you the same assembly, if not, log a bug on your compiler.
At the same time, some operations with ints might not be atomic (operator*=), std::atomic
simply doesn't hold those operations, requiring you to correctly work with those.
On a side note: ++x
and x = x+1
are different operations, they might be optimized to the same assembly. Given non-atomic platform requirements, the second suddenly is a bug which takes days to solve.
++x
is atomic doesn't mean, thatx=x+1
isn't? (From a logical point of view, I doubt, that++x
is always atomic anyway) – Bradleystd::atomic
would be implemented by someone who knows the hardware that you're targeting, perhaps far better than you do. Let the expert do the work. Usestd::atomic
when you need atomicity. – Eustace++
are not unary-operators such as& * + - ~ !
. but part of a unary-expression. So the question title is inconsistent with the body. – Arbuckleoperator++
is also not part of unary-expression but postfix-expression. Unary operator is a general, widely understood term that is used correctly here. – Barbet