/*** Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved. File: AuSemaphore.Win32.cpp Date: 2021-6-12 Author: Reece ***/ #include #include "AuSemaphore.Generic.hpp" #include "AuSemaphore.NT.hpp" #if !defined(_AURUNTIME_GENERIC_SEMAPHORE) namespace Aurora::Threading::Primitives { Semaphore::Semaphore(long iIntialValue) { this->value_ = iIntialValue; InitializeSRWLock(&this->lock_); InitializeConditionVariable(&this->winCond_); } Semaphore::~Semaphore() { } bool Semaphore::HasOSHandle(AuMach &mach) { return false; } bool Semaphore::HasLockImplementation() { return true; } bool Semaphore::TryLock() { auto old = this->value_; return (old != 0 && AuAtomicCompareExchange(&this->value_, old - 1, old) == old); } bool Semaphore::Lock(AuUInt64 timeout) { AuUInt64 start = AuTime::CurrentInternalClockMS(); AuUInt64 end = start + timeout; AcquireSRWLockShared(&lock_); // we use atomics. using shared is fine, let's not get congested early while (!TryLock()) { AuUInt32 timeoutMs = INFINITE; if (timeout != 0) { start = Time::CurrentClockMS(); if (start >= end) { ReleaseSRWLockShared(&this->lock_); return false; } timeoutMs = end - start; } if (!::SleepConditionVariableSRW(&this->winCond_, &this->lock_, AuUInt32(timeoutMs), CONDITION_VARIABLE_LOCKMODE_SHARED)) { ReleaseSRWLockShared(&this->lock_); return false; } } ReleaseSRWLockShared(&this->lock_); return true; } void Semaphore::Lock() { auto status = Lock(0); SysAssert(status, "Couldn't lock semaphore"); } void Semaphore::Unlock(long count) { AcquireSRWLockShared(&this->lock_); AuAtomicAdd(&this->value_, count); ::WakeAllConditionVariable(&this->winCond_); ReleaseSRWLockShared(&this->lock_); } void Semaphore::Unlock() { return Unlock(1); } AUKN_SYM ISemaphore *SemaphoreNew(int iInitialCount) { return _new Semaphore(iInitialCount); } AUKN_SYM void SemaphoreRelease(ISemaphore *pSemaphore) { AuSafeDelete(pSemaphore); } } #endif