AuroraRuntime/Source/Threading/Primitives/AuSpinLock.cpp

132 lines
2.8 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
{
SpinLock::SpinLock()
{
this->state_ = 0;
2021-06-27 21:25:29 +00:00
}
bool SpinLock::HasOSHandle(AuMach &mach)
{
return false;
}
bool SpinLock::TryLock()
{
return DoTryIfAlderLake([=]()
{
return AuAtomicTestAndSet(&this->state_, 0) == 0;
}, &this->state_);
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::LockAbsNS(AuUInt64 timeout)
2021-06-27 21:25:29 +00:00
{
if (timeout == 0)
{
while (true)
{
if (DoTryIfAlderLake([=]()
{
return AuAtomicTestAndSet(&this->state_, 0) == 0;
}, &this->state_))
{
return true;
}
}
}
else
{
while (AuAtomicTestAndSet(&this->state_, 0))
{
if (DoTryIfAlderLake([=]()
{
return AuAtomicTestAndSet(&this->state_, 0) == 0;
}, &this->state_))
{
return true;
}
if (timeout <= AuTime::SteadyClockNS())
{
return false;
}
}
return true;
}
return true;
}
bool SpinLock::LockNS(AuUInt64 timeout)
{
if (timeout == 0)
{
while (true)
{
if (DoTryIfAlderLake([=]()
{
return AuAtomicTestAndSet(&this->state_, 0) == 0;
}, &this->state_))
{
return true;
}
}
}
else
2021-06-27 21:25:29 +00:00
{
timeout += AuTime::SteadyClockNS();
while (AuAtomicTestAndSet(&this->state_, 0))
2021-06-27 21:25:29 +00:00
{
if (DoTryIfAlderLake([=]()
{
return AuAtomicTestAndSet(&this->state_, 0) == 0;
}, &this->state_))
{
return true;
}
if (timeout <= AuTime::SteadyClockNS())
{
return false;
}
2021-06-27 21:25:29 +00:00
}
return true;
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
}
}