Differences

This shows you the differences between two versions of the page.

Link to this comparison view

blog:2019:0104_spinlock_implementation [2019/01/04 10:29] (current)
Line 1: Line 1:
 +====== SpinLock implementation in C++ ======
  
 +{{tag>​cpp dev}}
 +
 +Since I read the book **Game Engine Architecture** I was looking for a way to implement a simple **SpinLock** in C++. And actually it turns out this is (almost) readily available from boost.
 +
 +====== ======
 +
 +I used the following reference pages:
 +
 +  * [[https://​jiafei427.wordpress.com/​2016/​08/​24/​spinlock-v-s-mutex-v-s-atomics/​|This page clearly shows that you don't want to use mutexes in many situations]].
 +  * [[https://​www.boost.org/​doc/​libs/​1_54_0/​doc/​html/​atomic/​usage_examples.html#​boost_atomic.usage_examples.example_spinlock|The official boost spinlock implementation template]]
 +  * [[https://​stackoverflow.com/​questions/​19742993/​implementing-a-spinlock-in-boost-example-needed|The source I used for my own implementation]].
 +
 +
 +And in the end, if will fit in a single simple header file: <sxh cpp>#​ifndef NV_SPINLOCK_H_
 +#define NV_SPINLOCK_H_
 +
 +#include <​boost/​atomic.hpp>​
 +#include <​boost/​thread.hpp>​
 +
 +namespace nv {
 +
 +class SpinLock
 +{
 +    boost::​atomic_flag flag; // it differs from std::​atomic_flag a bit -
 +                             // does not require ATOMIC_FLAG_INIT
 +public:
 +    void lock()
 +    {
 +        while( flag.test_and_set(boost::​memory_order_acquire) )
 +            ;
 +    }
 +    bool try_lock()
 +    {
 +        return !flag.test_and_set(boost::​memory_order_acquire);​
 +    }
 +    void unlock()
 +    {
 +        flag.clear(boost::​memory_order_release);​
 +    }
 +};
 +
 +typedef boost::​lock_guard<​SpinLock>​ SpinLockGuard;​
 +
 +};
 +
 +#​endif</​sxh>​