139 lines
3.2 KiB
C++
139 lines
3.2 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"
|
|
#include "SMTYield.hpp"
|
|
|
|
#if !defined(_AURUNTIME_GENERIC_MUTEX) && !defined(AURORA_IS_LINUX_DERIVED)
|
|
#include <Source/Time/Time.hpp>
|
|
|
|
namespace Aurora::Threading::Primitives
|
|
{
|
|
MutexImpl::MutexImpl()
|
|
{
|
|
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");
|
|
}
|
|
|
|
MutexImpl::~MutexImpl()
|
|
{
|
|
::pthread_cond_destroy(&this->pthreadCv_);
|
|
}
|
|
|
|
bool MutexImpl::HasOSHandle(AuMach &mach)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
bool MutexImpl::HasLockImplementation()
|
|
{
|
|
return true;
|
|
}
|
|
|
|
bool MutexImpl::TryLock()
|
|
{
|
|
return DoTryIf([=]()
|
|
{
|
|
auto old = this->value_;
|
|
return (old == 0 && AuAtomicCompareExchange(&this->value_, 1, old) == old);
|
|
});
|
|
}
|
|
|
|
bool MutexImpl::LockMS(AuUInt64 uTimeout)
|
|
{
|
|
return LockNS(AuMSToNS<AuUInt64>(uTimeout));
|
|
}
|
|
|
|
bool MutexImpl::LockNS(AuUInt64 uTimeout)
|
|
{
|
|
if (this->TryLock())
|
|
{
|
|
return true;
|
|
}
|
|
|
|
AuUInt64 uStart = AuTime::SteadyClockNS();
|
|
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::auabsns2ts(&tspec, uEnd);
|
|
}
|
|
|
|
int ret {};
|
|
while (!this->TryLock())
|
|
{
|
|
if (uTimeout != 0)
|
|
{
|
|
uStart = Time::SteadyClockNS();
|
|
if (uStart >= uEnd)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
do
|
|
{
|
|
ret = ::pthread_cond_timedwait(&this->pthreadCv_, mutex, &tspec);
|
|
}
|
|
while (ret == EINTR);
|
|
}
|
|
else
|
|
{
|
|
bool bStatus {};
|
|
|
|
do
|
|
{
|
|
if ((ret = ::pthread_cond_wait(&this->pthreadCv_, mutex)) == 0)
|
|
{
|
|
bStatus = true;
|
|
break;
|
|
}
|
|
}
|
|
while (ret == EINTR);
|
|
|
|
RUNTIME_ASSERT_SHUTDOWN_SAFE(bStatus, "Mutex wait failed: {}", ret)
|
|
}
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
void MutexImpl::Lock()
|
|
{
|
|
auto status = LockNS(0);
|
|
SysAssert(status, "Couldn't lock mutex");
|
|
}
|
|
|
|
void MutexImpl::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 MutexImpl();
|
|
}
|
|
|
|
AUKN_SYM void MutexRelease(IWaitable *pMutex)
|
|
{
|
|
AuSafeDelete<MutexImpl *>(pMutex);
|
|
}
|
|
|
|
AUROXTL_INTERFACE_SOO_SRC_EX(AURORA_SYMBOL_EXPORT, Mutex, MutexImpl)
|
|
}
|
|
#endif |