AuroraRuntime/Source/Threading/Primitives/AuMutex.Unix.cpp

113 lines
2.5 KiB
C++
Raw Normal View History

2021-06-27 21:25:29 +00:00
/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
2022-11-17 07:46:07 +00:00
File: AuMutex.Unix.cpp
2021-06-27 21:25:29 +00:00
Date: 2021-6-12
Author: Reece
***/
2021-09-30 14:57:41 +00:00
#include <Source/RuntimeInternal.hpp>
2022-11-17 07:46:07 +00:00
#include "AuMutex.Generic.hpp"
2021-06-27 21:25:29 +00:00
#if !defined(_AURUNTIME_GENERICMUTEX)
2022-11-17 07:46:07 +00:00
#include "AuMutex.Unix.hpp"
2021-09-30 14:57:41 +00:00
#include <Source/Time/Time.hpp>
2021-06-27 21:25:29 +00:00
namespace Aurora::Threading::Primitives
{
Mutex::Mutex()
{
auto status = pthread_mutex_init(&this->value_, nullptr) == 0;
2021-06-27 21:25:29 +00:00
SysAssert(status, "Mutex init failed");
}
Mutex::~Mutex()
{
int status = pthread_mutex_destroy(&this->value_);
RUNTIME_ASSERT_SHUTDOWN_SAFE(status == 0, "Mutex destruct failed, {} {}", status, errno);
2021-06-27 21:25:29 +00:00
}
bool Mutex::HasOSHandle(AuMach &mach)
{
mach = reinterpret_cast<AuMach>(&this->value_);
2021-06-27 21:25:29 +00:00
return true;
}
bool Mutex::TryLock()
{
return pthread_mutex_trylock(&this->value_) == 0;
2021-06-27 21:25:29 +00:00
}
bool Mutex::HasLockImplementation()
{
return true;
}
void Mutex::Lock()
{
auto status = Lock(0);
SysAssert(status, "Couldn't lock Mutex object");
}
bool Mutex::Lock(AuUInt64 timeout)
{
if (timeout == 0)
{
int ret {};
do
{
if ((ret = pthread_mutex_lock(&this->value_)) == 0)
{
return true;
}
} while (ret == EINTR);
RUNTIME_ASSERT_SHUTDOWN_SAFE(false, "mutex lock failed: {}", ret)
return false;
2021-06-27 21:25:29 +00:00
}
else
{
struct timespec tspec;
Time::ms2tsabsRealtime(&tspec, timeout);
2021-06-27 21:25:29 +00:00
2022-04-13 15:06:26 +00:00
int ret {};
do
2021-06-27 21:25:29 +00:00
{
ret = pthread_mutex_timedlock(&this->value_, &tspec);
2022-04-13 15:06:26 +00:00
if (ret == 0)
{
return true;
}
if (ret == ETIMEDOUT)
{
return false;
}
} while (ret == EINTR);
2021-06-27 21:25:29 +00:00
RUNTIME_ASSERT_SHUTDOWN_SAFE(false, "mutex timed lock failed: {}", ret)
return false;
2021-06-27 21:25:29 +00:00
}
}
void Mutex::Unlock()
{
auto status = pthread_mutex_unlock(&this->value_) == 0;
2021-06-27 21:25:29 +00:00
SysAssert(status, "Mutex release error");
}
AUKN_SYM IWaitable *MutexNew()
{
return _new Mutex();
}
AUKN_SYM void MutexRelease(IWaitable *waitable)
{
AuSafeDelete<Mutex *>(waitable);
2021-06-27 21:25:29 +00:00
}
}
#endif