1. 程式人生 > >Linux下原子操作函式

Linux下原子操作函式

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);
}