AuroraRuntime/Source/Threading/Primitives/AuSpinLock.cpp

92 lines
1.9 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"
2021-06-27 21:25:29 +00:00
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;
2021-06-27 21:25:29 +00:00
}
SpinLock::SpinLock()
{
value_ = 0;
}
bool SpinLock::HasOSHandle(AuMach &mach)
{
return false;
}
bool SpinLock::TryLock()
{
2022-02-19 13:20:22 +00:00
return AuAtomicTestAndSet(&this->value_, 0) == 0;
2021-06-27 21:25:29 +00:00
}
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)
{
2022-02-19 13:20:22 +00:00
while (AuAtomicTestAndSet(&this->value_, 0))
{
long count = 0;
2022-11-17 07:46:07 +00:00
while (this->value_)
{
YieldCpu(count);
}
}
}
else
2021-06-27 21:25:29 +00:00
{
AuUInt64 startTime = AuTime::CurrentInternalClockMS();
AuUInt64 endTime = startTime + timeout;
2022-02-19 13:20:22 +00:00
while (AuAtomicTestAndSet(&this->value_, 0))
2021-06-27 21:25:29 +00:00
{
long count = 0;
while (value_)
{
if (endTime <= AuTime::CurrentInternalClockMS())
{
return false;
}
YieldCpu(count);
}
2021-06-27 21:25:29 +00:00
}
}
return true;
}
void SpinLock::Unlock()
{
2022-11-17 07:46:07 +00:00
this->value_ = 0;
2021-06-27 21:25:29 +00:00
}
}