1+ #pragma once
2+ #ifndef CPPBASE_MUTEX_HPP
3+ #define CPPBASE_MUTEX_HPP
4+
5+ #include < mutex>
6+ #include < chrono>
7+ #include < type_traits>
8+ #include " nocopyable.hpp"
9+ #include " nomoveable.hpp"
10+
11+ namespace cppbase {
12+
13+ /* *
14+ * @brief Generic template mutex class, based on standard mutex type encapsulation
15+ * @tparam Mtx Underlying mutex type, default is std::mutex
16+ * @note Template implementation is in mutex-inl.hpp, must be included after declaration
17+ */
18+ template <typename Mtx = std::mutex>
19+ class Mutex final : public NoCopyable, public NoMoveable
20+ {
21+ public:
22+ void lock ();
23+ bool try_lock () noexcept ;
24+ void unlock () noexcept ;
25+
26+ template <class Rep , class Period >
27+ auto try_lock_for (const std::chrono::duration<Rep, Period>& rel_time)
28+ -> decltype(std::declval<Mtx>().try_lock_for(rel_time), bool());
29+
30+ template <class Clock , class Duration >
31+ auto try_lock_until (const std::chrono::time_point<Clock, Duration>& abs_time)
32+ -> decltype(std::declval<Mtx>().try_lock_until(abs_time), bool());
33+
34+ typename Mtx::native_handle_type native_handle () noexcept ;
35+
36+ private:
37+ Mtx mutex_;
38+ };
39+
40+ /* *
41+ * @brief RAII wrapper for Mutex, auto lock/unlock
42+ * @tparam Mtx Underlying mutex type (same as Mutex's template parameter)
43+ * @note Only works with cppbase::Mutex, not std::mutex directly
44+ */
45+ template <typename Mtx = std::mutex>
46+ class LockGuard final : public NoCopyable, public NoMoveable
47+ {
48+ public:
49+ explicit LockGuard (Mutex<Mtx> &mtx) noexcept
50+ : mutex_(mtx)
51+ {
52+ mutex_.lock ();
53+ }
54+
55+ ~LockGuard () noexcept
56+ {
57+ mutex_.unlock ();
58+ }
59+
60+ private:
61+ Mutex<Mtx> &mutex_;
62+ };
63+
64+ } // namespace cppbase
65+
66+ #include " mutex-inl.hpp"
67+ #endif // CPPBASE_MUTEX_HPP
0 commit comments