1
0
cuberite-2a/src/OSSupport/CriticalSection.cpp

152 lines
1.6 KiB
C++
Raw Normal View History

#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules
#include "CriticalSection.h"
////////////////////////////////////////////////////////////////////////////////
// cCriticalSection:
2014-10-20 16:26:18 -04:00
#ifdef _DEBUG
cCriticalSection::cCriticalSection()
{
2014-10-20 16:26:18 -04:00
m_IsLocked = 0;
}
2014-10-20 16:26:18 -04:00
#endif // _DEBUG
void cCriticalSection::Lock()
{
2014-10-20 16:26:18 -04:00
m_Mutex.lock();
#ifdef _DEBUG
m_IsLocked += 1;
2014-10-18 19:29:34 -04:00
m_OwningThreadID = std::this_thread::get_id();
#endif // _DEBUG
}
void cCriticalSection::Unlock()
{
#ifdef _DEBUG
ASSERT(m_IsLocked > 0);
m_IsLocked -= 1;
#endif // _DEBUG
2014-10-20 16:26:18 -04:00
m_Mutex.unlock();
}
#ifdef _DEBUG
bool cCriticalSection::IsLocked(void)
{
return (m_IsLocked > 0);
}
bool cCriticalSection::IsLockedByCurrentThread(void)
{
2014-10-18 19:29:34 -04:00
return ((m_IsLocked > 0) && (m_OwningThreadID == std::this_thread::get_id()));
}
#endif // _DEBUG
////////////////////////////////////////////////////////////////////////////////
// cCSLock
2014-07-17 16:50:58 -04:00
cCSLock::cCSLock(cCriticalSection * a_CS)
: m_CS(a_CS)
, m_IsLocked(false)
{
Lock();
}
2014-07-17 16:50:58 -04:00
cCSLock::cCSLock(cCriticalSection & a_CS)
: m_CS(&a_CS)
, m_IsLocked(false)
{
Lock();
}
cCSLock::~cCSLock()
{
if (!m_IsLocked)
{
return;
}
Unlock();
}
void cCSLock::Lock(void)
{
ASSERT(!m_IsLocked);
m_IsLocked = true;
m_CS->Lock();
}
void cCSLock::Unlock(void)
{
ASSERT(m_IsLocked);
m_IsLocked = false;
m_CS->Unlock();
}
////////////////////////////////////////////////////////////////////////////////
// cCSUnlock:
cCSUnlock::cCSUnlock(cCSLock & a_Lock) :
m_Lock(a_Lock)
{
m_Lock.Unlock();
}
cCSUnlock::~cCSUnlock()
{
m_Lock.Lock();
}