-
Notifications
You must be signed in to change notification settings - Fork 184
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Following #2778
- Loading branch information
Showing
1 changed file
with
34 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |