AuroraRuntime/Source/Threading/Primitives/Semaphore.Unix.cpp
2021-06-27 22:25:29 +01:00

99 lines
2.2 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: Semaphore.Unix.cpp
Date: 2021-6-12
Author: Reece
***/
#include <RuntimeInternal.hpp>
#include "Semaphore.Generic.hpp"
#include "Semaphore.Unix.hpp"
#if !defined(_AURUNTIME_GENERIC_SEMAPHORE)
#include <Time/Time.hpp>
namespace Aurora::Threading::Primitives
{
Semaphore::Semaphore(long intialValue)
{
auto status = sem_init(&value_, 0, intialValue) == 0;
SysAssert(status, "Semaphore init failed");
}
Semaphore::~Semaphore()
{
auto status = sem_destroy(&value_) == 0;
SysAssert(status, "Semaphore destroy failed");
}
bool Semaphore::HasOSHandle(AuMach &mach)
{
mach = reinterpret_cast<AuMach>(value_);
return true;
}
bool Semaphore::HasLockImplementation()
{
return true;
}
bool Semaphore::TryLock()
{
return sem_trywait(&_value) == 0;
}
bool Semaphore::Lock(AuUInt64 timeout)
{
if (timeout == 0)
{
auto status = sem_wait(&value_) == 0;
SysAssert(status, "semaphore lock failed");
return true;
}
else
{
struct timespec tspec;
ms2ts(&tspec, timeout);
auto ret = sem_timedwait(&value_, &tspec);
if (ret != 0)
{
SysAssert(errno == ETIMEDOUT, "semaphore timed lock failed");
return false;
}
return true;
}
}
void Semaphore::Lock()
{
auto status = Lock(0);
SysAssert(status, "Couldn't lock semaphore");
}
void Semaphore::Unlock(long count)
{
for (int i = 0; i++; i < count)
{
Unlock();
}
}
void Semaphore::Unlock()
{
auto status = sem_post(&value_) == 0;
SysAssert(status, "Semaphore release error");
}
AUKN_SYM ISemaphore *SemaphoreNew(int initialCount)
{
return _new Semaphore(initialCount);
}
AUKN_SYM void SemaphoreRelease(ISemaphore *waitable)
{
SafeDelete<Semaphore *>(waitable);
}
}
#endif