std::atomic和std::mutex区别
std::atomic介绍
模板类std::atomic是C++11提供的原子操作类型,头文件 #include<atomic>。在多线程调用下,利用std::atomic可实现数据结构的无锁设计。
和互斥量的不同之处在于,std::atomic原子操作,主要是保护一个变量,互斥量的保护范围更大,可以一段代码或一个变量。std::atomic确保任意时刻只有一个线程对这个资源进行访问,避免了锁的使用,提高了效率。
原子类型和内置类型对照表如下:
以下以两个简单的例子,比较std::mutex和std::atomic执行效率
atomic和mutex性能比较
使用std::mutex
#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;
}
执行结果:
使用std::atomic
#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 能大大的提高程序的运行效率。
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2021-05-18 公网可用的RTMP、RTSP测试地址(更新于2021年3月)
2021-05-18 rtmp/rtsp/hls公网真正可用的测试地址
2021-05-18 Windows平台RTMP|RTSP播放器实现画面全屏功能
2021-05-18 Windows平台RTMP|RTSP播放器为什么要兼容GDI绘制
2021-05-18 Windows平台RTMP推送|轻量级RTSP服务实现本地摄像头|屏幕|叠加数据预览
2021-05-18 Android对接实现内网无纸化会议|智慧教室|实时同屏功能
2021-05-18 QT实现低延迟的RTSP、RTMP播放器