Why does the C / C ++ compiler not always make ++ atomic?

As a header, when we write ++a in C/C++ , it seems the compiler can 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 compiling it as a non-nuclear style?

+5
source share
3 answers

What if your code looks like this?

 ++a; if (a > 1) { ... } 

If the compiler uses the first representation, it accesses memory to increase a , then accesses memory again to compare with 1 . In the second case, it accesses the memory to get the value once and puts it in eax . Then it simply compares the eax register with 1 , which is much faster.

+9
source

First, you seem to have a very specific processor family. Not everyone has an instruction that acts directly in memory.

Even if they are, one instruction of this kind can be very complicated and expensive. If it is truly atomic, as you say, it must stop all other bus transfers. This slows down the computation to the speed of the memory bus. Usually these orders are slower than the processor.

+2
source

The non-atomic variant ends with a value in the register, ready for future use.

0
source

Source: https://habr.com/ru/post/1274687/


All Articles