92 lines
1.9 KiB
C++
92 lines
1.9 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"
|
|
|
|
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 (this->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()
|
|
{
|
|
this->value_ = 0;
|
|
}
|
|
} |