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;
对应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保证原子性操作的同时,耗时也较低
版权声明:本文为qq_24447809原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。