cc从4.1.2提供了__sync_*系列的built-in函数,用于提供加减和逻辑运算的原子操做。
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, ...)
这一系列函数完成对ptr所指向的内存地址的对应操做,并返回操做以前的值。
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, ...)
这一系列函数完成对ptr所指向的内存地址的对应操做,并返回操做以后的值
bool __sync_bool_compare_and_swap (type *ptr, type oldval, type newval, ...)
type __sync_val_compare_and_swap (type *ptr, type oldval, type newval, ...)
这两个函数完成对变量的原子比较和交换。即若是ptr所指向的内存地址存放的值与oldval相同的话,
则将其用newval的值替换。
返回bool类型的函数返回比较的结果,相同为true,不一样为false;返回type的函数返回的是ptr指向地址交换前存放的值。html
type能够是1,2,4或8字节长度的int类型,即:linux
int8_t / uint8_t函数
int16_t / uint16_tfetch
int32_t / uint32_tui
int64_t / uint64_tspa
这两组函数的区别在于第一组返回更新前的值,第二组返回更新后的值。code
后面的可扩展参数(...)用来指出哪些变量须要memory barrier,由于目前gcc实现的是full barrier(相似于linux kernel 中的mb(),表示这个操做以前的全部内存操做不会被重排序到这个操做以后),因此能够略掉这个参数。htm
还有两个函数:
type __sync_lock_test_and_set (type *ptr, type value, ...)
将*ptr设为value并返回*ptr操做以前的值。
void __sync_lock_release (type *ptr, ...)
将*ptr置0
排序
https://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html#Atomic-Builtins内存