std::atomic<int>的原理

⚠️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 
#include 
#include 
#include 

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++操作:
std::atomic<int>的原理_第1张图片
再看fetch_add:
std::atomic<int>的原理_第2张图片
std::atomic<int>的原理_第3张图片

结论

很明显所有加法操作,++,fetch_add, 不论用什么memory order底层都是用lock xadd指令实现的。
over

你可能感兴趣的:(modern,C++,linux,atomic,modern,c++,atomic_int)