AuroraRuntime/Source/Threading/Primitives/SpinLock.cpp
2022-02-19 13:21:34 +00:00

92 lines
1.9 KiB
C++

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