You are wrong. There is no guarantee that ++ is atomic and neither is there for the compound assignment operators, or indeed for any C++ operation.
x++
is often implemented in 3 instructions: Read X into a register, Increment it, and Write it back to memory.
Your thread may be pre-empted in between any of those.
For the change in value to be visible across cores, a += (for instance) would have to load the value, add the increment and then store it. This means that the operation will not be atomic.
To ensure atomicity you'd need to put appropriate locking around the operation.
No, they're not atomic! If you need atomic operations on primitive types, and you're using linux, you can take a look here: http://gcc.gnu.org/onlinedocs/gcc-4.1.0/gcc/Atomic-Builtins.html and/or atomic.h...
++ might be atomic on your compiler/platform, but in the c++ specs it is not defined to be atomic.
If you want to make sure to modify a value in an atomic way, you should use the appropiate methods, like Interlocked* on windows.
Same for all the other routines. If you want atomic operations, you should use the appropiate calls, not the standard ones.
No operator in C or C++ is guaranteed to be atomic. They might be on your platform, but you won't know for sure. Typically, the only operation that is atomic is the an instruction Test and Set, which is usually available on most modern CPUs in some form as the basis for implementing semaphores.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With