C++原子操作和互斥锁性能(速度)对比
创始人
2024-03-01 21:34:37
0

先说结论:原子操作性能(速度)强于互斥锁,下面用例子进行说明。

 编写测试demo,开启两个线程,对全局变量n分别进行自增、自减操作,计算执行时间。

首先看没有用任何手段进行互斥的情况,用文章《C++计算打印函数和代码块的执行时间(支持所有类型函数)》中的方法进行时间测量:

#include 
#include 
#include 
#include 
#include 
#include 
#include using namespace std;
#define TOTAL 100000000
int n = 0;template
auto measure(T&& func, Args&&... args)->std::future::type>
{using return_type = typename std::result_of::type;auto task = std::make_shared>(std::bind(std::forward(func), std::forward(args)...));std::future res = task->get_future();auto begin = std::chrono::high_resolution_clock::now();(*task)();auto end = std::chrono::high_resolution_clock::now();auto elapsed = std::chrono::duration_cast(end - begin);printf("执行时间: % .3f seconds.\n", elapsed.count() * 1e-9);return res;
}void funPlus()
{for (int i = 0; i < TOTAL; i++){n++;}
}void funMinus()
{for (int i = 0; i < TOTAL; i++){n--;}
}int main()
{measure([] {thread a(funPlus);thread b(funMinus);a.join();b.join();});cout << "执行结束,n的值为: " << n << endl;return 0;
}

运行结果如下:

执行时间是0.541秒,是耗时最短的,但是由于没有用互斥方法保护,所以临界资源n的值不正确(正确的值应该为0)。这是因为自增、自减操作不是原子的,编译得到的汇编指令可能会对应多条指令。所以我们得要对n这个临界资源进行互斥保护。

我们来看下使用原子操作std::atomic

#include 
#include 
#include 
#include 
#include 
#include 
#include using namespace std;
#define TOTAL 100000000
atomic n(0);template
auto measure(T&& func, Args&&... args)->std::future::type>
{using return_type = typename std::result_of::type;auto task = std::make_shared>(std::bind(std::forward(func), std::forward(args)...));std::future res = task->get_future();auto begin = std::chrono::high_resolution_clock::now();(*task)();auto end = std::chrono::high_resolution_clock::now();auto elapsed = std::chrono::duration_cast(end - begin);printf("执行时间: % .3f seconds.\n", elapsed.count() * 1e-9);return res;
}void funPlus()
{for (int i = 0; i < TOTAL; i++){n++;}
}void funMinus()
{for (int i = 0; i < TOTAL; i++){n--;}
}int main()
{measure([] {thread a(funPlus);thread b(funMinus);a.join();b.join();});cout << "执行结束,n的值为: " << n << endl;return 0;
}

执行效果如下:

 可以看到耗时为:5.261秒,n的值为0。也就是说耗时变长了,但是临界资源n的值可以保证 一定正确。

我们再来看使用互斥锁的情况:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include using namespace std;
#define TOTAL 100000000
std::mutex g_mutex;
int n = 0;template
auto measure(T&& func, Args&&... args)->std::future::type>
{using return_type = typename std::result_of::type;auto task = std::make_shared>(std::bind(std::forward(func), std::forward(args)...));std::future res = task->get_future();auto begin = std::chrono::high_resolution_clock::now();(*task)();auto end = std::chrono::high_resolution_clock::now();auto elapsed = std::chrono::duration_cast(end - begin);printf("执行时间: % .3f seconds.\n", elapsed.count() * 1e-9);return res;
}void funPlus()
{for (int i = 0; i < TOTAL; i++){std::lock_guard lock(g_mutex);n++;}
}void funMinus()
{for (int i = 0; i < TOTAL; i++){std::lock_guard lock(g_mutex);n--;}
}int main()
{measure([] {thread a(funPlus);thread b(funMinus);a.join();b.join();});cout << "执行结束,n的值为: " << n << endl;return 0;
}

运行效果如下:

可以看到执行时间为27.762秒。执行时间最长,但也能保持临界资源n的值正确。

所以对于基本类型的临界资源,我们进行访问时可以用原子操作代替互斥锁,来提高性能。

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
有效的括号 一、题目 给定一个只包括 '(',')','{','}'...
【Ctfer训练计划】——(三... 作者名:Demo不是emo  主页面链接:主页传送门 创作初心ÿ...