AuroraRuntime/Source/Threading/Primitives/AuSemaphore.NT.cpp
Reece Wilson 72dc0d715e [*] Begin enforcing steady time
[+] IOProcessor::WakeupThread
[+] NT: Begin hacking in timeBeginPeriod (must spam it in some places)
[+] ConsoleTTY (more specifically the win32 calls) are too slow to run on the mainthread. Delegate to worker.
[*] AuTime.CurrentClockSteady
[*] AuTime.CurrentClockSteadyMS
[*] AuTime.CurrentClockSteadyNS
2022-11-28 16:01:08 +00:00

105 lines
2.5 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;
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 timeout)
{
AuUInt64 start = AuTime::CurrentClockSteadyMS();
AuUInt64 end = start + timeout;
AcquireSRWLockShared(&lock_); // we use atomics. using shared is fine, let's not get congested early
while (!TryLock())
{
AuUInt32 timeoutMs = INFINITE;
if (timeout != 0)
{
start = Time::CurrentClockSteadyMS();
if (start >= end)
{
ReleaseSRWLockShared(&this->lock_);
return false;
}
timeoutMs = end - start;
}
if (!::SleepConditionVariableSRW(&this->winCond_, &this->lock_, AuUInt32(timeoutMs), 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)
{
AcquireSRWLockShared(&this->lock_);
AuAtomicAdd<AuInt32>(&this->value_, count);
::WakeAllConditionVariable(&this->winCond_);
ReleaseSRWLockShared(&this->lock_);
}
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