|
#define DEFAULT_PAUSE_YIELD 8
#define DEFAULT_PAUSE_CYCLE 4096
class CReentrantSpinGuard
{
public:
CReentrantSpinGuard()
: m_dwThreadID (0)
, m_iCount (0)
{
}
~CReentrantSpinGuard()
{
ASSERT(m_dwThreadID == 0);
ASSERT(m_iCount == 0);
}
void Lock()
{
for(UINT i = 0; !_TryLock(i == 0); ++i)
Pause(i);
}
BOOL TryLock()
{
return _TryLock(TRUE);
}
void Unlock()
{
ASSERT(m_dwThreadID == ::GetCurrentThreadId());
if((--m_iCount) == 0)
m_dwThreadID = 0;
}
static void Pause(UINT i)
{
if (i < DEFAULT_PAUSE_YIELD) YieldProcessor();
else if (i < DEFAULT_PAUSE_CYCLE - 1) SwitchToThread();
else if (i < DEFAULT_PAUSE_CYCLE) Sleep(1);
else Pause(i & (DEFAULT_PAUSE_CYCLE - 1));
}
private:
CReentrantSpinGuard(const CReentrantSpinGuard& cs);
CReentrantSpinGuard operator = (const CReentrantSpinGuard& cs);
BOOL _TryLock(BOOL bFirst)
{
DWORD dwCurrentThreadID = ::GetCurrentThreadId();
if(bFirst && m_dwThreadID == dwCurrentThreadID)
{
++m_iCount;
return TRUE;
}
if(::InterlockedCompareExchange(&m_dwThreadID, dwCurrentThreadID, 0) == 0)
{
::_ReadWriteBarrier();
ASSERT(m_iCount == 0);
m_iCount = 1;
return TRUE;
}
return FALSE;
}
private:
volatile DWORD m_dwThreadID;
int m_iCount;
};
具体作用,能帮细说一下不? |
上一篇: 一道链表的题,谢谢大佬下一篇: 关于sql的操作
|