Skip to content

Commit

Permalink
Add new MutexProtected class
Browse files Browse the repository at this point in the history
Following #2778
  • Loading branch information
daljit46 committed Feb 19, 2024
1 parent 87f3b01 commit f406142
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions core/mutexprotected.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#ifndef MUTEXPROTECTED_H
#define MUTEXPROTECTED_H

#include <mutex>

template <typename Object> class MutexProtected {
public:
// Constructor forwards arguments to the constructor of the object
template <typename... Args> MutexProtected(Args &&...args) : m_object{std::forward<Args>(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<std::mutex> m_lock;
};

Guard lock() { return Guard(*this); }

private:
std::mutex m_mutex;
Object m_object;
};
#endif // MUTEXPROTECTED_H

0 comments on commit f406142

Please sign in to comment.