Debian Codegraph @

Utilities/std/cm/shared_mutex

raw
1 // -*-c++-*-
2 // vim: set ft=cpp:
3
4 /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
5 file LICENSE.rst or https://cmake.org/licensing for details. */
6 #pragma once
7
8 #if __cplusplus >= 201402L || defined(_MSVC_LANG) && _MSVC_LANG >= 201402L
9 # define CMake_HAVE_CXX_SHARED_LOCK
10 #endif
11 #if __cplusplus >= 201703L || defined(_MSVC_LANG) && _MSVC_LANG >= 201703L
12 # define CMake_HAVE_CXX_SHARED_MUTEX
13 #endif
14
15 #if defined(CMake_HAVE_CXX_SHARED_LOCK)
16 # include <shared_mutex> // IWYU pragma: export
17 #endif
18 #if !defined(CMake_HAVE_CXX_SHARED_MUTEX)
19 # include <cm3p/uv.h>
20 #endif
21
22 namespace cm {
23 #if defined(CMake_HAVE_CXX_SHARED_MUTEX)
24 using std::shared_mutex;
25 #else
26 class shared_mutex
27 {
28 uv_rwlock_t _M_;
29
30 public:
31 using native_handle_type = uv_rwlock_t*;
32
33 shared_mutex() { uv_rwlock_init(&_M_); }
34 ~shared_mutex() { uv_rwlock_destroy(&_M_); }
35
36 shared_mutex(shared_mutex const&) = delete;
37 shared_mutex& operator=(shared_mutex const&) = delete;
38
39 void lock() { uv_rwlock_wrlock(&_M_); }
40 bool try_lock() { return uv_rwlock_trywrlock(&_M_) == 0; }
41 void unlock() { uv_rwlock_wrunlock(&_M_); }
42
43 void lock_shared() { uv_rwlock_rdlock(&_M_); }
44 void unlock_shared() { uv_rwlock_rdunlock(&_M_); }
45
46 native_handle_type native_handle() { return &_M_; }
47 };
48 #endif
49
50 #if defined(CMake_HAVE_CXX_SHARED_LOCK)
51 using std::shared_lock;
52 #else
53 template <typename T>
54 class shared_lock
55 {
56 T& _mutex;
57
58 public:
59 using mutex_type = T;
60
61 shared_lock(T& m)
62 : _mutex(m)
63 {
64 _mutex.lock_shared();
65 }
66
67 ~shared_lock() { _mutex.unlock_shared(); }
68
69 shared_lock(shared_lock const&) = delete;
70 shared_lock& operator=(shared_lock const&) = delete;
71 };
72 #endif
73 }