AuroraRuntime/Source/Threading/Primitives/RWLock.cpp
2021-06-27 22:25:29 +01:00

146 lines
2.6 KiB
C++

/***
Copyright (C) 2021 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: RWLock.cpp
Date: 2021-6-12
Author: Reece
***/
#include <RuntimeInternal.hpp>
#include "RWLock.hpp"
namespace Aurora::Threading::Primitives
{
RWLockImpl::RWLockImpl() : read_(*this), write_(*this)
{
}
RWLockImpl::~RWLockImpl()
{
}
bool RWLockImpl::Init()
{
mutex_ = ConditionMutexUnique();
if (!mutex_)
{
return false;
}
condition_ = ConditionVariableUnique(mutex_.get());
if (!condition_)
{
return false;
}
return true;
}
bool RWLockImpl::LockRead(AuUInt64 timeout)
{
LockGuardPtr<IConditionMutex> mutex(mutex_.get());
while (state_ < 0)
{
if (!condition_->WaitForSignal(timeout))
{
return false;
}
}
state_++;
return true;
}
bool RWLockImpl::LockWrite(AuUInt64 timeout)
{
LockGuardPtr<IConditionMutex> mutex(mutex_.get());
while (state_ != 0)
{
if (!condition_->WaitForSignal(timeout))
{
return false;
}
}
state_ = -1;
return true;
}
bool RWLockImpl::TryLockRead()
{
LockGuardPtr<IConditionMutex> mutex(mutex_.get());
if (state_ == -1)
{
return false;
}
state_++;
return true;
}
bool RWLockImpl::TryLockWrite()
{
LockGuardPtr<IConditionMutex> mutex(mutex_.get());
if (state_ > 0)
{
return false;
}
state_ = -1;
return true;
}
void RWLockImpl::UnlockRead()
{
LockGuardPtr<IConditionMutex> mutex(mutex_.get());
if(--state_ == 0)
{
condition_->Signal();
}
}
void RWLockImpl::UnlockWrite()
{
LockGuardPtr<IConditionMutex> mutex(mutex_.get());
state_ = 0;
condition_->Broadcast();
}
IWaitable *RWLockImpl::AsReadable()
{
return &read_;
}
IWaitable *RWLockImpl::AsWritable()
{
return &write_;
}
AUKN_SYM RWLock *RWLockNew()
{
auto ret = _new RWLockImpl();
if (!ret)
{
return nullptr;
}
if (!ret->Init())
{
delete ret;
return nullptr;
}
return ret;
}
AUKN_SYM void RWLockRelease(RWLock *waitable)
{
SafeDelete<RWLockImpl *>(waitable);
}
}