diff --git a/Source/Threading/Primitives/AuSemaphore.NT.cpp b/Source/Threading/Primitives/AuSemaphore.NT.cpp index 5136f0b5..18a94e40 100644 --- a/Source/Threading/Primitives/AuSemaphore.NT.cpp +++ b/Source/Threading/Primitives/AuSemaphore.NT.cpp @@ -36,8 +36,17 @@ namespace Aurora::Threading::Primitives bool SemaphoreImpl::TryLockNoSpin() { - auto old = this->dwState_; - return (old != 0 && AuAtomicCompareExchange(&this->dwState_, old - 1, old) == old); + AuUInt32 uOld {}; + + while ((uOld = this->dwState_)) + { + if (AuAtomicCompareExchange(&this->dwState_, uOld - 1, uOld) == uOld) + { + return true; + } + } + + return false; } bool SemaphoreImpl::TryLockHeavy() @@ -87,10 +96,7 @@ namespace Aurora::Threading::Primitives if (gUseNativeWaitSemapahore) { - AuUInt32 uYieldCounter {}; - auto old = this->dwState_; - while (!((old != 0) && - (AuAtomicCompareExchange(&this->dwState_, old - 1, old) == old))) + while (!this->TryLockNoSpin()) { static const AuUInt32 kExpect { 0 }; @@ -103,8 +109,6 @@ namespace Aurora::Threading::Primitives { return false; } - - old = this->dwState_; } return true; @@ -148,9 +152,8 @@ namespace Aurora::Threading::Primitives if (gUseNativeWaitSemapahore) { AuUInt32 uYieldCounter {}; - auto old = this->dwState_; - while (!((old != 0) && - (AuAtomicCompareExchange(&this->dwState_, old - 1, old) == old))) + + while (!this->TryLockNoSpin()) { static const AuUInt32 kExpect { 0 }; @@ -163,8 +166,6 @@ namespace Aurora::Threading::Primitives { return false; } - - old = this->dwState_; } return true;