samedi 4 avril 2015

c++: spin lock or mutex comparison (simple calculations)

Spin lock should have better performance than mutex for simple tasks. However, in this simple test (8 threads incrementing a counter), the results shows differently:



#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;
}


To test spin lock:



$ g++ -DSPINLOCK -std=c++11 -Wall -pthread test.cc
$ time ./a.out
total: 80000000
real 0m18.206s
user 2m17.792s
sys 0m0.003s


To test mutex:



$ g++ -std=c++11 -Wall -pthread test.cc
$ time ./a.out
total: 80000000
real 0m9.483s
user 0m6.451s
sys 1m6.043s


The results show the mutex is almost two times faster than the spin lock. The spin lock spends most time in "user cpu" and the mutex spends most time in "sys cpu". How is the mutex implemented and should I use mutex instead of spin lock in the simple calculations like this? Can anyone explain the results?


The g++ is 4.8.2 and OS is Red Hat Enterprise Linux 7.


Thanks.


Aucun commentaire:

Enregistrer un commentaire