1

I have a windows server application that uses multiple threads to handle requests. I needed a reader-writer lock to guard access to a shared std::unordered_map; and I wanted to do this in a manner similar to a std::unique_lock (resource acquisition is initialization). So I came up with this SRWRaii class.

class SRWRaii
{
public:
    SRWRaii(const SRWLOCK& lock, bool m_exclusive = false)
        :m_lock(lock), m_exclusive(m_exclusive) 
    {
        if (m_exclusive)
        {
            AcquireSRWLockExclusive(const_cast<SRWLOCK*>(&m_lock));
        }
        else
        {
            AcquireSRWLockShared(const_cast<SRWLOCK*>(&m_lock));
        }
    }

    ~SRWRaii()
    {
        if (m_exclusive)
        {
            ReleaseSRWLockExclusive(const_cast<SRWLOCK*>(&m_lock));
        }
        else
        {
            ReleaseSRWLockShared(const_cast<SRWLOCK*>(&m_lock));
        }
    }
private:
    const SRWLOCK& m_lock;
    bool m_exclusive;
};

Then I use this as follows

SRWLOCK g_mutex;
void Initialize()
{
    InitializeSRWLock(&g_mutex);
}

void Reader()
{
    SRWRaii lock(g_mutex);
    // Read from unordered_map
}

void Writer()
{
    SRWRaii lock(g_mutex, true); // exclusive
    // add or delete from unordered_map
}

Given my noviceness to c++, I am a little suspect of this critical code. Are there issues with the above approach of implementing an Raii wrapper over SRWLOCK? What improvements can be done to the above code?

tcb
  • 4,408
  • 5
  • 34
  • 51
  • 1
    I would create two different classes: one for read and one for write access. Using bool parameters here makes both performance and readability worse. You can make this stuff even better by using macros for the scoped lock as described here: http://stackoverflow.com/questions/22257600/scoped-mutex-lock/22257815#22257815 – pasztorpisti Oct 06 '14 at 15:46

0 Answers0