gcc原子操作
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, ...)
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, ...)
拥有比正常的读写锁、互斥锁更高的性能。但是频繁使用可能造成进程性能的降低,这点要注意
代码
int next = 0;
__sync_fetch_and_add(&next, 3);
通过反汇编可以得到下面这个语句:
lock addl $0x3,(%rax)
lock表示锁前端总线FSB,FSB被锁住会导致其他线程无法从RAM中获取数据,在多线程CPU密集型的应用里,会导致系统整体性能降低。因此使用原子操作也是有代价的
由于使用原子操作有一定代价,因此原子操作针对的都是int/int64这种简单类型