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

108 lines
2.3 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(&this->atomicHolder_);
InitializeConditionVariable(&this->wakeup_);
this->state_ = 0;
2021-06-27 21:25:29 +00:00
}
Mutex::~Mutex()
{
}
bool Mutex::HasOSHandle(AuMach &mach)
{
return false;
}
bool Mutex::TryLock()
{
return _interlockedbittestandset(&this->state_, 0) == 0;
2021-06-27 21:25:29 +00:00
}
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(&this->atomicHolder_);
2021-06-27 21:25:29 +00:00
AuInt64 startTime = Time::SteadyClockMS();
2021-06-27 21:25:29 +00:00
AuInt64 endTime = startTime + timeout;
BOOL status = false;
while (!TryLock())
{
AuUInt32 timeoutMs = INFINITE;
if (timeout != 0)
{
startTime = Time::SteadyClockMS();
2022-02-18 11:52:52 +00:00
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
}
status = SleepConditionVariableSRW(&this->wakeup_, &this->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:
ReleaseSRWLockShared(&this->atomicHolder_);
2021-06-27 21:25:29 +00:00
return returnValue;
}
void Mutex::Unlock()
{
AcquireSRWLockExclusive(&this->atomicHolder_);
this->state_ = 0;
ReleaseSRWLockExclusive(&this->atomicHolder_);
WakeAllConditionVariable(&this->wakeup_);
2021-06-27 21:25:29 +00:00
}
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