AuroraRuntime/Source/Threading/Primitives/AuSemaphore.NT.cpp

162 lines
4.1 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: AuSemaphore.Win32.cpp
Date: 2021-6-12
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "AuSemaphore.Generic.hpp"
#include "AuSemaphore.NT.hpp"
#if !defined(_AURUNTIME_GENERIC_SEMAPHORE)
namespace Aurora::Threading::Primitives
{
Semaphore::Semaphore(long iIntialValue)
{
this->value_ = iIntialValue;
if (!pWaitOnAddress)
{
::InitializeSRWLock(&this->lock_);
::InitializeConditionVariable(&this->winCond_);
}
}
Semaphore::~Semaphore()
{
}
bool Semaphore::HasOSHandle(AuMach &mach)
{
return false;
}
bool Semaphore::HasLockImplementation()
{
return true;
}
bool Semaphore::TryLock()
{
auto old = this->value_;
return (old != 0 && AuAtomicCompareExchange(&this->value_, old - 1, old) == old);
}
bool Semaphore::Lock(AuUInt64 uTimeout)
{
if (this->TryLock())
{
return true;
}
AuUInt64 uStart = AuTime::SteadyClockMS();
AuUInt64 uEnd = uStart + uTimeout;
if (pWaitOnAddress)
{
auto old = this->value_;
//!tryLock (with old in a scope we can access)
while (!((old != 0) &&
(AuAtomicCompareExchange(&this->value_, old - 1, old) == old)))
{
AuUInt32 timeoutMs = INFINITE;
if (uTimeout != 0)
{
uStart = Time::SteadyClockMS();
if (uStart >= uEnd)
{
return false;
}
timeoutMs = uEnd - uStart;
}
if (!pWaitOnAddress(&this->value_, &old, sizeof(this->value_), timeoutMs))
{
SysAssertExp(GetLastError() == ERROR_TIMEOUT);
return false;
}
old = this->value_;
}
return true;
}
else
{
::AcquireSRWLockShared(&this->lock_); // we use atomics. using shared is fine, let's not get congested early
while (!TryLock())
{
AuUInt32 dwTimeoutMs = INFINITE;
if (uTimeout != 0)
{
uStart = Time::SteadyClockMS();
if (uStart >= uEnd)
{
::ReleaseSRWLockShared(&this->lock_);
return false;
}
dwTimeoutMs = uEnd - uStart;
}
if (!::SleepConditionVariableSRW(&this->winCond_, &this->lock_, AuUInt32(dwTimeoutMs), CONDITION_VARIABLE_LOCKMODE_SHARED))
{
::ReleaseSRWLockShared(&this->lock_);
return false;
}
}
::ReleaseSRWLockShared(&this->lock_);
}
return true;
}
void Semaphore::Lock()
{
auto status = Lock(0);
SysAssert(status, "Couldn't lock semaphore");
}
void Semaphore::Unlock(long count)
{
if (!pWaitOnAddress)
{
::AcquireSRWLockShared(&this->lock_);
AuAtomicAdd<AuInt32>(&this->value_, count);
::WakeAllConditionVariable(&this->winCond_);
::ReleaseSRWLockShared(&this->lock_);
}
else
{
AuAtomicAdd<AuInt32>(&this->value_, count);
if (count == 1)
{
pWakeByAddressSingle(&this->value_);
}
else
{
pWakeByAddressAll(&this->value_);
}
}
}
void Semaphore::Unlock()
{
return Unlock(1);
}
AUKN_SYM ISemaphore *SemaphoreNew(int iInitialCount)
{
return _new Semaphore(iInitialCount);
}
AUKN_SYM void SemaphoreRelease(ISemaphore *pSemaphore)
{
AuSafeDelete<Semaphore *>(pSemaphore);
}
}
#endif