Linux下原子操作函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_28110727/article/details/78813694
Linux 下gcc内置的原子操作函数


头文件
#include<asm/atomic.h>
编译时需要加上-march= cpu-type(可以设置为native 让系统自动去检测)


//先获取值再操作
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, ...)


//相等赋值 不相等直接返回原来的值
bool __sync_bool_compare_and_swap (type *ptr, type oldval, type newval, ...)
type __sync_val_compare_and_swap (type *ptr, type oldval, type newval, ...)


//原子赋值
type __sync_lock_test_and_set(type* ptr, type value)




类的封装
在实现相关得接口过程中可以调用内置的原子操作函数进行实现
template<class T>
class Automic
{
public:
Automic();
Automic(T value);
T get();
T get_and_add();
T add_and_get();
T increment();
T decrement();
void add();
private:
T _value;
};


Automic::Automic():_value(0)
{


}


Automic::Automic(T value):_value(value)
{


}
T Automic::get()
{
return __sync_val_compare_and_swap(&_value, 0, 0);
}

猜你喜欢

转载自blog.csdn.net/qq_28110727/article/details/78813694