c++多线程(十六) - std::atomic

    多线程中,必须确保在同一时刻只有一个线程对共享资源进行访问。可以使用互斥量(mutex)或原子操作(atomic)实现。

1.互斥量(mutex)

#include<iostream>
#include<mutex>
using namespace std;
int g_count = 0;    //全局变量
mutex g_mutex;      //互斥量
void myThread()
{
	for (int i = 0; i < 1000000; i++)
	{
		g_mutex.lock();
		g_count++;
		g_mutex.unlock();
	}
}

int main()
{
	thread t1(myThread);
	thread t2(myThread);
	t1.join();
	t2.join();
	cout << "g_count = " << g_count << endl;
	return 0;
}

2.原子操作(atomic)

#include<iostream>
#include<mutex>
#include <atomic>
using namespace std;
atomic<int> g_count = 0;    //全局变量
void myThread()
{
	for (int i = 0; i < 1000000; i++)
	{
		g_count++;
	}
}

int main()
{
	thread t1(myThread);
	thread t2(myThread);
	t1.join();
	t2.join();
	cout << "g_count = " << g_count << endl;
	return 0;
}

3.效率比较

    用clock_t统计程序的执行时间。

#include<iostream>
#include<mutex>
#include <atomic>
#include<time.h>
using namespace std;
int main()
{
	clock_t start, finish;
	start = clock();
	thread t1(myThread);
	thread t2(myThread);
	t1.join();
	t2.join();
	cout << "g_count = " << g_count << endl;
	finish = clock();
	cout << "运行时间:" << (double)(finish - start)/CLOCKS_PER_SEC << "秒!" << endl;
	return 0;
}

    统计结果:

循环次数执行时间/s(mutex)执行时间/s(atomic)
1000000.0330.026
10000000.2680.116
100000002.4770.851

4.总结

    原子操作(atomic)比互斥量(mutex)加锁效率高。

    原子操作(atomic)只能针对一个变量加锁,而互斥量(mutex)可以对代码段加锁。

    原子操作(atomic)支持的运算符有:++ , -- , += , -= , &=, |= , ^= 。

   原子操作(atomic)不支持拷贝构造函数和赋值运算符,可以分别用load()和store()以原子方式读取和写入。

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值