diff options
| author | Felix Morgner <felix.morgner@ost.ch> | 2025-12-29 12:01:04 +0100 |
|---|---|---|
| committer | Felix Morgner <felix.morgner@ost.ch> | 2025-12-29 12:01:04 +0100 |
| commit | c522a3634e0cd20804b1e3216caedd5e15cbee19 (patch) | |
| tree | c329349fc198c4a43dd0c7461ae70b13351afc7e /libs | |
| parent | c0ef12b6a449aef43d3a6a700a2c4041642bf88c (diff) | |
| download | teachos-c522a3634e0cd20804b1e3216caedd5e15cbee19.tar.xz teachos-c522a3634e0cd20804b1e3216caedd5e15cbee19.zip | |
kstd/mutex: implement lock_guard
Diffstat (limited to 'libs')
| -rw-r--r-- | libs/kstd/include/kstd/mutex | 61 |
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 |
