AuroraRuntime/Source/Threading/Primitives/AuMutex.Linux.cpp
J Reece Wilson 3ca8de022e [*] Fix issues related to inconstent retardation in the asinine freetard world
GNU and its consequences have been a disaster for the human race
2023-08-26 15:04:48 +01:00

173 lines
3.7 KiB
C++
Executable File

/***
Copyright (C) 2022 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: AuMutex.Linux.cpp
Date: 2022-12-28
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "AuMutex.Generic.hpp"
#include <sys/syscall.h>
#include <linux/futex.h>
#include "SMTYield.hpp"
#if !defined(_AURUNTIME_GENERIC_MUTEX)
#include <Source/Time/Time.hpp>
namespace Aurora::Threading::Primitives
{
MutexImpl::MutexImpl()
{
}
MutexImpl::~MutexImpl()
{
}
bool MutexImpl::HasOSHandle(AuMach &mach)
{
return false;
}
bool MutexImpl::HasLockImplementation()
{
return true;
}
bool MutexImpl::TryLock()
{
if (gRuntimeConfig.threadingConfig.bPreferLinuxMutexSpinTryLock)
{
return TryLockHeavy();
}
else
{
return TryLockNoSpin();
}
}
bool MutexImpl::TryLockNoSpin()
{
return AuAtomicTestAndSet(&this->state_, 0) == 0;
}
bool MutexImpl::TryLockHeavy()
{
return DoTryIf([=]()
{
return TryLockNoSpin();
});
}
bool MutexImpl::LockMS(AuUInt64 uTimeout)
{
return LockNS(AuMSToNS<AuUInt64>(uTimeout));
}
bool MutexImpl::LockNS(AuUInt64 uTimeout)
{
AuUInt64 uStart {};
AuUInt64 uEnd {};
if (this->TryLockHeavy())
{
return true;
}
AuAtomicAdd(&this->dwSleeping_, 1u);
//redundant: 8.2.3.8
//barrier();
struct timespec tspec;
if (uTimeout != 0)
{
uStart = AuTime::SteadyClockNS();
uEnd = uStart + uTimeout;
Time::monoabsns2ts(&tspec, uEnd);
}
auto state = this->state_;
while (!(state == 0 &&
AuAtomicCompareExchange<AuUInt32>(&this->state_, 1, state) == state))
{
if (uTimeout != 0)
{
if (Time::SteadyClockNS() >= uEnd)
{
AuAtomicSub(&this->dwSleeping_, 1u);
return false;
}
int ret {};
do
{
ret = futex_wait(&this->state_, state, &tspec);
}
while (ret == -EINTR);
}
else
{
int ret {};
bool bStatus {};
do
{
if ((ret = futex_wait(&this->state_, state)) == 0)
{
bStatus = true;
break;
}
if (ret == EAGAIN)
{
bStatus = true;
break;
}
}
while (ret == -EINTR);
RUNTIME_ASSERT_SHUTDOWN_SAFE(bStatus, "Mutex wait failed: {}", ret)
}
state = this->state_;
}
AuAtomicSub(&this->dwSleeping_, 1u);
return true;
}
void MutexImpl::SlowLock()
{
auto status = LockMS(0);
SysAssert(status, "Couldn't lock mutex");
}
void MutexImpl::Unlock()
{
AuAtomicClearU8Lock(&this->state_);
if (AuAtomicLoad(&this->dwSleeping_))
{
futex_wake(&this->state_, 1);
}
}
AUKN_SYM IHyperWaitable *MutexNew()
{
return _new MutexImpl();
}
AUKN_SYM void MutexRelease(IHyperWaitable *pMutex)
{
AuSafeDelete<MutexImpl *>(pMutex);
}
AUROXTL_INTERFACE_SOO_SRC_EX(AURORA_SYMBOL_EXPORT, Mutex, MutexImpl)
}
#endif