[*] After 2 or 3 years, redo the spinlock

This commit is contained in:
Reece Wilson 2024-05-07 16:46:12 +01:00
parent 631624dc55
commit d589ce3549

View File

@ -11,21 +11,9 @@
namespace Aurora::Threading::Primitives
{
static void YieldCpu(long &count)
{
int loops = (1 << count);
while (loops > 0)
{
SMPPause();
loops -= 1;
}
count++;
if (count >= 15) count = 0;
}
SpinLock::SpinLock()
{
state_ = 0;
this->state_ = 0;
}
bool SpinLock::HasOSHandle(AuMach &mach)
@ -35,7 +23,10 @@ namespace Aurora::Threading::Primitives
bool SpinLock::TryLock()
{
return AuAtomicTestAndSet(&this->state_, 0) == 0;
return DoTryIfAlderLake([=]()
{
return AuAtomicTestAndSet(&this->state_, 0) == 0;
}, &this->state_);
}
bool SpinLock::HasLockImplementation()
@ -49,36 +40,81 @@ namespace Aurora::Threading::Primitives
SysAssert(status, "Couldn't lock Mutex object");
}
bool SpinLock::LockNS(AuUInt64 timeout)
bool SpinLock::LockAbsNS(AuUInt64 timeout)
{
if (timeout == 0)
{
while (AuAtomicTestAndSet(&this->state_, 0))
while (true)
{
long count = 0;
while (this->state_)
if (DoTryIfAlderLake([=]()
{
YieldCpu(count);
return AuAtomicTestAndSet(&this->state_, 0) == 0;
}, &this->state_))
{
return true;
}
}
}
else
{
AuUInt64 startTime = AuTime::SteadyClockNS();
AuUInt64 endTime = startTime + timeout;
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
{
timeout += AuTime::SteadyClockNS();
while (AuAtomicTestAndSet(&this->state_, 0))
{
long count = 0;
while (this->state_)
if (DoTryIfAlderLake([=]()
{
if (endTime <= AuTime::SteadyClockNS())
{
return false;
}
YieldCpu(count);
return AuAtomicTestAndSet(&this->state_, 0) == 0;
}, &this->state_))
{
return true;
}
if (timeout <= AuTime::SteadyClockNS())
{
return false;
}
}
return true;
}
return true;