atomic操作
原子操作,就是多线程程序中“最小的且不可并行化的”操作。对于在多个线程间共享的一个资源而言,这意味着同一时刻,多个线程中有且仅有一个线程在对这个资源进行操作,即互斥访问。
C++ 11 新增atomic可以实现原子操作
#include<iostream>
#include<atomic>
#include<thread>
#include<string>
#include<mutex>
#include<pthread.h>
using namespace std;
//测试原子操作 ATOMIC 1
//测试多线程 ATOMIC 0
#define ATOMIC 1
#if ATOMIC
#endif
#if ATOMIC
atomic_int i = 0;
#else
int i = 0;
mutex mut_;
#endif
const int cnt_ = 1000000;
void mythread()
{
for (size_t j = 0; j < cnt_; j++)
{
#if ATOMIC
i++;
#else
mut_.lock(); //加锁操作
i++;
mut_.unlock();
#endif
}
}
int main(int argc, const char** argv){
auto begin = chrono::high_resolution_clock::now();
thread t1(mythread);
thread t2(mythread);
t1.join();
t2.join();
auto end = chrono::high_resolution_clock::now();
cout << "i=" << i << endl;
cout << "time: " << chrono::duration_cast<chrono::microseconds>(end - begin).count() * 1e-6 << "s" << endl; //秒计时
return 0;
}
编译记得加 -lpthread
g++ -std=c++17 atomic.cpp -o atomic -lpthread