Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why C/C++ compiler not always make ++a atomic?

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?

like image 205
Louis Avatar asked Jan 14 '18 07:01

Louis


2 Answers

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.

like image 200
Silvio Mayolo Avatar answered Sep 20 '22 13:09

Silvio Mayolo


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.

like image 24
Jens Gustedt Avatar answered Sep 16 '22 13:09

Jens Gustedt