AuroraRuntime/Source/Threading/Primitives/AuRWLock.hpp
Reece d755a9d651 [*] Massive perf boost by removing atomic and
[*] Refactor ambiguous IWaitable::Lock(timeoutMs) to LockMS to prevent final using collisions
2023-04-03 08:21:44 +01:00

90 lines
2.0 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: AuRWLock.hpp
Date: 2021-6-12
Author: Reece
***/
#pragma once
#include "AuConditionVariable.Generic.hpp"
#include "AuConditionMutex.Generic.hpp"
#include "ThreadCookie.hpp"
namespace Aurora::Threading::Primitives
{
template<bool bIsWriteRecursionAllowed>
struct RWLockImpl;
template<bool bIsReadView, typename T>
struct RWLockAccessView : IWaitable
{
RWLockAccessView(T &impl) : parent_(impl)
{
}
bool LockMS(AuUInt64 timeout) override;
bool LockNS(AuUInt64 timeout) override;
bool TryLock() override;
bool HasOSHandle(AuMach &mach) override
{
return false;
}
bool HasLockImplementation() override
{
return true;
}
void Lock() override
{
SysAssert(LockNS(0));
}
void Unlock() override;
private:
T &parent_;
};
template<bool bIsWriteRecursionAllowed>
struct RWLockImpl : IRWLock
{
RWLockImpl();
~RWLockImpl();
bool LockReadNS(AuUInt64 timeout);
bool LockWriteNS(AuUInt64 timeout);
bool TryLockRead();
bool TryLockWrite();
void UnlockRead();
void UnlockWrite();
bool UpgradeReadToWrite(AuUInt64 timeout) override;
bool DowngradeWriteToRead() override;
IWaitable *AsReadable() override;
IWaitable *AsWritable() override;
bool Init();
private:
//bool reentrantWriteLock_ {true};
ThreadCookie_t reentrantWriteLockHandle_ {};
RWLockAccessView<true, RWLockImpl> read_;
RWLockAccessView<false, RWLockImpl> write_;
ConditionMutexImpl mutex_;
ConditionVariableImpl condition_;
volatile AuInt32 state_ {};
AuInt32 writersPending_ : 31 {};
AuInt32 bElevaterPending_ : 1 {};
//bool bElevaterPending_{};
};
}