经常用到的场景: ++x变成原子的, flag变成原子的, 算是一个更加方便的东西, 因为我们的锁用起来比较麻烦, 而这个算是一个小型的"锁"??? 差不多可以这样理解吧.
atomic
是一个模板类.
支持了整形, 允许++, --, &, 异或等操作. 它支持下面这些类型.
他还提前弄了一些类: atomic_flag
类.
其底层本质用的是硬件提供的一些原子性操作(comper and set).
具体怎么用呢? 我们来看下面这个示例:
#include <iostream>
#include <mutex>
#include <thread>
#include <atomic>
using namespace std;
// 需求: 假设我们依然是要求两个线程++一个公共变量x
int main()
{
mutex mtx;
atomic<int> x(0);
// atomic<int> x = { 0 };
// atomic<int> x { 0 };
thread th1([&](int n) {
{
// lock_guard<mutex> lock(mtx);
for (int i = 0; i < n; i++)
{
++x;
}
}
// 不想加锁的code:
int a = 10;
int b = 20;
int c = 30;
}, 100000);
thread th2([&](int n) {
{
// lock_guard<mutex> lock(mtx);
for (int i = 0; i < n; i++)
{
++x;
}
}
// 不想加锁的code:
int a = 10;
int b = 20;
int c = 30;
}, 300000);
th1.join();
th2.join();
cout << "x : " << x << endl;
return 0;
}
之前的时候, 想要保证++x是安全的, 我们之前是不是加了一个锁? 但是那玩意用起来比较麻烦, 现在我们把锁去掉, 用一个原子操作即可.
里面还有个load()
的接口, 用来获取值, 因为我们用atomic
对int进行封装了嘛, 所以说想要取到里面的值需要用到load()
接口.
具体他的底层细节, 推荐看左耳朵耗子的博客. 链接是: 酷壳 – CoolShell.cn