AuroraRuntime/Source/Threading/Primitives/AuConditionMutex.NT.cpp

114 lines
2.5 KiB
C++
Raw Normal View History

2021-06-27 21:25:29 +00:00
/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
2022-11-17 07:46:07 +00:00
File: AuConditionMutex.Win32.cpp
2021-06-27 21:25:29 +00:00
Date: 2021-6-12
Author: Reece
***/
2021-09-30 14:57:41 +00:00
#include <Source/RuntimeInternal.hpp>
2022-11-17 07:46:07 +00:00
#include "AuConditionMutex.Generic.hpp"
#include "SMPYield.hpp"
#include "AuProcAddresses.NT.hpp"
2021-06-27 21:25:29 +00:00
#if !defined(_AURUNTIME_GENERICCM)
namespace Aurora::Threading::Primitives
{
2021-06-27 21:25:29 +00:00
Win32ConditionMutex::Win32ConditionMutex()
{
if (gKeyedEventHandle == INVALID_HANDLE_VALUE)
{
if (!pNtCreateKeyedEvent)
{
InitNTAddresses();
}
pNtCreateKeyedEvent(&gKeyedEventHandle, -1, NULL, 0);
}
2021-06-27 21:25:29 +00:00
}
Win32ConditionMutex::~Win32ConditionMutex()
{
}
bool Win32ConditionMutex::TryLock()
{
return DoTryIf([=]()
{
return !AuAtomicTestAndSet(&this->lock_.uWaitCount, 0);
});
}
2021-06-27 21:25:29 +00:00
void Win32ConditionMutex::Lock()
{
while (!TryLock())
{
auto &uValueRef = this->lock_.uWaitCount;
auto uValue = uValueRef | 1;
if (AuAtomicCompareExchange(&uValueRef, uValue + FAST_M_WAIT, uValue) == uValue)
{
pNtWaitForKeyedEvent(gKeyedEventHandle, &uValueRef, 0, NULL);
AuAtomicSub(&uValueRef, FAST_M_WAIT);
}
}
2021-06-27 21:25:29 +00:00
}
void Win32ConditionMutex::Unlock()
{
auto &uValueRef = this->lock_.uWaitCount;
auto uValue = uValueRef;
if (uValue == 1)
{
if (AuAtomicCompareExchange(&uValueRef, 0u, 1u) == 1u)
{
return;
}
}
while (true)
{
if (uValue < FAST_M_WAIT)
{
return;
}
if (uValue & 1)
{
return;
}
if (uValue & FAST_M_WAKE)
{
return;
}
if (AuAtomicCompareExchange(&uValueRef, uValue - FAST_M_WAIT + FAST_M_WAKE, uValue) == uValue)
{
pNtReleaseKeyedEvent(gKeyedEventHandle, &uValueRef, 0, NULL);
return;
}
SMPPause();
}
2021-06-27 21:25:29 +00:00
}
AuUInt Win32ConditionMutex::GetOSHandle()
{
2022-11-17 07:46:07 +00:00
return reinterpret_cast<AuUInt>(&this->lock_);
2021-06-27 21:25:29 +00:00
}
AUKN_SYM IConditionMutex *ConditionMutexNew()
{
return _new Win32ConditionMutex();
}
2022-11-17 07:46:07 +00:00
AUKN_SYM void ConditionMutexRelease(IConditionMutex *pMutex)
2021-06-27 21:25:29 +00:00
{
2022-11-17 07:46:07 +00:00
AuSafeDelete<Win32ConditionMutex *>(pMutex);
2021-06-27 21:25:29 +00:00
}
}
#endif