#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;
}
对于多个变量的原子操作,在多线程时,是不行的,必须 用临界区