summaryrefslogtreecommitdiffstats
path: root/lock.hh
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-08-26 10:29:59 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-08-26 10:29:59 +0000
commitfead91cfb1835d16049c615e1f1c87caa606ff06 (patch)
tree0d7fbbff7ff88b0873a99ead502d6ebb12beb6d6 /lock.hh
parentAdding debian version 1.9.5-1. (diff)
downloaddnsdist-fead91cfb1835d16049c615e1f1c87caa606ff06.tar.xz
dnsdist-fead91cfb1835d16049c615e1f1c87caa606ff06.zip
Merging upstream version 1.9.6.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'lock.hh')
-rw-r--r--lock.hh105
1 files changed, 105 insertions, 0 deletions
diff --git a/lock.hh b/lock.hh
index 611d8ad..3602a81 100644
--- a/lock.hh
+++ b/lock.hh
@@ -298,6 +298,111 @@ private:
};
template <typename T>
+class RecursiveLockGuardedHolder
+{
+public:
+ explicit RecursiveLockGuardedHolder(T& value, std::recursive_mutex& mutex) :
+ d_lock(mutex), d_value(value)
+ {
+ }
+
+ T& operator*() const noexcept
+ {
+ return d_value;
+ }
+
+ T* operator->() const noexcept
+ {
+ return &d_value;
+ }
+
+private:
+ std::lock_guard<std::recursive_mutex> d_lock;
+ T& d_value;
+};
+
+template <typename T>
+class RecursiveLockGuardedTryHolder
+{
+public:
+ explicit RecursiveLockGuardedTryHolder(T& value, std::recursive_mutex& mutex) :
+ d_lock(mutex, std::try_to_lock), d_value(value)
+ {
+ }
+
+ T& operator*() const
+ {
+ if (!owns_lock()) {
+ throw std::runtime_error("Trying to access data protected by a mutex while the lock has not been acquired");
+ }
+ return d_value;
+ }
+
+ T* operator->() const
+ {
+ if (!owns_lock()) {
+ throw std::runtime_error("Trying to access data protected by a mutex while the lock has not been acquired");
+ }
+ return &d_value;
+ }
+
+ operator bool() const noexcept
+ {
+ return d_lock.owns_lock();
+ }
+
+ [[nodiscard]] bool owns_lock() const noexcept
+ {
+ return d_lock.owns_lock();
+ }
+
+ void lock()
+ {
+ d_lock.lock();
+ }
+
+private:
+ std::unique_lock<std::recursive_mutex> d_lock;
+ T& d_value;
+};
+
+template <typename T>
+class RecursiveLockGuarded
+{
+public:
+ explicit RecursiveLockGuarded(const T& value) :
+ d_value(value)
+ {
+ }
+
+ explicit RecursiveLockGuarded(T&& value) :
+ d_value(std::move(value))
+ {
+ }
+
+ explicit RecursiveLockGuarded() = default;
+
+ RecursiveLockGuardedTryHolder<T> try_lock()
+ {
+ return RecursiveLockGuardedTryHolder<T>(d_value, d_mutex);
+ }
+
+ RecursiveLockGuardedHolder<T> lock()
+ {
+ return RecursiveLockGuardedHolder<T>(d_value, d_mutex);
+ }
+
+ RecursiveLockGuardedHolder<const T> read_only_lock()
+ {
+ return RecursiveLockGuardedHolder<const T>(d_value, d_mutex);
+ }
+
+private:
+ std::recursive_mutex d_mutex;
+ T d_value;
+};
+
+template <typename T>
class SharedLockGuardedHolder
{
public: