GreensnoWorld
记录点滴,分享乐趣,一块凝固的时间
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;
}

 

LIJG
余本顽劣,生于紫云下,长于汝水滨。早年求学,兴趣广泛,好高骛远,学无所成,仓皇入世。兴趣所致,投身互联网,求知未证,而立已至,始悟光阴荏苒,终需务实钻研。故有此站,记录时光,积累点滴,验证所学,分享愚见。指舞方寸间,心系万千年。
留言