??WARNING??
注意:
试验平台是CentOS7,x86_64,Intel Xeon CPU
不同平台原理大不相同!
[mzhai@include]$ lscpu
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
CPU(s): 1
On-line CPU(s) list: 0
Thread(s) per core: 1
Core(s) per socket: 1
Socket(s): 1
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 85
Model name: Intel? Xeon? Gold 6242R CPU @ 3.10GHz
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
std::atomic_int acnt;
int cnt;
void f()
{
for (int n = 0; n < 10000; ++n)
{
++acnt;
++cnt;
// Note: for this example, relaxed memory order
// is sufficient, e.g. acnt.fetch_add(1, std::memory_order_relaxed);
}
}
void g(){
acnt.fetch_add(1,std::memory_order_relaxed);
acnt.fetch_add(1,std::memory_order_consume);
acnt.fetch_add(1,std::memory_order_acquire);
acnt.fetch_add(1,std::memory_order_release);
acnt.fetch_add(1,std::memory_order_acq_rel);
}
int main()
{
std::vector<std::thread> pool;
for (int n = 0; n < 10; ++n)
pool.emplace_back(f);
for(auto&& t:pool){
t.join();
}
std::cout << "The atomic counter is " << acnt << '\n'
<< "The non-atomic counter is " << cnt << '\n';
g();
}
先看atomic++操作:
再看fetch_add:
很明显所有加法操作,++,fetch_add, 不论用什么memory order底层都是用lock xadd指令实现的。
over