I have a class instance that is used by several other classes in other threads to communicate.
This class uses a slim reader/writer lock (WinAPI’s SRWLOCK) as a synchronization object and a couple of RAII helper classes to actually lock/unlock the thing:
static unsigned int readCounter = 0;
class CReadLock
{
public:
CReadLock(SRWLOCK& Lock) : m_Lock(Lock) { InterlockedIncrement(&readCounter); AcquireSRWLockShared(&m_Lock); }
~CReadLock() {ReleaseSRWLockShared(m_Lock); InterlockedDecrement(&readCounter);}
private:
SRWLOCK& m_Lock;
};
class CWriteLock
{
public:
CWriteLock(SRWLOCK& Lock) : m_Lock(Lock) { AcquireSRWLockExclusive(&m_Lock); }
~CWriteLock() { ReleaseSRWLockExclusive(&m_Lock); }
private:
SRWLOCK& m_Lock;
};
The problem is the whole thing deadlocks all the time. When I pause the deadlocked program, I see:
- one thread stuck in
AcquireSRWLockExclusive(); - two threads stuck in
AcquireSRWLockShared(); readCounterglobal is set to 3.
The way I see it, the only way for this to happen is CReadLock instance’s destructor hasn’t been called somehow somewhere so the lock is perpetually stuck. However, the only way for this to happen (as far as I know) is because an exception has been thrown. It wasn’t. I checked.
What might be the problem? How should I go about fixing (or at least locating the reason of) this thing?
Are you using Read lock in recursive manner?
if
foo()andbaz()are called simultaneously you may get deadlock:The fact that you have 2 threads stuck on Read lock and Read Lock counter is 3 that most likely shows that you have a recursion in one of the locks – i.e. one thread had tried to acquired read lock twice.