http://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Atomic-Builtins.html
I believe that the following code increases the value of var atomically.
volatile int var = 0;
__sync_fetch_and_add( &var, 1 )
I understood the above codes as the following logic:
- Load the address of variable var
- write number 1 onto variable var atomically - through register/cache, somehow
However, I doubt if the following is atomic, too
volatile int var = 0;
volatile int num = 1;
__sync_fetch_and_add( &var, num )
Since it may be interpreted as
- Load the address of variable var
- Load the value of variable num into a register
- write the value onto variable var.
After #2 is executed, but before #3, the CPU/thread gets interrupted and another CPU/thread updates the value of variable num.
In other words, when using _sync*() of gcc, can I use a variable, not a constant, as the second argument?
Doesn't it break the atomicity?