AuroraRuntime/Source/Threading/Primitives/AuSpinLock.cpp

96 lines
2.0 KiB
C++
Raw Normal View History

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