模板类std::atomic是C++11提供的原子操作类型,头文件 #include<atomic>。在多线程调用下,利用std::atomic可实现数据结构的无锁设计。
和互斥量的不同之处在于,std::atomic原子操作,主要是保护一个变量,互斥量的保护范围更大,可以一段代码或一个变量。std::atomic确保任意时刻只有一个线程对这个资源进行访问,避免了锁的使用,提高了效率。
原子类型和内置类型对照表如下:
以下以两个简单的例子,比较std::mutex和std::atomic执行效率
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <mutex>
#include <thread>
#include<future>
std::mutex mtx;
int cnt = 0;
void mythread()
{
for (int i = 0; i < 1000000; i++)
{
std::unique_lock<std::mutex> lock(mtx);
cnt++;
}
}
int main()
{
clock_t start_time = clock();
std::thread t1(mythread);
std::thread t2(mythread);
t1.join();
t2.join();
clock_t cost_time = clock() - start_time;
std::cout << "cnt= " << cnt << " 耗时:" << cost_time << "ms" << std::endl;
return 0;
}
执行结果:
#include <iostream>
#include <ctime>
#include <thread>
#include<future>
std::atomic<int> cnt(0);
void mythread()
{
for (int i = 0; i < 1000000; i++)
{
cnt++;
}
}
int main()
{
clock_t start_time = clock();
std::thread t1(mythread);
std::thread t2(mythread);
t1.join();
t2.join();
clock_t cost_time = clock() - start_time;
std::cout << "cnt= " << cnt << " 耗时:" << cost_time << "ms" << std::endl;
return 0;
}
执行结果如下:
通过以上比较,可以看出来,使用std::atomic,耗时比std::mutex低非常多,使用 std::atomic 能大大的提高程序的运行效率。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有