为了便于多线程编程,C++11引入了原子类型,可以保证对该类型变量的操作不会产生多线程的竞争:
#include <iostream>
#include <atomic>
#include <thread>
using namespace std;
atomic_int g_d{0};    //定义原子类型变量
void tFunc(int a)
{
	for(int i = 0; i < 100000000; ++i)
	{
		g_d++;        //对原子类型的操作,不会产生竞争
	}
}
int main(){
	thread t1(tFunc, 0);
	thread t2(tFunc, 0);
	t1.join();
	t2.join();
	cout<<g_d<<endl;
	return 0;
}
运行程序输出:
200000000









