/*** Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved. File: Semaphore.Unix.cpp Date: 2021-6-12 Author: Reece ***/ #include #include "Semaphore.Generic.hpp" #include "Semaphore.Unix.hpp" #if !defined(_AURUNTIME_GENERIC_SEMAPHORE) && !defined(AURORA_IS_XNU_DERIVED) #include 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(&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; Time::ms2tsabs(&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) { AuSafeDelete(waitable); } } #endif