原子操作,一般都是指“不可分割的操作”,也就是说这种操作状态要么是完成的,要么是没完成的,不可能出现半完成状态;
std::atomic代表原子操作,是一个类模板,其实这个东西用来封装某个类型的值的。
注意和互斥量的区分,互斥量的加锁一般都是针对一个代码段(几行代码),而原子操作针对的一般都是一个变量,而不是一个代码段,是无锁的。
下面看一个简单的例子,就是共同写一个数字,然后最后访问。
int ncount = 0;
std::mutex mutex1;
void testx()
{
clock_t t1 = clock();
for (int i = 0; i < 10000000;i++)
{
mutex1.lock();
ncount++;
mutex1.unlock();
}
clock_t t2 = clock();
double totaltime = (t2 - t1)*1.0 / CLOCKS_PER_SEC;
cout << "执行时间:" << totaltime << "秒\n";
}
void main()
{
std::thread t(testx);
std::thread t1(testx);
t.join();
t1.join();
cout << "ncount:" << ncount << endl;
system("pause");
}
结果:
接下来看看原子操作:
std::atomic<int> ncount = 0;
void testx()
{
clock_t t1 = clock();
for (int i = 0; i < 10000000;i++)
{
ncount++;
}
clock_t t2 = clock();
double totaltime = (t2 - t1)*1.0 / CLOCKS_PER_SEC;
cout << "执行时间:" << totaltime << "秒\n";
}
void main()
{
std::thread t(testx);
std::thread t1(testx);
t.join();
t1.join();
cout << "ncount:" << ncount << endl;
system("pause");
}
结果:
从运行结果可以看出原子操作确实大大提高了效率。
如果本文对你有所帮助,可以微信扫码支持一下!