std::atomic和std::mutex区别


?

?std::atomic介绍?

?模板类std::atomic是C++11提供的原子操作类型,头文件 #include。?在多线程调用下,利用std::atomic可实现数据结构的无锁设计。??

?和互斥量的不同之处在于,std::atomic原子操作,主要是保护一个变量,互斥量的保护范围更大,可以一段代码或一个变量。std::atomic?确保任意时刻只有一个线程对这个资源进行访问,避免了锁的使用,提高了效率。??

??原子类型和内置类型对照表如下:??

?

以下以两个简单的例子,比较std::mutex和std::atomic执行效率

atomic和mutex性能比较

使用std::mutex

#include "stdafx.h"

#include 
#include 
#include 
#include 
#include

std::mutex mtx;

int cnt = 0; 

void mythread()
{
  for (int i = 0; i < 1000000; i++)
  {
    std::unique_lock 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 
#include 
#include 
#include

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

?