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

108 lines
2.2 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: AuMutex.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 "AuMutex.Generic.hpp"
2021-06-27 21:25:29 +00:00
#if !defined(_AURUNTIME_GENERICMUTEX)
2022-11-17 07:46:07 +00:00
#include "AuMutex.NT.hpp"
2021-06-27 21:25:29 +00:00
namespace Aurora::Threading::Primitives
{
Mutex::Mutex()
{
InitializeSRWLock(&atomicHolder_);
InitializeConditionVariable(&wakeup_);
state_ = 0;
}
Mutex::~Mutex()
{
}
bool Mutex::HasOSHandle(AuMach &mach)
{
return false;
}
bool Mutex::TryLock()
{
return _interlockedbittestandset(&state_, 0) == 0;
}
bool Mutex::HasLockImplementation()
{
return true;
}
void Mutex::Lock()
{
auto status = Lock(0);
SysAssert(status, "Couldn't lock Mutex object");
}
bool Mutex::Lock(AuUInt64 timeout)
{
bool returnValue = false;
AcquireSRWLockShared(&atomicHolder_);
AuInt64 startTime = Time::CurrentClockMS();
AuInt64 endTime = startTime + timeout;
BOOL status = false;
while (!TryLock())
{
AuUInt32 timeoutMs = INFINITE;
if (timeout != 0)
{
2022-02-18 11:52:52 +00:00
startTime = Time::CurrentClockMS();
if (startTime >= endTime)
2021-06-27 21:25:29 +00:00
{
goto exitWin32;
}
2022-02-18 11:52:52 +00:00
timeoutMs = endTime - startTime;
2021-06-27 21:25:29 +00:00
}
2022-02-18 11:52:52 +00:00
status = SleepConditionVariableSRW(&wakeup_, &atomicHolder_, timeoutMs, CONDITION_VARIABLE_LOCKMODE_SHARED);
2021-06-27 21:25:29 +00:00
if (!status)
{
SysAssertExp(GetLastError() == ERROR_TIMEOUT);
goto exitWin32;
}
}
returnValue = true;
2022-02-18 11:52:52 +00:00
exitWin32:
2021-06-27 21:25:29 +00:00
ReleaseSRWLockShared(&atomicHolder_);
return returnValue;
}
void Mutex::Unlock()
{
AcquireSRWLockExclusive(&atomicHolder_);
state_ = 0;
ReleaseSRWLockExclusive(&atomicHolder_);
WakeAllConditionVariable(&wakeup_);
}
AUKN_SYM IWaitable *MutexNew()
{
return _new Mutex();
}
2022-11-17 07:46:07 +00:00
AUKN_SYM void MutexRelease(IWaitable *pMutex)
2021-06-27 21:25:29 +00:00
{
2022-11-17 07:46:07 +00:00
AuSafeDelete<Mutex *>(pMutex);
2021-06-27 21:25:29 +00:00
}
}
#endif