atomic

std::atomic是一个模板类,模板参数为数据类型。atomic对象的一个重要特性就是多线程同时读写该变量时不会产生竞争条件,任意时刻只有一个线程对这个资源进行访问。

#include <thread>
#include <vector>
#include <iostream>

using namespace std;

int n;
atomic<int> atomic_n;

void adder1()
{
	for (int i = 0; i < 10000; i++)
	{
		n++;
	}
}

void adder2()
{
	for (int i = 0; i < 10000; i++)
	{
		atomic_n++;
	}
}

int main()
{
	n = atomic_n = 0;
	vector<thread*> threadVec;
	for (int i = 0; i < 100; i++)
	{
		thread* t = new thread(adder1);
		threadVec.push_back(t);
	}
	for (int i = 0; i < 100; i++)
	{
		thread* t = new thread(adder2);
		threadVec.push_back(t);
	}
	for (auto iter = threadVec.begin(); iter != threadVec.end(); iter++)
	{
		(*iter)->join();
	}
	cout << n<<endl;
	cout << atomic_n<<endl;
}

输出:

711123
1000000

可以看到如果不是atomic类型且没有加锁的情况下,多个线程同时读写同一个变量会出现竞争条件,导致最终值不等于1000000