AuroraRuntime/Source/Threading/Primitives/AuCriticalSection.cpp

121 lines
2.2 KiB
C++
Raw Normal View History

2021-06-27 21:25:29 +00:00
/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
2022-11-17 07:46:07 +00:00
File: AuCriticalSection.cpp
2021-06-27 21:25:29 +00:00
Date: 2021-6-12
Author: Reece
***/
2021-09-30 14:57:41 +00:00
#include <Source/RuntimeInternal.hpp>
2022-11-17 07:46:07 +00:00
#include "AuCriticalSection.hpp"
2021-06-27 21:25:29 +00:00
namespace Aurora::Threading::Primitives
{
CriticalSection::CriticalSection()
{
this->owner_ = {};
2022-11-17 07:46:07 +00:00
this->count_ = 0;
2021-06-27 21:25:29 +00:00
}
CriticalSection::~CriticalSection()
{
}
bool CriticalSection::HasOSHandle(AuMach &mach)
{
return false;
}
bool CriticalSection::TryLock()
{
auto cur = GetThreadCookie();
2021-06-27 21:25:29 +00:00
2022-11-17 07:46:07 +00:00
if (this->owner_ == cur)
2021-06-27 21:25:29 +00:00
{
2022-11-17 07:46:07 +00:00
this->count_++;
2021-06-27 21:25:29 +00:00
return true;
}
2022-11-17 07:46:07 +00:00
if (!this->mutex_.TryLock())
2021-06-27 21:25:29 +00:00
{
return false;
}
2022-11-17 07:46:07 +00:00
this->owner_ = cur;
this->count_ = 1;
2021-06-27 21:25:29 +00:00
return true;
}
void CriticalSection::Lock()
{
auto status = Lock(0);
SysAssert(status, "Spurious critical section wakeup");
}
bool CriticalSection::Lock(AuUInt64 timeout)
{
auto cur = GetThreadCookie();
2021-06-27 21:25:29 +00:00
2022-11-17 07:46:07 +00:00
if (this->owner_ == cur)
2021-06-27 21:25:29 +00:00
{
2022-11-17 07:46:07 +00:00
this->count_++;
2021-06-27 21:25:29 +00:00
return true;
}
if (!this->mutex_.Lock(timeout))
{
return false;
}
this->owner_ = cur;
this->count_ = 1;
return true;
}
bool CriticalSection::LockNS(AuUInt64 timeout)
{
auto cur = GetThreadCookie();
if (this->owner_ == cur)
{
this->count_++;
return true;
}
if (!this->mutex_.LockNS(timeout))
2021-06-27 21:25:29 +00:00
{
return false;
}
2022-11-17 07:46:07 +00:00
this->owner_ = cur;
this->count_ = 1;
2021-06-27 21:25:29 +00:00
return true;
}
void CriticalSection::Unlock()
{
2022-11-17 07:46:07 +00:00
if (--this->count_ == 0)
2021-06-27 21:25:29 +00:00
{
this->owner_ = {};
2022-11-17 07:46:07 +00:00
this->mutex_.Unlock();
2021-06-27 21:25:29 +00:00
}
}
bool CriticalSection::HasLockImplementation()
{
return true;
}
AUKN_SYM IWaitable *CriticalSectionNew()
{
return _new CriticalSection();
}
2022-11-17 07:46:07 +00:00
AUKN_SYM void CriticalSectionRelease(IWaitable *pCriticalSection)
2021-06-27 21:25:29 +00:00
{
2022-11-17 07:46:07 +00:00
AuSafeDelete<CriticalSection *>(pCriticalSection);
2021-06-27 21:25:29 +00:00
}
}