diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-08-26 10:29:59 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-08-26 10:29:59 +0000 |
commit | fead91cfb1835d16049c615e1f1c87caa606ff06 (patch) | |
tree | 0d7fbbff7ff88b0873a99ead502d6ebb12beb6d6 /lock.hh | |
parent | Adding debian version 1.9.5-1. (diff) | |
download | dnsdist-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.hh | 105 |
1 files changed, 105 insertions, 0 deletions
@@ -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: |