Recently, in the user State, we suddenly needed to use atomic variables, and didn't want to compile boost on our own. We accidentally found that GCC still has this set of built-in functions.
// First perform the operation, and then return the changed Value Type _ sync_fetch_and_add (type * PTR, type value); Type _ sync_fetch_and_sub (type * PTR, type value ); type _ sync_fetch_and_or (type * PTR, type value); Type _ sync_fetch_and_and (type * PTR, type value); Type _ sync_fetch_and_xor (type * PTR, type value ); type _ sync_fetch_and_nand (type * PTR, type value); // first return the value before the change, and then perform the operation type _ sync_add_and_fetch (type * PTR, type value ); type _ sync_sub_and_fetch (type * PTR, type value); Type _ sync_or_and_fetch (type * PTR, type value); Type _ sync_and_and_fetch (type * PTR, type value ); type _ sync_xor_and_fetch (type * PTR, type value); Type _ sync_nand_and_fetch (type * PTR, type value );
According to the official document,
GCC will allow any integral scalar or pointer type that is 1, 2, 4, or 8 bytes in length. 16-byte integral types are also allowed if '_ int128' (see _ int128) is supported by the architecture.
That is to say, an integer with a length of at least 1, 2, and 4, 8 is supported.
After a simple test, we found that no header files need to be included. During GCC compilation, the corresponding assembly code is automatically replaced.
int main(){ int a = 100; __sync_fetch_and_add(&a,1); return a;}
The following figure shows the generated assembly:
. File "funtest. C ". text. globl main. type main, @ functionmain :. lfb0 :. cfi_startproc pushq % RBP. cfi_def_cfa_offset 16. cfi_offset 6,-16 movq % RSP, % RBP. cfi_def_cfa_register 6 movl $100,-4 (% RBP) Lock addl $1,-4 (% RBP) // _ sync_fetch_and_add (& A, 1 ); corresponding command movl-4 (% RBP), % eax popq % RBP. cfi_def_cfa 7, 8 ret. cfi_endproc.lfe0 :. size main ,. -Main. ident "GCC: (Debian 4.7.2-5) 4.7.2 ". section. note. GNU-stack, "", @ progbits
Reference
Https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/_005f_005fatomic-Builtins.html#_005f_005fatomic-Builtins
Built-in atomic operation functions of GCC