std::atomic和std::mutex区别

2022-10-15,,,

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 ​​能大大的提高程序的运行效率。​​

std::atomic和std::mutex区别的相关教程结束。

《std::atomic和std::mutex区别.doc》

下载本文的Word格式文档,以方便收藏与打印。