C++ 原子操作(atomic)

1、atomic概述
所谓原子操作,就是多线程程序中“最小的且不可并行化的”操作。对于在多个线程间共享的一个资源而言,这意味着同一时刻,多个线程中有且仅有一个线程在对这个资源进行操作,即互斥访问。

C++ 11 新增atomic可以实现原子操作

2、非原子操作
#include <thread>
#include <atomic>
#include <iostream>
using namespace std;

int i = 0;
const int maxCnt = 1000000;
void mythread()
{
    for (int j = 0; j < maxCnt; j++)
        i++;  //线程同时操作变量
}

int main()
{
    auto begin = chrono::high_resolution_clock::now();
    thread t1(mythread);
    thread t2(mythread);
    t1.join();
    t2.join();
    auto end = chrono::high_resolution_clock::now();
    cout << "i=" << i << endl;
    cout << "time: " << chrono::duration_cast<chrono::microseconds>(end - begin).count() * 1e-6 << "s" << endl; //秒计时
}
在这里插入图片描述
测试结果:发现结果并不是2000000,两个线程同时对共享资源操作会出问题

 


问题分析:以下是i++反汇编代码

在这里插入图片描述 

 

i++这一条程序在计算机中是分几个机器指令来执行的,先把i值赋值给eax寄存器,eax寄存器自加1,然后再把eax寄存器值赋值回i,如果在指令执行过程中发生了线程调度,那么这一套完整的i++指令操作被打断,会发生结果错乱。

举例子:

在这里插入图片描述
从图上可知,EAX寄存器进行了两次自加操作,但实际上i的值只加了1

 

3、加锁
#include <thread>
#include <atomic>
#include <iostream>
#include<mutex>
using namespace std;

int i = 0;
const int maxCnt = 1000000;
mutex mut;
void mythread()
{
    for (int j = 0; j < maxCnt; j++)
    {
        mut.lock();    //加锁操作
        i++;
        mut.unlock();
    }
}

int main()
{

    auto begin = chrono::high_resolution_clock::now();
    thread t1(mythread);
    thread t2(mythread);
    t1.join();
    t2.join();
    auto end = chrono::high_resolution_clock::now();
    cout << "i=" << i << endl;
    cout << "time: " << chrono::duration_cast<chrono::microseconds>(end - begin).count() * 1e-6 << "s" << endl; //秒计时
}


在这里插入图片描述
测试结果如图:虽然保证了结果正确,但耗时也增加了

 


4、atomic代码
使用方法:

atomic<int> i;
1
对应i++汇编代码如下:
发现调用的atomic类方法operator++,继续追踪。
只需关注红笔标注的代码,lock xadd 指令就是计算机硬件底层提供的原子性支持。

代码实现:

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

atomic<int> i;
//atomic_int32_t i;  两种写法
const int maxCnt = 1000000;
void mythread()
{
    for (int j = 0; j < maxCnt; j++)
    {
        i++;
    }
}

int main()
{

    auto begin = chrono::high_resolution_clock::now();
    thread t1(mythread);
    thread t2(mythread);
    t1.join();
    t2.join();
    auto end = chrono::high_resolution_clock::now();
    cout << "i=" << i << endl;
    cout << "time: " << chrono::duration_cast<chrono::microseconds>(end - begin).count() * 1e-6 << "s" << endl; //秒计时
}



测试结果如下:atomic保证原子性操作的同时,耗时也较低

在这里插入图片描述

 

————————————————
版权声明:本文为CSDN博主「Mr.禾」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_24447809/article/details/118179908

  • 10
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值