SpinLock implementation in C++


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:

And in the end, if will fit in a single simple header file:

#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
    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()

typedef boost::lock_guard<SpinLock> SpinLockGuard;