天天看點

c++ 原子操作

#include <atomic>

class Counter
{
public:
	Counter() : m_count(0) {}
	~Counter() {}
	void addcount() { m_count++; }
	int Getcount() const { return m_count; }

private:
	std::atomic<int> m_count;
};

template<class T>
VOID ReakWord(Counter &c, std::atomic<LONG64> &totalc, T &it, T &end)
{
	for (auto t = it;t != end;++t)
	{
	//	std::this_thread::sleep_for(std::chrono::milliseconds(11)); // 線程等1毫秒,與windows平台 下的 sleep 一樣
		totalc += *t;
		c.addcount();
	}
}


void testatomic()
{
	std::vector<int> vec;
	Counter c;
	std::atomic<LONG64> ntotal = 0;
	for (int i = 0; i < 10000000; i++)
	{
		vec.push_back(i);// 壓一百萬次
	}
	auto it = vec.begin();
	auto it2 = vec.begin() + vec.size() / 2;
	auto end = vec.end();
	auto tickcoutn = GetTickCount();
	std::thread d([&]() { ReakWord(c, ntotal, it, it2); }); // 構造匿名函數  [&] 意思是所有用的變量,均以引用方式傳過去,
	std::thread f([&]() { ReakWord(c, ntotal, it2, end); });
	d.join();// 等待線程結束
	f.join();
	std::cout << c.Getcount() << " " << ntotal <<  " 耗時:" << (GetTickCount() - tickcoutn) << std::endl;

}
           

 對于多個變量的原子操作,在多線程時,是不行的,必須 用臨界區

繼續閱讀