原子操作-atomic

一、原子操作简介

  所谓的原子操作,取的就是“原子是最小的、不可分割的最小个体”的意义,它表示在多个线程访问同一个全局资源的时候,能够确保所有其他的线程都不在同一时间内访问相同的资源。也就是他确保了在同一时刻只有唯一的线程对这个资源进行访问。这有点类似互斥对象对共享资源的访问的保护,但是原子操作更加接近底层,因而效率更高。原子操作不需要加锁

  原子类型对象的主要特点就是从不同线程访问不会导致数据竞争(data race)。因此从不同线程访问某个原子对象是良性 (well-defined) 行为,而通常对于非原子类型而言,并发访问某个对象(如果不做任何同步操作)会导致未定义 (undifined) 行为发生。

二、demo

#include <iostream>
#include <thread>
#include <atomic> 
#include <ctime>
using namespace std;

atomic<int> cnt(0);

void fun()
{
    for (int i = 0; i < 100000; ++i)
    {
        ++cnt;
    }
}

int main()
{
    clock_t start_time = clock();

    thread threads[100];
    for (int i = 0; i != 100; ++i)
    {
        threads[i] = thread(fun);
    }
    for (auto &th : threads)
        th.join();

    clock_t end_time = clock();
    cout << "Running time is: " << static_cast<double>(end_time-start_time)/CLOCKS_PER_SEC*1000 <<
         "ms" << endl;
    system("pause");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/daaikuaichuan/article/details/81173586