//--------------------------------------------------------- // switch.h: mutex based switch //--------------------------------------------------------- #include // std::size_t #include // std::mutex //--------------------------------------------------------- class mutex_switch { public: void lock(std::mutex &key) { std::unique_lock lock(mutex); if (++counter == 1) key.lock(); } void unlock(std::mutex &key) { std::unique_lock lock(mutex); if (--counter == 0) key.unlock(); } protected: std::mutex mutex; size_t counter = 0; }; //----------------------------------------------- class switch_lock { public: switch_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 mutex_switch sw; // protects readers from writers }; //---------------------------------------------------------