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

93 lines
2.0 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: Mutex.Unix.cpp
Date: 2021-6-12
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "Mutex.Generic.hpp"
#if !defined(_AURUNTIME_GENERICMUTEX)
#include "Mutex.Unix.hpp"
#include <Source/Time/Time.hpp>
namespace Aurora::Threading::Primitives
{
Mutex::Mutex()
{
auto status = pthread_mutex_init(&value_, nullptr) == 0;
SysAssert(status, "Mutex init failed");
}
Mutex::~Mutex()
{
auto status = pthread_mutex_destroy(&value_) == 0;
SysAssert(status, "Mutex init failed");
}
bool Mutex::HasOSHandle(AuMach &mach)
{
mach = reinterpret_cast<AuMach>(&value_);
return true;
}
bool Mutex::TryLock()
{
return pthread_mutex_trylock(&value_) == 0;
}
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)
{
auto status = pthread_mutex_lock(&value_) == 0;
SysAssert(status, "mutex lock failed");
return true;
}
else
{
struct timespec tspec;
Time::ms2tsabs(&tspec, timeout);
auto ret = pthread_mutex_timedlock(&value_, &tspec);
if (ret != 0)
{
SysAssert(errno == ETIMEDOUT, "mutex timed lock failed");
return false;
}
return true;
}
}
void Mutex::Unlock()
{
auto status = pthread_mutex_unlock(&value_) == 0;
SysAssert(status, "Mutex release error");
}
AUKN_SYM IWaitable *MutexNew()
{
return _new Mutex();
}
AUKN_SYM void MutexRelease(IWaitable *waitable)
{
AuSafeDelete<Mutex *>(waitable);
}
}
#endif