Skip to content

Optimization with reader/writer lock

When multiple threads (e.g. thread A and thread B, the “readers”) want to access some data for reading there is no problem if they do it at the same time in parallel. It is not necessary for thread A to wait until thread B has read the data. The only situation to synchronize is when another thread (the “writer”) wants to change the data.

While the writer thread changes the data, no other reader or writer thread can have access to data.
The writer thread itself has to wait until all reader threads or an other writer thread are ready with data access before he can get exclusive access.

class SomeClass
{
public:
    void WriteSomeData(const Data & in_data)
    { 
        // request exclusive access for writing data
        std::unique_lock writerLock(m_dataMutex);
        m_data = in_data;
    }

    Data ReadSomeData() const
    {
        // allows access to multiple threads for reading, but blocks if currently
        // one thread is writing
        std::shared_lock readerLock(m_dataMutex);
        return m_data;
    }
private:
    mutable std::shared_mutex m_dataMutex;
};