AuroraRuntime/Source/Threading/Primitives/AuMutex.Unix.cpp
J Reece Wilson 2209aeb7a8 [+] Linux: semaphores and mutexes directly over futexes. Move UNIX pthread condvar mutex into the condvar mutex class.
[*] BSD: Rewrote fundamentally flawed pthread_mutex class code to use MONOTONIC clock time
[+] Linus SwInfo: Added enterprise check for RedHat
2022-12-28 23:44:45 +00:00

143 lines
3.3 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: AuMutex.Unix.cpp
Date: 2021-6-12
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "AuMutex.Generic.hpp"
#if !defined(_AURUNTIME_GENERIC_MUTEX) && !defined(AURORA_IS_LINUX_DERIVED)
#include <Source/Time/Time.hpp>
namespace Aurora::Threading::Primitives
{
Mutex::Mutex()
{
pthread_condattr_t attr;
::pthread_condattr_init(&attr);
::pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
SysAssert(::pthread_cond_init(&this->pthreadCv_, &attr) == 0, "couldn't initialize mutex/CV");
}
Mutex::~Mutex()
{
::pthread_cond_destroy(&this->pthreadCv_);
}
bool Mutex::HasOSHandle(AuMach &mach)
{
return false;
}
bool Mutex::HasLockImplementation()
{
return true;
}
bool Mutex::TryLock()
{
auto old = this->value_;
return (old == 0 && AuAtomicCompareExchange(&this->value_, 1, old) == old);
}
bool Mutex::Lock(AuUInt64 uTimeout)
{
if (this->TryLock())
{
return true;
}
AuUInt64 uStart = AuTime::SteadyClockMS();
AuUInt64 uEnd = uStart + uTimeout;
AU_LOCK_GUARD(this->mutex_);
auto mutex = reinterpret_cast<pthread_mutex_t*>(this->mutex_.GetOSHandle());
struct timespec tspec;
if (uTimeout != 0)
{
Time::ms2tsabs(&tspec, uTimeout);
}
while (!this->TryLock())
{
if (uTimeout != 0)
{
uStart = Time::SteadyClockMS();
if (uStart >= uEnd)
{
return false;
}
int ret {};
do
{
ret = ::pthread_cond_timedwait(&this->pthreadCv_, mutex, &tspec);
if (ret == 0)
{
continue;
}
if (ret == ETIMEDOUT)
{
return false;
}
}
while (ret == EINTR);
RUNTIME_ASSERT_SHUTDOWN_SAFE(false, "Mutex timed wait failed: {}", ret)
return false;
}
else
{
int ret {};
do
{
if ((ret = ::pthread_cond_wait(&this->pthreadCv_, mutex)) == 0)
{
continue;
}
}
while (ret == EINTR);
RUNTIME_ASSERT_SHUTDOWN_SAFE(false, "Mutex wait failed: {}", ret)
return false;
}
}
return true;
}
void Mutex::Lock()
{
auto status = Lock(0);
SysAssert(status, "Couldn't lock mutex");
}
void Mutex::Unlock()
{
{
AU_LOCK_GUARD(this->mutex_);
this->value_ = 0;
}
auto ret = ::pthread_cond_signal(&this->pthreadCv_);
SysAssert(ret == 0, "Couldn't wake any mutex waiter");
}
AUKN_SYM IWaitable *MutexNew()
{
return _new Mutex();
}
AUKN_SYM void MutexRelease(IWaitable *pMutex)
{
AuSafeDelete<Mutex *>(pMutex);
}
}
#endif