AuroraRuntime/Include/Aurora/Threading/LockGuard.hpp

89 lines
2.1 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.
File: LockGuard.hpp
Date: 2021-6-10
Author: Reece
***/
#pragma once
namespace Aurora::Threading
{
template<typename T>
class LockGuard
{
2021-09-06 10:58:08 +00:00
private:
2022-01-19 18:18:13 +00:00
using Internal_t = AuRemovePointer_t<T>;
2021-09-06 10:58:08 +00:00
2021-06-27 21:25:29 +00:00
public:
2021-09-06 10:58:08 +00:00
LockGuard(T &lock)
{
2022-01-19 17:08:13 +00:00
if constexpr (AuIsPointer_v<T>)
2021-09-06 10:58:08 +00:00
{
annoying_ = lock;
}
else
{
annoying_ = &lock;
}
if constexpr (AuIsBaseOfTemplate<AURORA_RUNTIME_AU_SHARED_PTR, Internal_t>::value || AuIsBaseOfTemplate<AURORA_RUNTIME_AU_UNIQUE_PTR, Internal_t>::value)
{
annoying_->get()->Lock();
}
else
{
annoying_->Lock();
}
2022-01-21 19:36:56 +00:00
constructed_ = true;
2021-09-06 10:58:08 +00:00
}
LockGuard(T &&lock)
2021-06-27 21:25:29 +00:00
{
2022-01-19 17:08:13 +00:00
if constexpr (AuIsPointer_v<T>)
2021-09-06 10:58:08 +00:00
{
annoying_ = lock;
}
else
{
annoying_ = &lock;
}
if constexpr (AuIsBaseOfTemplate<AURORA_RUNTIME_AU_SHARED_PTR, Internal_t>::value || AuIsBaseOfTemplate<AURORA_RUNTIME_AU_UNIQUE_PTR, Internal_t>::value)
{
annoying_->get()->Lock();
}
else
{
annoying_->Lock();
}
2022-01-21 19:36:56 +00:00
constructed_ = true;
2021-06-27 21:25:29 +00:00
}
~LockGuard()
{
2022-01-21 19:36:56 +00:00
if (!constructed_)
{
return;
}
2021-09-06 10:58:08 +00:00
if constexpr (AuIsBaseOfTemplate<AURORA_RUNTIME_AU_SHARED_PTR, Internal_t>::value || AuIsBaseOfTemplate<AURORA_RUNTIME_AU_UNIQUE_PTR, Internal_t>::value)
{
annoying_->get()->Unlock();
}
else
{
annoying_->Unlock();
}
2021-06-27 21:25:29 +00:00
}
private:
2022-01-19 18:37:00 +00:00
AuConditional_t<AuIsPointer_v<T>, T, T*> annoying_;
2022-01-21 19:36:56 +00:00
bool constructed_ {};
2021-06-27 21:25:29 +00:00
};
2021-09-06 10:58:08 +00:00
#define AU_LOCK_GUARD(variable) Aurora::Threading::LockGuard<decltype(variable)> AU_CONCAT(__stack_lock, __COUNTER__) (variable);
2021-06-27 21:25:29 +00:00
}