之前有人提及在linux下std::mutex性能没有atomic_flag快,大概差了一倍;
我今天在我的windows10以及vs2017上测试了一下,
1)在使用lock_guard情况下,多线程同步测试结果是一样;
2)在std::atomic<int>单纯无锁计算累计数据时候明显要快;
有其他网友分析windows vista以上版本mutex是使用的SRWLOCK,而不再是互斥段。
参考:https://blog.csdn.net/jiangdong2007/article/details/89513476
代码如下:
// 自旋锁的实现
class spin_lock {
public:
spin_lock() = default;
spin_lock(const spin_lock&) = delete;
spin_lock& operator=(const spin_lock) = delete;
void lock() { // acquire spin lock
while (flag.test_and_set()) {}
}
void unlock() { // release spin lock
flag.clear();
}
private:
atomic_flag flag;
};
spin_lock splock;
std::mutex myMutex;
int num = 0;
std::atomic<int> count1(0);
void addFunc1()
{
for (int i = 0; i < 1000000; ++i)
{
//std::lock_guard<spin_lock> lock(splock); // 就是这里不一样!!!
//num++;
count1 ++;
}
}
void addFunc2()
{
for (int i = 0; i < 1000000; ++i)
{
std::lock_guard<std::mutex> lock(myMutex); // 就是这里不一样!!!
num++;
}
}
int main() {
Timer timer1;
timer1.start();
thread t1(addFunc1);
thread t2(addFunc1);
thread t3(addFunc1);
t1.join();
t2.join();
t3.join();
auto duration2 = timer1.stop_delta<std::milli>();
std::cout << "耗时(ms): " << duration2 << endl;
std::cout << count1 << endl;
return 0;
}