1008.C++并发编程-atomic模板
C/C++ 2023年4月13日
1. 每个 std::atomic 模板的实例化和全特化定义一个原子类型。如果一个线程写入原子对象,同时另一线程从它读取,那么行为定义明确:
#include <iostream>
#include <thread>
#include <time.h>
#include <atomic>
using namespace std;
atomic_long cnt;
void counter()
{
for(int i=0; i<100000; i++)
{
cnt++;
}
}
int main()
{
clock_t start = clock();
thread threads[100];
for(int i=0; i<100; i++)
{
threads[i] = thread(counter);
}
for(auto &th: threads)
th.join();
clock_t finish = clock();
cout << "Wanted = " << 100*100000 << endl;
cout << "Real = " << cnt << endl;
cout << "Duration: " << finish-start << "ms" << endl;
return 0;
}