[cpp] cpp11--原子操作

经常用到的场景: ++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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值