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

100.0% Lines (18/18) 100.0% List of functions (5/5) 100.0% Branches (4/4)
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 10381x win_mutex()
41 10381x {
42 10381x ::InitializeCriticalSectionAndSpinCount(&cs_, 0x80000000);
43 10381x }
44
45 10381x ~win_mutex()
46 {
47 10381x ::DeleteCriticalSection(&cs_);
48 10381x }
49
50 win_mutex(win_mutex const&) = delete;
51 win_mutex& operator=(win_mutex const&) = delete;
52
53 1247x void set_enabled(bool v) noexcept
54 {
55 1247x enabled_ = v;
56 1247x }
57 bool enabled() const noexcept
58 {
59 return enabled_;
60 }
61
62 47489x void lock() noexcept
63 {
64
2/2
✓ Branch 2 → 3 taken 47485 times.
✓ Branch 2 → 4 taken 4 times.
47489x if (enabled_)
65 47485x ::EnterCriticalSection(&cs_);
66 47489x }
67
68 47489x void unlock() noexcept
69 {
70
2/2
✓ Branch 2 → 3 taken 47485 times.
✓ Branch 2 → 4 taken 4 times.
47489x if (enabled_)
71 47485x ::LeaveCriticalSection(&cs_);
72 47489x }
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