原子操作,就是多线程程序中“最小的且不可并行化的”操作。通常对一个共享资源的操作是原子操作的话,意味着多个线程访问该资源时,有且仅有唯一一个线程在对这个资源进行操作。
C++11中支持的原子类型有
常用的可以使用atomic类模板,通过类模板,可以任意定义出需要的原子类型
std::atomic<T> t;
//C++11
atomic_int total{0};
void func()
{
for (int i = 0; i < 100000; i++)
{
total += i;
}
}
int main()
{
thread th1(func);
thread th2(func);
th1.join();
th2.join();
cout<<"total:"<<total<<endl;
return 0;
}