include/boost/corosio/native/detail/iocp/win_mutex.hpp

100.0% Lines (18 / 18) 100.0% Branches (4 / 4) 100.0% Functions (5 / 5)
win_mutex.hpp
f(x) Functions (5)
Line Branch TLA Hits Source Code
1 //
2 // Copyright (c) 2025 Vinnie Falco ([email protected])
3 // Copyright (c) 2026 Steve Gerbino
4 //
5 // Distributed under the Boost Software License, Version 1.0. (See accompanying
6 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7 //
8 // Official repository: https://github.com/cppalliance/corosio
9 //
10
11 #ifndef BOOST_COROSIO_NATIVE_DETAIL_IOCP_WIN_MUTEX_HPP
12 #define BOOST_COROSIO_NATIVE_DETAIL_IOCP_WIN_MUTEX_HPP
13
14 #include <boost/corosio/detail/platform.hpp>
15
16 #if BOOST_COROSIO_HAS_IOCP
17
18 #include <boost/corosio/detail/config.hpp>
19
20 #include <boost/corosio/native/detail/iocp/win_windows.hpp>
21
22 namespace boost::corosio::detail {
23
24 /** Recursive mutex using Windows CRITICAL_SECTION.
25
26 This mutex can be locked multiple times by the same thread.
27 Each call to `lock()` or successful `try_lock()` must be
28 balanced by a corresponding call to `unlock()`.
29
30 When disabled via `set_enabled(false)`, all locking operations
31 become no-ops. This supports single-threaded (lockless) mode
32 where cross-thread posting is undefined behavior.
33
34 Satisfies the Lockable named requirement and is compatible
35 with `std::lock_guard`, `std::unique_lock`, and `std::scoped_lock`.
36 */
37 class win_mutex
38 {
39 public:
40 8694x win_mutex()
41 8694x {
42 8694x ::InitializeCriticalSectionAndSpinCount(&cs_, 0x80000000);
43 8694x }
44
45 8694x ~win_mutex()
46 {
47 8694x ::DeleteCriticalSection(&cs_);
48 8694x }
49
50 win_mutex(win_mutex const&) = delete;
51 win_mutex& operator=(win_mutex const&) = delete;
52
53 5224x void set_enabled(bool v) noexcept
54 {
55 5224x enabled_ = v;
56 5224x }
57 bool enabled() const noexcept
58 {
59 return enabled_;
60 }
61
62 345082x void lock() noexcept
63 {
64
2/2
✓ Branch 2 → 3 taken 345068 times.
✓ Branch 2 → 4 taken 14 times.
345082x if (enabled_)
65 345068x ::EnterCriticalSection(&cs_);
66 345082x }
67
68 345082x void unlock() noexcept
69 {
70
2/2
✓ Branch 2 → 3 taken 345068 times.
✓ Branch 2 → 4 taken 14 times.
345082x if (enabled_)
71 345068x ::LeaveCriticalSection(&cs_);
72 345082x }
73
74 bool try_lock() noexcept
75 {
76 return !enabled_ || ::TryEnterCriticalSection(&cs_) != 0;
77 }
78
79 private:
80 ::CRITICAL_SECTION cs_;
81 bool enabled_ = true;
82 };
83
84 } // namespace boost::corosio::detail
85
86 #endif // BOOST_COROSIO_HAS_IOCP
87
88 #endif // BOOST_COROSIO_NATIVE_DETAIL_IOCP_WIN_MUTEX_HPP
89