Add MutexProtectedObject helper class
This commit is contained in:
63
openVulkanoCpp/Base/MutexProtectedObject.hpp
Normal file
63
openVulkanoCpp/Base/MutexProtectedObject.hpp
Normal file
@@ -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 <mutex>
|
||||||
|
|
||||||
|
namespace openVulkanoCpp
|
||||||
|
{
|
||||||
|
template<typename T>
|
||||||
|
class MutexProtectedObject
|
||||||
|
{
|
||||||
|
T object;
|
||||||
|
std::mutex mutex;
|
||||||
|
|
||||||
|
public:
|
||||||
|
class Accessor
|
||||||
|
{
|
||||||
|
std::unique_lock<std::mutex> 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<typename... Args>
|
||||||
|
MutexProtectedObject(Args&&... args)
|
||||||
|
: object(std::forward<Args>(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();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user