1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP_SHARED_MUTEX
11#define _LIBCPP_SHARED_MUTEX
12
13/*
14    shared_mutex synopsis
15
16// C++1y
17
18namespace std
19{
20
21class shared_mutex      // C++17
22{
23public:
24    shared_mutex();
25    ~shared_mutex();
26
27    shared_mutex(const shared_mutex&) = delete;
28    shared_mutex& operator=(const shared_mutex&) = delete;
29
30    // Exclusive ownership
31    void lock(); // blocking
32    bool try_lock();
33    void unlock();
34
35    // Shared ownership
36    void lock_shared(); // blocking
37    bool try_lock_shared();
38    void unlock_shared();
39
40    typedef implementation-defined native_handle_type; // See 30.2.3
41    native_handle_type native_handle(); // See 30.2.3
42};
43
44class shared_timed_mutex
45{
46public:
47    shared_timed_mutex();
48    ~shared_timed_mutex();
49
50    shared_timed_mutex(const shared_timed_mutex&) = delete;
51    shared_timed_mutex& operator=(const shared_timed_mutex&) = delete;
52
53    // Exclusive ownership
54    void lock(); // blocking
55    bool try_lock();
56    template <class Rep, class Period>
57        bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
58    template <class Clock, class Duration>
59        bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);
60    void unlock();
61
62    // Shared ownership
63    void lock_shared(); // blocking
64    bool try_lock_shared();
65    template <class Rep, class Period>
66        bool
67        try_lock_shared_for(const chrono::duration<Rep, Period>& rel_time);
68    template <class Clock, class Duration>
69        bool
70        try_lock_shared_until(const chrono::time_point<Clock, Duration>& abs_time);
71    void unlock_shared();
72};
73
74template <class Mutex>
75class shared_lock
76{
77public:
78    typedef Mutex mutex_type;
79
80    // Shared locking
81    shared_lock() noexcept;
82    explicit shared_lock(mutex_type& m); // blocking
83    shared_lock(mutex_type& m, defer_lock_t) noexcept;
84    shared_lock(mutex_type& m, try_to_lock_t);
85    shared_lock(mutex_type& m, adopt_lock_t);
86    template <class Clock, class Duration>
87        shared_lock(mutex_type& m,
88                    const chrono::time_point<Clock, Duration>& abs_time);
89    template <class Rep, class Period>
90        shared_lock(mutex_type& m,
91                    const chrono::duration<Rep, Period>& rel_time);
92    ~shared_lock();
93
94    shared_lock(shared_lock const&) = delete;
95    shared_lock& operator=(shared_lock const&) = delete;
96
97    shared_lock(shared_lock&& u) noexcept;
98    shared_lock& operator=(shared_lock&& u) noexcept;
99
100    void lock(); // blocking
101    bool try_lock();
102    template <class Rep, class Period>
103        bool try_lock_for(const chrono::duration<Rep, Period>& rel_time);
104    template <class Clock, class Duration>
105        bool try_lock_until(const chrono::time_point<Clock, Duration>& abs_time);
106    void unlock();
107
108    // Setters
109    void swap(shared_lock& u) noexcept;
110    mutex_type* release() noexcept;
111
112    // Getters
113    bool owns_lock() const noexcept;
114    explicit operator bool () const noexcept;
115    mutex_type* mutex() const noexcept;
116};
117
118template <class Mutex>
119    void swap(shared_lock<Mutex>& x, shared_lock<Mutex>& y) noexcept;
120
121}  // std
122
123*/
124
125#include <__assert> // all public C++ headers provide the assertion handler
126#include <__availability>
127#include <__chrono/duration.h>
128#include <__chrono/steady_clock.h>
129#include <__chrono/time_point.h>
130#include <__condition_variable/condition_variable.h>
131#include <__config>
132#include <__memory/addressof.h>
133#include <__mutex/mutex.h>
134#include <__mutex/tag_types.h>
135#include <__mutex/unique_lock.h>
136#include <__system_error/system_error.h>
137#include <__utility/swap.h>
138#include <cerrno>
139#include <version>
140
141_LIBCPP_PUSH_MACROS
142#include <__undef_macros>
143
144#if _LIBCPP_STD_VER >= 14
145
146#  if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
147#    pragma GCC system_header
148#  endif
149
150#  ifdef _LIBCPP_HAS_NO_THREADS
151#    error "<shared_mutex> is not supported since libc++ has been configured without support for threads."
152#  endif
153
154_LIBCPP_BEGIN_NAMESPACE_STD
155
156struct _LIBCPP_EXPORTED_FROM_ABI _LIBCPP_AVAILABILITY_SHARED_MUTEX __shared_mutex_base {
157  mutex __mut_;
158  condition_variable __gate1_;
159  condition_variable __gate2_;
160  unsigned __state_;
161
162  static const unsigned __write_entered_ = 1U << (sizeof(unsigned) * __CHAR_BIT__ - 1);
163  static const unsigned __n_readers_     = ~__write_entered_;
164
165  __shared_mutex_base();
166  _LIBCPP_HIDE_FROM_ABI ~__shared_mutex_base() = default;
167
168  __shared_mutex_base(const __shared_mutex_base&)            = delete;
169  __shared_mutex_base& operator=(const __shared_mutex_base&) = delete;
170
171  // Exclusive ownership
172  void lock(); // blocking
173  bool try_lock();
174  void unlock();
175
176  // Shared ownership
177  void lock_shared(); // blocking
178  bool try_lock_shared();
179  void unlock_shared();
180
181  //     typedef implementation-defined native_handle_type; // See 30.2.3
182  //     native_handle_type native_handle(); // See 30.2.3
183};
184
185#  if _LIBCPP_STD_VER >= 17
186class _LIBCPP_EXPORTED_FROM_ABI
187    _LIBCPP_AVAILABILITY_SHARED_MUTEX _LIBCPP_THREAD_SAFETY_ANNOTATION(__capability__("shared_mutex")) shared_mutex {
188  __shared_mutex_base __base_;
189
190public:
191  _LIBCPP_HIDE_FROM_ABI shared_mutex() : __base_() {}
192  _LIBCPP_HIDE_FROM_ABI ~shared_mutex() = default;
193
194  shared_mutex(const shared_mutex&)            = delete;
195  shared_mutex& operator=(const shared_mutex&) = delete;
196
197  // Exclusive ownership
198  _LIBCPP_HIDE_FROM_ABI void lock() _LIBCPP_THREAD_SAFETY_ANNOTATION(__acquire_capability__()) {
199    return __base_.lock();
200  }
201  _LIBCPP_HIDE_FROM_ABI bool try_lock() _LIBCPP_THREAD_SAFETY_ANNOTATION(__try_acquire_capability__(true)) {
202    return __base_.try_lock();
203  }
204  _LIBCPP_HIDE_FROM_ABI void unlock() _LIBCPP_THREAD_SAFETY_ANNOTATION(__release_capability__()) {
205    return __base_.unlock();
206  }
207
208  // Shared ownership
209  _LIBCPP_HIDE_FROM_ABI void lock_shared() _LIBCPP_THREAD_SAFETY_ANNOTATION(__acquire_shared_capability__()) {
210    return __base_.lock_shared();
211  }
212  _LIBCPP_HIDE_FROM_ABI bool try_lock_shared()
213      _LIBCPP_THREAD_SAFETY_ANNOTATION(__try_acquire_shared_capability__(true)) {
214    return __base_.try_lock_shared();
215  }
216  _LIBCPP_HIDE_FROM_ABI void unlock_shared() _LIBCPP_THREAD_SAFETY_ANNOTATION(__release_shared_capability__()) {
217    return __base_.unlock_shared();
218  }
219
220  //     typedef __shared_mutex_base::native_handle_type native_handle_type;
221  //     _LIBCPP_HIDE_FROM_ABI native_handle_type native_handle() { return __base::unlock_shared(); }
222};
223#  endif
224
225class _LIBCPP_EXPORTED_FROM_ABI _LIBCPP_AVAILABILITY_SHARED_MUTEX _LIBCPP_THREAD_SAFETY_ANNOTATION(
226    __capability__("shared_timed_mutex")) shared_timed_mutex {
227  __shared_mutex_base __base_;
228
229public:
230  shared_timed_mutex();
231  _LIBCPP_HIDE_FROM_ABI ~shared_timed_mutex() = default;
232
233  shared_timed_mutex(const shared_timed_mutex&)            = delete;
234  shared_timed_mutex& operator=(const shared_timed_mutex&) = delete;
235
236  // Exclusive ownership
237  void lock() _LIBCPP_THREAD_SAFETY_ANNOTATION(__acquire_capability__());
238  bool try_lock() _LIBCPP_THREAD_SAFETY_ANNOTATION(__try_acquire_capability__(true));
239  template <class _Rep, class _Period>
240  _LIBCPP_HIDE_FROM_ABI bool try_lock_for(const chrono::duration<_Rep, _Period>& __rel_time)
241      _LIBCPP_THREAD_SAFETY_ANNOTATION(__try_acquire_capability__(true)) {
242    return try_lock_until(chrono::steady_clock::now() + __rel_time);
243  }
244  template <class _Clock, class _Duration>
245  _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS bool
246  try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time)
247      _LIBCPP_THREAD_SAFETY_ANNOTATION(__try_acquire_capability__(true));
248  void unlock() _LIBCPP_THREAD_SAFETY_ANNOTATION(__release_capability__());
249
250  // Shared ownership
251  void lock_shared() _LIBCPP_THREAD_SAFETY_ANNOTATION(__acquire_shared_capability__());
252  bool try_lock_shared() _LIBCPP_THREAD_SAFETY_ANNOTATION(__try_acquire_shared_capability__(true));
253  template <class _Rep, class _Period>
254  _LIBCPP_HIDE_FROM_ABI bool try_lock_shared_for(const chrono::duration<_Rep, _Period>& __rel_time)
255      _LIBCPP_THREAD_SAFETY_ANNOTATION(__try_acquire_shared_capability__(true)) {
256    return try_lock_shared_until(chrono::steady_clock::now() + __rel_time);
257  }
258  template <class _Clock, class _Duration>
259  _LIBCPP_METHOD_TEMPLATE_IMPLICIT_INSTANTIATION_VIS bool
260  try_lock_shared_until(const chrono::time_point<_Clock, _Duration>& __abs_time)
261      _LIBCPP_THREAD_SAFETY_ANNOTATION(__try_acquire_shared_capability__(true));
262  void unlock_shared() _LIBCPP_THREAD_SAFETY_ANNOTATION(__release_shared_capability__());
263};
264
265template <class _Clock, class _Duration>
266bool shared_timed_mutex::try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time) {
267  unique_lock<mutex> __lk(__base_.__mut_);
268  if (__base_.__state_ & __base_.__write_entered_) {
269    while (true) {
270      cv_status __status = __base_.__gate1_.wait_until(__lk, __abs_time);
271      if ((__base_.__state_ & __base_.__write_entered_) == 0)
272        break;
273      if (__status == cv_status::timeout)
274        return false;
275    }
276  }
277  __base_.__state_ |= __base_.__write_entered_;
278  if (__base_.__state_ & __base_.__n_readers_) {
279    while (true) {
280      cv_status __status = __base_.__gate2_.wait_until(__lk, __abs_time);
281      if ((__base_.__state_ & __base_.__n_readers_) == 0)
282        break;
283      if (__status == cv_status::timeout) {
284        __base_.__state_ &= ~__base_.__write_entered_;
285        __base_.__gate1_.notify_all();
286        return false;
287      }
288    }
289  }
290  return true;
291}
292
293template <class _Clock, class _Duration>
294bool shared_timed_mutex::try_lock_shared_until(const chrono::time_point<_Clock, _Duration>& __abs_time) {
295  unique_lock<mutex> __lk(__base_.__mut_);
296  if ((__base_.__state_ & __base_.__write_entered_) ||
297      (__base_.__state_ & __base_.__n_readers_) == __base_.__n_readers_) {
298    while (true) {
299      cv_status __status = __base_.__gate1_.wait_until(__lk, __abs_time);
300      if ((__base_.__state_ & __base_.__write_entered_) == 0 &&
301          (__base_.__state_ & __base_.__n_readers_) < __base_.__n_readers_)
302        break;
303      if (__status == cv_status::timeout)
304        return false;
305    }
306  }
307  unsigned __num_readers = (__base_.__state_ & __base_.__n_readers_) + 1;
308  __base_.__state_ &= ~__base_.__n_readers_;
309  __base_.__state_ |= __num_readers;
310  return true;
311}
312
313template <class _Mutex>
314class shared_lock {
315public:
316  typedef _Mutex mutex_type;
317
318private:
319  mutex_type* __m_;
320  bool __owns_;
321
322public:
323  _LIBCPP_HIDE_FROM_ABI shared_lock() _NOEXCEPT : __m_(nullptr), __owns_(false) {}
324
325  _LIBCPP_HIDE_FROM_ABI explicit shared_lock(mutex_type& __m) : __m_(_VSTD::addressof(__m)), __owns_(true) {
326    __m_->lock_shared();
327  }
328
329  _LIBCPP_HIDE_FROM_ABI shared_lock(mutex_type& __m, defer_lock_t) _NOEXCEPT
330      : __m_(_VSTD::addressof(__m)),
331        __owns_(false) {}
332
333  _LIBCPP_HIDE_FROM_ABI shared_lock(mutex_type& __m, try_to_lock_t)
334      : __m_(_VSTD::addressof(__m)), __owns_(__m.try_lock_shared()) {}
335
336  _LIBCPP_HIDE_FROM_ABI shared_lock(mutex_type& __m, adopt_lock_t) : __m_(_VSTD::addressof(__m)), __owns_(true) {}
337
338  template <class _Clock, class _Duration>
339  _LIBCPP_HIDE_FROM_ABI shared_lock(mutex_type& __m, const chrono::time_point<_Clock, _Duration>& __abs_time)
340      : __m_(_VSTD::addressof(__m)), __owns_(__m.try_lock_shared_until(__abs_time)) {}
341
342  template <class _Rep, class _Period>
343  _LIBCPP_HIDE_FROM_ABI shared_lock(mutex_type& __m, const chrono::duration<_Rep, _Period>& __rel_time)
344      : __m_(_VSTD::addressof(__m)), __owns_(__m.try_lock_shared_for(__rel_time)) {}
345
346  _LIBCPP_HIDE_FROM_ABI ~shared_lock() {
347    if (__owns_)
348      __m_->unlock_shared();
349  }
350
351  shared_lock(shared_lock const&)            = delete;
352  shared_lock& operator=(shared_lock const&) = delete;
353
354  _LIBCPP_HIDE_FROM_ABI shared_lock(shared_lock&& __u) _NOEXCEPT : __m_(__u.__m_), __owns_(__u.__owns_) {
355    __u.__m_    = nullptr;
356    __u.__owns_ = false;
357  }
358
359  _LIBCPP_HIDE_FROM_ABI shared_lock& operator=(shared_lock&& __u) _NOEXCEPT {
360    if (__owns_)
361      __m_->unlock_shared();
362    __m_        = nullptr;
363    __owns_     = false;
364    __m_        = __u.__m_;
365    __owns_     = __u.__owns_;
366    __u.__m_    = nullptr;
367    __u.__owns_ = false;
368    return *this;
369  }
370
371  _LIBCPP_HIDE_FROM_ABI void lock();
372  _LIBCPP_HIDE_FROM_ABI bool try_lock();
373  template <class _Rep, class _Period>
374  _LIBCPP_HIDE_FROM_ABI bool try_lock_for(const chrono::duration<_Rep, _Period>& __rel_time);
375  template <class _Clock, class _Duration>
376  _LIBCPP_HIDE_FROM_ABI bool try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time);
377  _LIBCPP_HIDE_FROM_ABI void unlock();
378
379  // Setters
380  _LIBCPP_HIDE_FROM_ABI void swap(shared_lock& __u) _NOEXCEPT {
381    _VSTD::swap(__m_, __u.__m_);
382    _VSTD::swap(__owns_, __u.__owns_);
383  }
384
385  _LIBCPP_HIDE_FROM_ABI mutex_type* release() _NOEXCEPT {
386    mutex_type* __m = __m_;
387    __m_            = nullptr;
388    __owns_         = false;
389    return __m;
390  }
391
392  // Getters
393  _LIBCPP_HIDE_FROM_ABI bool owns_lock() const _NOEXCEPT { return __owns_; }
394
395  _LIBCPP_HIDE_FROM_ABI explicit operator bool() const _NOEXCEPT { return __owns_; }
396
397  _LIBCPP_HIDE_FROM_ABI mutex_type* mutex() const _NOEXCEPT { return __m_; }
398};
399_LIBCPP_CTAD_SUPPORTED_FOR_TYPE(shared_lock);
400
401template <class _Mutex>
402void shared_lock<_Mutex>::lock() {
403  if (__m_ == nullptr)
404    __throw_system_error(EPERM, "shared_lock::lock: references null mutex");
405  if (__owns_)
406    __throw_system_error(EDEADLK, "shared_lock::lock: already locked");
407  __m_->lock_shared();
408  __owns_ = true;
409}
410
411template <class _Mutex>
412bool shared_lock<_Mutex>::try_lock() {
413  if (__m_ == nullptr)
414    __throw_system_error(EPERM, "shared_lock::try_lock: references null mutex");
415  if (__owns_)
416    __throw_system_error(EDEADLK, "shared_lock::try_lock: already locked");
417  __owns_ = __m_->try_lock_shared();
418  return __owns_;
419}
420
421template <class _Mutex>
422template <class _Rep, class _Period>
423bool shared_lock<_Mutex>::try_lock_for(const chrono::duration<_Rep, _Period>& __d) {
424  if (__m_ == nullptr)
425    __throw_system_error(EPERM, "shared_lock::try_lock_for: references null mutex");
426  if (__owns_)
427    __throw_system_error(EDEADLK, "shared_lock::try_lock_for: already locked");
428  __owns_ = __m_->try_lock_shared_for(__d);
429  return __owns_;
430}
431
432template <class _Mutex>
433template <class _Clock, class _Duration>
434bool shared_lock<_Mutex>::try_lock_until(const chrono::time_point<_Clock, _Duration>& __t) {
435  if (__m_ == nullptr)
436    __throw_system_error(EPERM, "shared_lock::try_lock_until: references null mutex");
437  if (__owns_)
438    __throw_system_error(EDEADLK, "shared_lock::try_lock_until: already locked");
439  __owns_ = __m_->try_lock_shared_until(__t);
440  return __owns_;
441}
442
443template <class _Mutex>
444void shared_lock<_Mutex>::unlock() {
445  if (!__owns_)
446    __throw_system_error(EPERM, "shared_lock::unlock: not locked");
447  __m_->unlock_shared();
448  __owns_ = false;
449}
450
451template <class _Mutex>
452inline _LIBCPP_HIDE_FROM_ABI void swap(shared_lock<_Mutex>& __x, shared_lock<_Mutex>& __y) _NOEXCEPT {
453  __x.swap(__y);
454}
455
456_LIBCPP_END_NAMESPACE_STD
457
458#endif // _LIBCPP_STD_VER >= 14
459
460_LIBCPP_POP_MACROS
461
462#if !defined(_LIBCPP_REMOVE_TRANSITIVE_INCLUDES) && _LIBCPP_STD_VER <= 20
463#  include <system_error>
464#endif
465
466#endif // _LIBCPP_SHARED_MUTEX
467