AuroraRuntime/Source/IO/Loop/LSLocalSemaphore.cpp

174 lines
3.7 KiB
C++

/***
Copyright (C) 2023 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: LSLocalSemaphore.cpp
Date: 2023-10-21
Author: Reece
***/
#include <RuntimeInternal.hpp>
#include "LSLocalSemaphore.hpp"
#include <Source/Threading/Primitives/SMTYield.hpp>
namespace Aurora::IO::Loop
{
static auto const kFutexBitWake = 256u;
LSLocalSemaphore::LSLocalSemaphore()
{
}
LSLocalSemaphore::~LSLocalSemaphore()
{
}
bool LSLocalSemaphore::TryInit(AuUInt32 initialCount)
{
if (!LSSemaphore::TryInit(1))
{
return false;
}
this->uAtomicSemaphore = initialCount;
return true;
}
bool LSLocalSemaphore::OnTrigger(AuUInt handle)
{
if (AuAtomicLoad(&this->uAtomicWord) & kFutexBitWake)
{
AuAtomicSub(&this->uAtomicWord, kFutexBitWake);
}
return this->TryTakeNoSpin();
}
bool LSLocalSemaphore::AddOne()
{
AuAtomicAdd(&this->uAtomicSemaphore, 1u);
while (true)
{
auto uState = AuAtomicLoad(&this->uAtomicWord);
if (uState & kFutexBitWake)
{
if (AuAtomicCompareExchange(&this->uAtomicWord, uState, uState) == uState)
{
return true;
}
else
{
continue;
}
}
if (AuAtomicCompareExchange(&this->uAtomicWord, uState + kFutexBitWake, uState) == uState)
{
LSSemaphore::AddOne();
return true;
}
}
}
bool LSLocalSemaphore::IsSignaled()
{
return this->TryTake();
}
bool LSLocalSemaphore::WaitOn(AuUInt32 timeout)
{
return this->TryTakeWaitMS(timeout);
}
ELoopSource LSLocalSemaphore::GetType()
{
return ELoopSource::eSourceSemaphore;
}
bool LSLocalSemaphore::TryTakeNoSpin()
{
AuUInt32 uOld {};
while ((uOld = this->uAtomicSemaphore))
{
if (AuAtomicCompareExchange(&this->uAtomicSemaphore, uOld - 1, uOld) == uOld)
{
return true;
}
}
return false;
}
bool LSLocalSemaphore::TryTakeSpin()
{
return Threading::Primitives::DoTryIf([&]
{
return this->TryTakeNoSpin();
});
}
bool LSLocalSemaphore::TryTake()
{
return this->TryTakeNoSpin();
}
bool LSLocalSemaphore::TryTakeWaitMS(AuUInt32 timeout)
{
auto uEndTime = AuTime::SteadyClockNS() + AuMSToNS<AuUInt64>(timeout);
if (this->TryTakeSpin())
{
return true;
}
while (!this->TryTakeNoSpin())
{
if (!timeout)
{
if (LSSemaphore::WaitOn(0))
{
return true;
}
}
else
{
auto uStartTime = Time::SteadyClockNS();
if (uStartTime >= uEndTime)
{
return false;
}
auto uDeltaMs = AuNSToMS<AuInt64>(uEndTime - uStartTime);
if (uDeltaMs &&
LSSemaphore::WaitOn(uDeltaMs))
{
return true;
}
}
}
return true;
}
AUKN_SYM AuSPtr<ILSSemaphore> NewLSSemaphore(AuUInt32 initialCount)
{
auto pMutex = AuMakeShared<LSLocalSemaphore>();
if (!pMutex)
{
SysPushErrorGeneric();
return {};
}
if (!pMutex->TryInit(initialCount))
{
SysPushErrorNested();
return {};
}
return pMutex;
}
}