std::atomic是 C++11 标准库提供的一个模板类,用于实现原子操作。原子操作是指不会被线程调度机制打断的操作,即这种操作一旦开始,就一直运行到结束,中间不会有任何线程切换。在多线程编程中,原子操作对于确保数据的一致性和避免数据竞争至关重要。
实际上,使用编译器编译的简单语句,即使仅为简单的输入输出,也是分步执行的,都不是原子操作。因此针对同一对象的访问就有可能产生不可预料的问题。在单线程的程序中,标准库提供的操作通常已经解决了这些问题。但在多线程环境中,如果多个线程同时访问共享数据依然要考虑这类问题。一般的,可以使用互斥量就可以解决这个隐患。但是,这个方法往往很影响执行的效率。因此,针对一些仅对单个变量的共享数据的访问,可以考虑使用原子操作来实现多线程安全的同时提高效率。
#include<iostream>
#include<thread>
#include<future>//使用原子操作要
using namespace std;int a = 0;//std::atmoic<int> a=0;原子操作void mythread()
{for (int i = 0; i < 10000; i++){a++;}
}
int main()
{thread myth(mythread);thread myth2(mythread);myth.join();myth2.join();cout << a << endl;//输出结果往往是10000到20000中间的某个值。}
#include<iostream>
#include<thread>
#include<future>
using namespace std;std::atomic<bool> myend = false;void mythread()
{std::chrono::milliseconds dura(1000);while (myend == false){cout <<this_thread::get_id()<< "正在执行" << endl;std::this_thread::sleep_for(dura);}cout <<this_thread::get_id()<< "执行结束" << endl;return;
}
int main()
{thread myth(mythread);thread myth2(mythread);std::chrono::milliseconds dura(5000);std::this_thread::sleep_for(dura);myend = true;myth.join();myth2.join();}