rwlock.h
来自「一个管理ie的软件」· C头文件 代码 · 共 103 行
H
103 行
#ifndef __CRWLock_h__
#define __CRWLock_h__
#define EnterCriticalSectionTimeout(nTimeout) { \
if ( nTimeout > 0 ) \
{ \
for ( int i = 0; ! TryEnterCriticalSection(&m_csLock); i ++ ) \
{ \
Sleep(100); \
if ( i >= nTimeout * 10 ) \
return FALSE; \
} \
} \
else if ( nTimeout == 0 ) \
{ \
EnterCriticalSection(&m_csLock); \
} \
else \
{ \
if ( ! TryEnterCriticalSection(&m_csLock)) \
return FALSE; \
} \
}
////////////////////////////////////////////////////////////////////////////////
// simple R/W lock implementation
// this implementation is only reasonable if write locks are rare
class CRWLock
{
private:
CRITICAL_SECTION m_csLock;
long m_nReadLocks; // count of current read locks
public:
CRWLock()
{
m_nReadLocks = 0;
InitializeCriticalSection(&m_csLock);
}
~CRWLock()
{
DeleteCriticalSection(&m_csLock);
}
BOOL ReadLock(int nTimeout = 0)
{
EnterCriticalSectionTimeout(nTimeout);
// increment (interlocked because release doesn't do CS) read lock count
InterlockedIncrement(&m_nReadLocks);
LeaveCriticalSection(&m_csLock);
return TRUE;
}
void ReadUnlock()
{
// interlocked because outside of CS
InterlockedDecrement(&m_nReadLocks);
}
BOOL WriteLock(int nTimeout = 0)
{
EnterCriticalSectionTimeout(nTimeout);
// wait for all read locks to drain
if ( nTimeout < 0 )
{
if ( m_nReadLocks > 0 )
{
LeaveCriticalSection(&m_csLock);
return FALSE;
}
}
else
{
int i = 0;
for (i = 0; m_nReadLocks > 0; i ++)
{
Sleep(100);
if ( nTimeout > 0 && i >= nTimeout * 10 )
{
LeaveCriticalSection(&m_csLock);
return FALSE;
}
}
}
return TRUE;
}
void WriteUnlock()
{
LeaveCriticalSection(&m_csLock);
}
};
#endif //__CRWLock_h__
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?