From f4061426069470d5ec2a32f5b3427f204e7d8ca0 Mon Sep 17 00:00:00 2001 From: Daljit Date: Fri, 2 Feb 2024 15:25:14 +0000 Subject: [PATCH] Add new MutexProtected class Following #2778 --- core/mutexprotected.h | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 core/mutexprotected.h diff --git a/core/mutexprotected.h b/core/mutexprotected.h new file mode 100644 index 0000000000..818cba87a9 --- /dev/null +++ b/core/mutexprotected.h @@ -0,0 +1,34 @@ +#ifndef MUTEXPROTECTED_H +#define MUTEXPROTECTED_H + +#include + +template class MutexProtected { +public: + // Constructor forwards arguments to the constructor of the object + template MutexProtected(Args &&...args) : m_object{std::forward(args)...} {} + + class Guard { + public: + Guard(MutexProtected &protectedObject) : m_protectedObject(protectedObject), m_lock(protectedObject.m_mutex) {} + Guard(const Guard &) = delete; + Guard &operator=(const Guard &) = delete; + Guard(Guard &&) noexcept = default; + Guard &operator=(Guard &&) noexcept = default; + ~Guard() = default; + + Object &operator*() { return m_protectedObject.m_object; } + Object *operator->() { return &m_protectedObject.m_object; } + + private: + MutexProtected &m_protectedObject; + std::lock_guard m_lock; + }; + + Guard lock() { return Guard(*this); } + +private: + std::mutex m_mutex; + Object m_object; +}; +#endif // MUTEXPROTECTED_H