Simple read/write lock implementation without starvation I've built a read/write lock and have been testing it without encountering any problems. It was made to avoid writer starvation, but I believe it works against reader starvation as well. I've seen alternatives online, but was wondering if this is a solid implementation.
If you use a normal shared mutex, new read actions can still be queued, which will prevent write actions from ever being processed while there is any read action present. This will cause starvation. I used a second mutex which will be locked by the write process and prevents any new read processes to be queued. Thank you!
class unique_priority_mutex
{
public:

    void lock_shared(void)
    {
        // If there is a unique operation running, wait for it to finish.
        if( this-&gt;_is_blocked ){
            // Use a shared lock to let all shared actions through as soon as the unique action finishes.
            std::shared_lock&lt;std::shared_mutex&gt; l(this-&gt;_unique_mutex);
        }

        // Allow for multiple shared actions, but no unique actions.
        this-&gt;_shared_mutex.lock_shared();
    }

    void unlock_shared(void)
    {
        this-&gt;_shared_mutex.unlock_shared();
    }

    void lock(void)
    {
        // Avoid other unique actions and avoid new shared actions from being queued.
        this-&gt;_unique_mutex.lock();

        // Redirect shared actions to the unique lock.
        this-&gt;_is_blocked = true;

        // Perform the unique lock.
        this-&gt;_shared_mutex.lock();
    }

    void unlock(void)
    {
        this-&gt;_shared_mutex.unlock();
        this-&gt;_is_blocked = false;
        this-&gt;_unique_mutex.unlock();
    }

    std::shared_mutex _shared_mutex;
    std::shared_mutex _unique_mutex;
    std::atomic&lt;bool&gt; _is_blocked = false;
};
You'd need _shared_mutex and _is_blocked to flip together 'atomically' in order for this code to work, no?
Imaging one thread in lock() just flipped _unique_mutex and before it flips _is_blocked, another thread in lock_shared() is testing _is_blocked.