As the title, when we write ++a
in C/C++
, it seems the compiler may compile it as:
inc dword ptr[i]
which is atomic, or:
mov eax, dword ptr[i]
inc eax
mov dword ptr[i], eax
which is not atomic.
Is there any advantage to compile it as non-atomic style?
What if your code looks like this?
++a;
if (a > 1) {
...
}
If the compiler uses the first representation, it accesses memory to increment a
, then it accesses memory again to compare to 1
. In the second case, it accesses memory to get the value once and puts it in eax
. Then it simply compares the register eax
against 1
, which is significantly quicker.
First, you seem to have a very particular family of processors in mind. Not all have an instruction that acts directly on memory.
Even if they have, a single instruction of that kind can be a very complex and costly thing. If it is really atomic as you claim, it has to stop all other bus transfers. This slows computation down to the speed of the memory bus. This is usually orders slower than the CPU.
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