理解多執行緒(四)--原子量和原子操作
阿新 • • 發佈:2018-12-28
原子量
互斥量可以對於共享變數的訪問進行加鎖,可以保證對臨界區的互斥訪問,但加鎖總是繁瑣的,所以提供了更簡單的共享變數保護訪問的操作,原子量和原子操作。
原子量的構造
原子量包含在#include 中,對於基本型別,我們可以這樣定義原子變數
std::atomic_bool abool;
std::atomic_int aint;
std::atomic_uint auint;
std::atomic_char achar;
std: :atomic_schar aschar;
std::atomic_uchar auchar;
std::atomic_short ashort;
也可以使用atomic的模版定義
std::atomic<int> aint;
std::atomic<bool> abool;
原子變數不支援拷貝構造,move構造,賦值構造等。
std::atomic<int> aint=0;
std::atomic<int> aint2= aint;//error
std::atomic<int> aint3{std::move(aint)}//error
std::atomic<int> aint4(aint)//error
簡單用法
原子變數已經內部封裝好各種操作,=,+=,++等等,可以像基本變數一樣操作
#include <iostream>
#include <atomic>
#include <thread>
std::atomic<int> i=0;
void add()
{
for (int j = 0; j < 100000; ++j)
i++;
}
int main()
{
//i.store(0);
std::vector<std::thread> workers;
for (int j = 0; j < 10; ++j)
std::thread(add).detach();
std::this_thread::sleep_for(std::chrono::microseconds(100000));
std::cout << i << std::endl;
system("pause");
return 0;
}
當然atomic是一個模版,所以,也是可以用自定義型別的。比如
class test
{
int a;
int b;
};
std::atomic<test> i;
當然不是所有類都支援。
原子操作
自加操作
傳入地址
LONG InterlockedIncrement(LONG *pAddend);
自減操作
LONG InterlockedDecrement(LONG *pAddend);
增加/減某個值
LONG InterlockedExchangeAdd(LONG *pAddend, LONG Increment );
交換
LONG InterlockedExchange( LPLONG Target, LONG Value );
比較交換
LONG InterlockedCompareExchange(
LPLONG Destination, LONG Exchange, LONG Comperand );