GCC內建原子性操作

2021-07-31 23:05:29 字數 1339 閱讀 6368

先簡單看一篇關於gcc原子性操作的概念東西吧,見

gcc內建原子操作函式

再來看一看陳碩老師封裝的原子類,很簡單,拿來直接用了。(ps:我去掉了namespace)

下面是執行緒安全的

// use of this source code is governed by a bsd-style license

// that can be found in the license file.

//// author: shuo chen (chenshuo at chenshuo dot com)

#ifndef muduo_base_atomic_h

#define muduo_base_atomic_h

#include

#include

templateclass atomicintegert : boost::noncopyable

// uncomment if you need copying and assignment

//// atomicintegert(const atomicintegert& that)

// : value_(that.get())

// {}

//// atomicintegert& operator=(const atomicintegert& that)

// t get()

t getandadd(t x)

t addandget(t x)

t incrementandget()

t decrementandget()

void add(t x)

void increment()

void decrement()

t getandset(t newvalue)

private:

/*volatile變數

c和c++中的volatile並不是用來解決多執行緒競爭問題的?

而是用來修飾一些因為程式不可控因素導致變化的變數,比如訪問底層硬體裝置的變數,

以提醒編譯器不要對該變數的訪問擅自進行優化

*/volatile t value_;

};typedef detail::atomicintegertatomicint32;

typedef detail::atomicintegertatomicint64;

#endif // muduo_base_atomic_h

附帶上的測試程式

#include

#include

int main()

}

原子性,原子操作

舉個例子 a想要從自己的帳戶中轉1000塊錢到b的帳戶裡。那個從a開始轉帳,到轉帳結束的這乙個過程,稱之為乙個事務。在這個事務裡,要做如下操作 從a的帳戶中減去1000塊錢。如果a的帳戶原來有3000塊錢,現在就變成2000塊錢了。在b的帳戶裡加1000塊錢。如果b的帳戶如果原來有2000塊錢,現在...

GCC的原子操作

gcc從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 sy...

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...