atomic原子操作:是在新標準c++11,引入了原子操作的概念,並通過這個新的標頭檔案提供了多種原子運算元據型別,例如,atomic_bool,atomic_int等等
#include #include#include
#include
#include
#define test_data_length 100000 //
每個執行緒操作次數
#define thread_num 10 //
執行緒個數
using
namespace std;//
引入std命名空間
mutex m;
//宣告互斥鎖m
long n_total = 0
;long m_total = 0
;atomic
a_total = 0;//
原子量的初始化
//在不採用互斥鎖和原子類的情況下
void
test_f_normal()}//
使用mutex互斥鎖
void
test_f_mutex()}//
使用原子操作
void
test_f_atomic()
}void
main()
for(int i = 0; i < thread_num; i++)
clock_t end =clock();
cout
<< "
total:
"<< n_total
<< "
test_f_normal:
"<< end - start /use mutex ,
clock_t mstart =clock();
for(int i = 0; i < thread_num; i++)
for(int i = 0; i < thread_num; i++)
clock_t mend =clock();
cout
<< "
total:
"<< m_total
<< "
test_f_mutex:
"<< mend - mstart /use atomic
clock_t astart =clock();
for(int i = 0; i < thread_num; i++)
for(int i = 0; i < thread_num; i++)
clock_t aend =clock();
cout
<< "
total:
"<< a_total
<< "
test_f_atomic:
"<< aend - astart
"pause");
return
;}
total: 601409test_f_normal:
29total:
1000000
test_f_mutex:
11274
total:
1000000
test_f_atomic:
35
由上面的測試結果可以看得出來
1.在不使用互斥鎖和原子量的時候,多執行緒的操作會使結果是錯誤的.
2.原子操作的實現跟普通資料型別類似,但是它能夠在保證結果正確的前提下,提供比mutex等鎖機制更好的效能
Golang 原子操作與互斥鎖
先來看乙個 package main import fmt runtime sync var counter int32 wg sync.waitgroup func main func addcounter whoami string final counter is 2 首先這個程式是起了兩個 ...
C 互斥量 原子鎖 自旋鎖等比較
現象 1 單執行緒無鎖速度最快,但應用場合受限 2 多執行緒無鎖速度第二快,但結果不對,未保護臨界 段 3 多執行緒原子鎖第三快,且結果正確 4 多執行緒互斥量較慢,慢與原子鎖近10倍,結果正確 5 多執行緒自旋鎖最慢,慢與原子鎖30倍,結果正確。結論 原子鎖速度最快,互斥量和自旋鎖都用保護多執行緒...
互斥體 原子操作 自旋鎖 訊號量
一 互斥體 struct mutex my mutex 定義mutex mutex init my mutex 初始化mutex mutex lock my mutex 獲取mutex 臨界資源 mutex unlock my mutex 釋放mutex 二 原子操作 1 定義 原子操作指的是在執行...