From 55e72222ba09efd7b974abdb005c720e0cb3d9a8 Mon Sep 17 00:00:00 2001 From: GeorgH93 Date: Fri, 1 Jan 2021 09:11:22 +0100 Subject: [PATCH] Add MutexProtectedObject helper class --- openVulkanoCpp/Base/MutexProtectedObject.hpp | 63 ++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 openVulkanoCpp/Base/MutexProtectedObject.hpp diff --git a/openVulkanoCpp/Base/MutexProtectedObject.hpp b/openVulkanoCpp/Base/MutexProtectedObject.hpp new file mode 100644 index 0000000..c6561fa --- /dev/null +++ b/openVulkanoCpp/Base/MutexProtectedObject.hpp @@ -0,0 +1,63 @@ +/* + * This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at https://mozilla.org/MPL/2.0/. + */ + +#pragma once + +#include + +namespace openVulkanoCpp +{ + template + class MutexProtectedObject + { + T object; + std::mutex mutex; + + public: + class Accessor + { + std::unique_lock lock; + T& ref; + + public: + Accessor(std::mutex& m, T& obj) + : lock(m), ref(obj) + {} + + T* operator->() { return &ref; } + + T& Get() { return ref; } + }; + + MutexProtectedObject() = default; + + MutexProtectedObject(const T& initValue) : object(initValue) {} + + template + MutexProtectedObject(Args&&... args) + : object(std::forward(args)...) + {} + + MutexProtectedObject(const MutexProtectedObject&) = delete; + + Accessor Access() + { + return Accessor(mutex, object); + } + + MutexProtectedObject& operator =(const T& value) + { + Accessor accessor = Access(); + object = value; + } + + operator T() + { + Accessor accessor = Access(); + return accessor.Get(); + } + }; +}