Skip to content

Instantly share code, notes, and snippets.

@carlchen0928
Created June 29, 2015 02:52
Show Gist options
  • Save carlchen0928/98329a39eda655a27fbe to your computer and use it in GitHub Desktop.
Save carlchen0928/98329a39eda655a27fbe to your computer and use it in GitHub Desktop.
c++ spinlock && test with mutex
#include <atomic>
/*
*
* spin lock implemented by C++ std::atomic
*
*/
class spinlock_mutex
{
public:
spinlock_mutex() : _lock(ATOMIC_FLAG_INIT)
{}
void lock()
{
while (_lock.test_and_set(std::memory_order_acquire));
}
void unlock()
{
_lock.clear(std::memory_order_release);
}
private:
std::atomic_flag _lock;
};
#include "spinlock_mutex.cpp"
#include <mutex>
#include <thread>
#include <vector>
/*
* spinlock: g++ spinlock_test.cpp -o spinlock_test -DSPIN -DLOOP=1000000 -DTHREAD_NUM=8 -std=c++11
* mutex: g++ spinlock_test.cpp -o spinlock_test -DLOOP=1000000 -DTHREAD_NUM=8 -std=c++11
*/
using namespace std;
int num = 0;
#ifdef SPIN
spinlock_mutex _lock;
#else
mutex _lock;
#endif
void func()
{
for (int i = 0; i < LOOP; i++)
{
#ifdef SPIN
lock_guard<spinlock_mutex> lg(_lock);
#else
lock_guard<mutex> lg(_lock);
#endif
++ num;
}
}
int main()
{
thread ths[THREAD_NUM];
for (int i = 0; i < THREAD_NUM; i++)
ths[i] = thread(func);
for (int i = 0; i < THREAD_NUM; i++)
ths[i].join();
}
@carlchen0928
Copy link
Author

Performance test between SpinLock and Mutex

  • hardware_concurrency threads (8 in my macbook pro), every thread do 1000000 times operations.
spin_lock
real    0m4.113s
user    0m29.517s
sys     0m0.100s
mutex
real    0m40.848s
user    0m4.036s
sys     0m38.737s
  • double hardware_concurrency threads, every thread do 1000000 times operations.
spin_lock
real    0m12.667s
user    1m35.209s
sys     0m0.253s
mutex
real    1m46.668s
user    0m10.306s
sys     1m41.601s

Conclusion

When threads number same as core number, spin lock have very high performance than mutex. But when threads more than core number, spin lock takes more time in user space to busy loop. More threads number, more context switching when use mutex.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment