#include <iostream>
#include <thread>
#include <atomic>
/*原子操作(类模板),可以理解成所对应的汇编指令
已经是最小化了,不可分割,所以不用枷锁*/
std::atomic<int> foo(0);
void print_foo()
{
for (int i = 0; i < 1000000; i++)
{
/*不用枷锁,不用担心线程切换会产生错误*/
++foo;
}
}
int main()
{
std::cout << "foo: " << foo << std::endl;
std::thread print_th1(print_foo);
std::thread print_th2(print_foo);
print_th1.join();
print_th2.join();
std::cout << "foo: " << foo << std::endl;
return 0;
}
c++11原子操作atomic
最新推荐文章于 2022-12-12 21:55:30 发布