对于简单任务,自旋锁应具有比互斥锁更好的性能。然而,在这种简单的测试(8个线程递增计数器)区,结果表明是不同的:C++:自旋锁或互斥对比(简单计算)
#include <iostream>
#include <thread>
#include <mutex>
#include <atomic>
#include <vector>
using namespace std;
class SpinLock {
private:
atomic_flag lck = ATOMIC_FLAG_INIT;
public:
void lock() { while(lck.test_and_set(memory_order_acquire)) {} }
void unlock() { lck.clear(memory_order_release); }
};
int total = 0;
#ifdef SPINLOCK
SpinLock my_lock;
#else
mutex my_lock;
#endif
void foo(int n)
{
for(int i = 0; i < 10000000; ++i) {
#ifdef SPINLOCK
lock_guard<SpinLock> lck(my_lock);
#else
lock_guard<mutex> lck(my_lock);
#endif
++total;
}
}
int main()
{
vector<thread> v;
for(int i = 0; i < 8; ++i)
v.emplace_back(foo, i);
for(auto& t : v)
t.join();
cout << "total: " << total << endl;
return 0;
}
要测试自旋锁:
$ g++ -DSPINLOCK -std=c++11 -Wall -pthread test.cc
$ time ./a.out
total: 80000000
real 0m18.206s
user 2m17.792s
sys 0m0.003s
要测试互斥:
$ g++ -std=c++11 -Wall -pthread test.cc
$ time ./a.out
total: 80000000
real 0m9.483s
user 0m6.451s
sys 1m6.043s
的结果显示互斥锁比自旋锁快近两倍。自旋锁在“用户cpu”中花费最多的时间,互斥锁花费大部分时间在“sys cpu”中。互斥体是如何实现的,我应该在这种简单的计算中使用互斥锁而不是自旋锁吗?任何人都可以解释结果吗?
g ++是4.8.2,操作系统是红帽企业Linux 7.
谢谢。
感谢您的解释。 – user2847598 2015-04-05 14:00:56