aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--libs/kstd/include/kstd/mutex61
1 files changed, 61 insertions, 0 deletions
diff --git a/libs/kstd/include/kstd/mutex b/libs/kstd/include/kstd/mutex
index ae91970..7795558 100644
--- a/libs/kstd/include/kstd/mutex
+++ b/libs/kstd/include/kstd/mutex
@@ -38,6 +38,67 @@ namespace kstd
std::atomic_flag m_locked{};
};
+ //! A tag type to specify that a given @p lockable wrapper should adopt ownership of the @p lockable.
+ struct adopt_lock_t
+ {
+ explicit adopt_lock_t() = default;
+ } constexpr inline adopt_lock{};
+
+ //! A tag type to specify that a given @p lockable wrapper should defer locking the @p lockable.
+ struct defer_lock_t
+ {
+ explicit defer_lock_t() = default;
+ } constexpr inline defer_lock{};
+
+ //! A tag type to specify that a given @p lockable wrapper should attempt to lock the @p lockable.
+ struct try_to_lock_t
+ {
+ explicit try_to_lock_t() = default;
+ } constexpr inline try_to_lock{};
+
+ //! An RAII wrapper for a single @p lockable like a kstd::mutex.
+ template<typename MutexType>
+ struct lock_guard
+ {
+ using mutex_type = MutexType;
+
+ //! Construct a new lock_guard and immediately lock the given mutex.
+ //!
+ //! @note This function will block until the mutex was successfully locked.
+ //! @param mutex The mutex to lock.
+ [[gnu::section(".stl_text")]]
+ lock_guard(MutexType & mutex) noexcept
+ : m_mutex(mutex)
+ {
+ m_mutex.lock();
+ }
+
+ //! Construct a new lock_guard and take ownership of the given mutex.
+ //!
+ //! @note The behavior is undefined if the mutex is not owned by the current thread.
+ //! @param mutex The mutex to take ownership of.
+ [[gnu::section(".stl_text")]]
+ lock_guard(MutexType & mutex, adopt_lock_t) noexcept
+ : m_mutex(mutex)
+ {}
+
+ //! Destroy this lock_guard and release the owned mutex.
+ [[gnu::section(".stl_text")]]
+ ~lock_guard()
+ {
+ m_mutex.unlock();
+ }
+
+ lock_guard(lock_guard const &) noexcept = delete;
+ lock_guard(lock_guard &&) noexcept = delete;
+
+ auto operator=(lock_guard const &) noexcept -> lock_guard & = delete;
+ auto operator=(lock_guard &&) noexcept -> lock_guard & = delete;
+
+ private:
+ mutex_type & m_mutex;
+ };
+
} // namespace kstd
#endif \ No newline at end of file