//--------------------------------------------------------- // spinlock.h: spinlock based switch //--------------------------------------------------------- #include // std::atomic_flag #include // std::mutex //--------------------------------------------------------- class spinlock_switch { public: void lock(std::mutex &key) { while (spinlock.test() || spinlock.test_and_set()) ; if (++counter == 1) key.lock(); spinlock.clear(); } void unlock(std::mutex &key) { while (spinlock.test() || spinlock.test_and_set()) ; if (--counter == 0) key.unlock(); spinlock.clear(); } protected: std::atomic_flag spinlock; size_t counter = 0; }; //----------------------------------------------- class spinlock_lock { public: spinlock_lock(std::size_t) {} void reader_lock() { sw.lock(mutex); } void reader_unlock() { sw.unlock(mutex); } void writer_lock() { mutex.lock(); } void writer_unlock() { mutex.unlock(); } private: std::mutex mutex; // writers mutex spinlock_switch sw; // protects readers from writers }; //---------------------------------------------------------