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

posted @   音视频牛哥  阅读(158)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-03-12 Windows平台Unity3d播放多路RTMP或RTSP流
点击右上角即可分享
微信分享提示