/*** Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved. File: AuMutex.Unix.cpp Date: 2021-6-12 Author: Reece ***/ #include #include "AuMutex.Generic.hpp" #include "SMPYield.hpp" #if !defined(_AURUNTIME_GENERIC_MUTEX) && !defined(AURORA_IS_LINUX_DERIVED) #include 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() { // Assume heavyweight pthread_cond_timedwait yield is followed by an instant hit, for now auto old = this->value_; return (old == 0 && AuAtomicCompareExchange(&this->value_, 1, old) == old); } bool Mutex::Lock(AuUInt64 uTimeout) { return LockNS(AuMSToNS(uTimeout)); } bool Mutex::LockNS(AuUInt64 uTimeout) { if (DoTryIf([=]() { auto old = this->value_; return (old == 0 && AuAtomicCompareExchange(&this->value_, 1, old) == old); })) { return true; } AuUInt64 uStart = AuTime::SteadyClockNS(); AuUInt64 uEnd = uStart + uTimeout; AU_LOCK_GUARD(this->mutex_); auto mutex = reinterpret_cast(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 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(pMutex); } } #endif