Created
June 29, 2015 02:52
-
-
Save carlchen0928/98329a39eda655a27fbe to your computer and use it in GitHub Desktop.
c++ spinlock && test with mutex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Performance test between SpinLock and Mutex
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.