AuroraRuntime/Source/Threading/Primitives/AuSpinLock.cpp
Reece 2a33d61e63 [*] further deprecate high res clock
[*] further posix resolution reporting
2023-04-22 22:58:20 +01:00

96 lines
2.0 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: AuSpinLock.cpp
Date: 2021-6-12
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "AuSpinLock.hpp"
#include "SMTYield.hpp"
namespace Aurora::Threading::Primitives
{
static void YieldCpu(long &count)
{
int loops = (1 << count);
while (loops > 0)
{
SMPPause();
loops -= 1;
}
count++;
if (count >= 15) count = 0;
}
SpinLock::SpinLock()
{
state_ = 0;
}
bool SpinLock::HasOSHandle(AuMach &mach)
{
return false;
}
bool SpinLock::TryLock()
{
return AuAtomicTestAndSet(&this->state_, 0) == 0;
}
bool SpinLock::HasLockImplementation()
{
return true;
}
void SpinLock::SlowLock()
{
auto status = LockNS(0);
SysAssert(status, "Couldn't lock Mutex object");
}
bool SpinLock::LockNS(AuUInt64 timeout)
{
if (timeout == 0)
{
while (AuAtomicTestAndSet(&this->state_, 0))
{
long count = 0;
while (this->state_)
{
YieldCpu(count);
}
}
}
else
{
AuUInt64 startTime = AuTime::SteadyClockNS();
AuUInt64 endTime = startTime + timeout;
while (AuAtomicTestAndSet(&this->state_, 0))
{
long count = 0;
while (this->state_)
{
if (endTime <= AuTime::SteadyClockNS())
{
return false;
}
YieldCpu(count);
}
}
}
return true;
}
bool SpinLock::LockMS(AuUInt64 timeout)
{
return LockNS(AuMSToNS<AuUInt64>(timeout));
}
void SpinLock::Unlock()
{
this->state_ = 0;
}
}