1 // <shared_mutex> -*- C++ -*-
3 // Copyright (C) 2013-2026 Free Software Foundation, Inc.
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the
7 // terms of the GNU General Public License as published by the
8 // Free Software Foundation; either version 3, or (at your option)
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
25 /** @file include/shared_mutex
26 * This is a Standard C++ Library header.
29 #ifndef _GLIBCXX_SHARED_MUTEX
30 #define _GLIBCXX_SHARED_MUTEX 1
32 #ifdef _GLIBCXX_SYSHDR
33 #pragma GCC system_header
36 #include <bits/requires_hosted.h> // concurrency
38 #if __cplusplus >= 201402L
40 #include <bits/chrono.h>
41 #include <bits/error_constants.h>
42 #include <bits/new_throw.h>
43 #include <bits/functexcept.h>
44 #include <bits/move.h> // move, __exchange
45 #include <bits/std_mutex.h> // defer_lock_t
47 #define __glibcxx_want_shared_mutex
48 #define __glibcxx_want_shared_timed_mutex
49 #include <bits/version.h>
51 #if ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK)
52 # include <condition_variable>
55 namespace std _GLIBCXX_VISIBILITY(default)
57 _GLIBCXX_BEGIN_NAMESPACE_VERSION
64 #ifdef _GLIBCXX_HAS_GTHREADS
66 #ifdef __cpp_lib_shared_mutex // C++ >= 17 && hosted && gthread
70 class shared_timed_mutex;
72 /// @cond undocumented
74 #if _GLIBCXX_USE_PTHREAD_RWLOCK_T
76 #define _GLIBCXX_GTHRW(name) \
77 __gthrw(pthread_ ## name); \
79 __glibcxx_ ## name (pthread_rwlock_t *__rwlock) \
81 if (__gthread_active_p ()) \
82 return __gthrw_(pthread_ ## name) (__rwlock); \
86 _GLIBCXX_GTHRW(rwlock_rdlock)
87 _GLIBCXX_GTHRW(rwlock_tryrdlock)
88 _GLIBCXX_GTHRW(rwlock_wrlock)
89 _GLIBCXX_GTHRW(rwlock_trywrlock)
90 _GLIBCXX_GTHRW(rwlock_unlock)
91 # ifndef PTHREAD_RWLOCK_INITIALIZER
92 _GLIBCXX_GTHRW(rwlock_destroy)
93 __gthrw(pthread_rwlock_init);
95 __glibcxx_rwlock_init (pthread_rwlock_t *__rwlock)
97 if (__gthread_active_p ())
98 return __gthrw_(pthread_rwlock_init) (__rwlock, NULL);
103 # if _GTHREAD_USE_MUTEX_TIMEDLOCK
104 __gthrw(pthread_rwlock_timedrdlock);
106 __glibcxx_rwlock_timedrdlock (pthread_rwlock_t *__rwlock,
107 const timespec *__ts)
109 if (__gthread_active_p ())
110 return __gthrw_(pthread_rwlock_timedrdlock) (__rwlock, __ts);
114 __gthrw(pthread_rwlock_timedwrlock);
116 __glibcxx_rwlock_timedwrlock (pthread_rwlock_t *__rwlock,
117 const timespec *__ts)
119 if (__gthread_active_p ())
120 return __gthrw_(pthread_rwlock_timedwrlock) (__rwlock, __ts);
127 __glibcxx_rwlock_rdlock (pthread_rwlock_t *__rwlock)
128 { return pthread_rwlock_rdlock (__rwlock); }
130 __glibcxx_rwlock_tryrdlock (pthread_rwlock_t *__rwlock)
131 { return pthread_rwlock_tryrdlock (__rwlock); }
133 __glibcxx_rwlock_wrlock (pthread_rwlock_t *__rwlock)
134 { return pthread_rwlock_wrlock (__rwlock); }
136 __glibcxx_rwlock_trywrlock (pthread_rwlock_t *__rwlock)
137 { return pthread_rwlock_trywrlock (__rwlock); }
139 __glibcxx_rwlock_unlock (pthread_rwlock_t *__rwlock)
140 { return pthread_rwlock_unlock (__rwlock); }
142 __glibcxx_rwlock_destroy(pthread_rwlock_t *__rwlock)
143 { return pthread_rwlock_destroy (__rwlock); }
145 __glibcxx_rwlock_init(pthread_rwlock_t *__rwlock)
146 { return pthread_rwlock_init (__rwlock, NULL); }
147 # if _GTHREAD_USE_MUTEX_TIMEDLOCK
149 __glibcxx_rwlock_timedrdlock (pthread_rwlock_t *__rwlock,
150 const timespec *__ts)
151 { return pthread_rwlock_timedrdlock (__rwlock, __ts); }
153 __glibcxx_rwlock_timedwrlock (pthread_rwlock_t *__rwlock,
154 const timespec *__ts)
155 { return pthread_rwlock_timedwrlock (__rwlock, __ts); }
159 /// A shared mutex type implemented using pthread_rwlock_t.
160 class __shared_mutex_pthread
162 friend class shared_timed_mutex;
164 #ifdef PTHREAD_RWLOCK_INITIALIZER
165 pthread_rwlock_t _M_rwlock = PTHREAD_RWLOCK_INITIALIZER;
168 __shared_mutex_pthread() = default;
169 ~__shared_mutex_pthread() = default;
171 pthread_rwlock_t _M_rwlock;
174 __shared_mutex_pthread()
176 int __ret = __glibcxx_rwlock_init(&_M_rwlock);
179 else if (__ret == EAGAIN)
180 __throw_system_error(int(errc::resource_unavailable_try_again));
181 else if (__ret == EPERM)
182 __throw_system_error(int(errc::operation_not_permitted));
183 // Errors not handled: EBUSY, EINVAL
184 __glibcxx_assert(__ret == 0);
187 ~__shared_mutex_pthread()
189 int __ret __attribute((__unused__)) = __glibcxx_rwlock_destroy(&_M_rwlock);
190 // Errors not handled: EBUSY, EINVAL
191 __glibcxx_assert(__ret == 0);
195 __shared_mutex_pthread(const __shared_mutex_pthread&) = delete;
196 __shared_mutex_pthread& operator=(const __shared_mutex_pthread&) = delete;
201 int __ret = __glibcxx_rwlock_wrlock(&_M_rwlock);
202 if (__ret == EDEADLK)
203 __throw_system_error(int(errc::resource_deadlock_would_occur));
204 // Errors not handled: EINVAL
205 __glibcxx_assert(__ret == 0);
211 int __ret = __glibcxx_rwlock_trywrlock(&_M_rwlock);
216 // Errors not handled: EINVAL, EDEADLK
217 __glibcxx_assert(__ret == 0);
218 // try_lock() is not permitted to throw
225 int __ret __attribute((__unused__)) = __glibcxx_rwlock_unlock(&_M_rwlock);
226 // Errors not handled: EPERM, EBUSY, EINVAL
227 __glibcxx_assert(__ret == 0);
236 // We retry if we exceeded the maximum number of read locks supported by
237 // the POSIX implementation; this can result in busy-waiting, but this
238 // is okay based on the current specification of forward progress
239 // guarantees by the standard.
241 __ret = __glibcxx_rwlock_rdlock(&_M_rwlock);
242 while (__ret == EAGAIN);
243 if (__ret == EDEADLK)
244 __throw_system_error(int(errc::resource_deadlock_would_occur));
245 // Errors not handled: EINVAL
246 __glibcxx_assert(__ret == 0);
252 int __ret = __glibcxx_rwlock_tryrdlock(&_M_rwlock);
253 // If the maximum number of read locks has been exceeded, we just fail
254 // to acquire the lock. Unlike for lock(), we are not allowed to throw
256 if (__ret == EBUSY || __ret == EAGAIN) return false;
257 // Errors not handled: EINVAL
258 __glibcxx_assert(__ret == 0);
268 void* native_handle() { return &_M_rwlock; }
272 #if ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK)
273 /// A shared mutex type implemented using std::condition_variable.
274 class __shared_mutex_cv
276 friend class shared_timed_mutex;
278 // Based on Howard Hinnant's reference implementation from N2406.
280 // The high bit of _M_state is the write-entered flag which is set to
281 // indicate a writer has taken the lock or is queuing to take the lock.
282 // The remaining bits are the count of reader locks.
284 // To take a reader lock, block on gate1 while the write-entered flag is
285 // set or the maximum number of reader locks is held, then increment the
286 // reader lock count.
287 // To release, decrement the count, then if the write-entered flag is set
288 // and the count is zero then signal gate2 to wake a queued writer,
289 // otherwise if the maximum number of reader locks was held signal gate1
292 // To take a writer lock, block on gate1 while the write-entered flag is
293 // set, then set the write-entered flag to start queueing, then block on
294 // gate2 while the number of reader locks is non-zero.
295 // To release, unset the write-entered flag and signal gate1 to wake all
296 // blocked readers and writers.
298 // This means that when no reader locks are held readers and writers get
299 // equal priority. When one or more reader locks is held a writer gets
300 // priority and no more reader locks can be taken while the writer is
303 // Only locked when accessing _M_state or waiting on condition variables.
305 // Used to block while write-entered is set or reader count at maximum.
306 condition_variable _M_gate1;
307 // Used to block queued writers while reader count is non-zero.
308 condition_variable _M_gate2;
309 // The write-entered flag and reader count.
312 static constexpr unsigned _S_write_entered
313 = 1U << (sizeof(unsigned)*__CHAR_BIT__ - 1);
314 static constexpr unsigned _S_max_readers = ~_S_write_entered;
316 // Test whether the write-entered flag is set. _M_mut must be locked.
317 bool _M_write_entered() const { return _M_state & _S_write_entered; }
319 // The number of reader locks currently held. _M_mut must be locked.
320 unsigned _M_readers() const { return _M_state & _S_max_readers; }
323 __shared_mutex_cv() : _M_state(0) {}
327 __glibcxx_assert( _M_state == 0 );
330 __shared_mutex_cv(const __shared_mutex_cv&) = delete;
331 __shared_mutex_cv& operator=(const __shared_mutex_cv&) = delete;
333 // Exclusive ownership
338 unique_lock<mutex> __lk(_M_mut);
339 // Wait until we can set the write-entered flag.
340 _M_gate1.wait(__lk, [this]{ return !_M_write_entered(); });
341 _M_state |= _S_write_entered;
342 // Then wait until there are no more readers.
343 _M_gate2.wait(__lk, [this]{ return _M_readers() == 0; });
349 unique_lock<mutex> __lk(_M_mut, try_to_lock);
350 if (__lk.owns_lock() && _M_state == 0)
352 _M_state = _S_write_entered;
361 lock_guard<mutex> __lk(_M_mut);
362 __glibcxx_assert( _M_write_entered() );
364 // call notify_all() while mutex is held so that another thread can't
365 // lock and unlock the mutex then destroy *this before we make the call.
366 _M_gate1.notify_all();
374 unique_lock<mutex> __lk(_M_mut);
375 _M_gate1.wait(__lk, [this]{ return _M_state < _S_max_readers; });
382 unique_lock<mutex> __lk(_M_mut, try_to_lock);
383 if (!__lk.owns_lock())
385 if (_M_state < _S_max_readers)
396 lock_guard<mutex> __lk(_M_mut);
397 __glibcxx_assert( _M_readers() > 0 );
398 auto __prev = _M_state--;
399 if (_M_write_entered())
401 // Wake the queued writer if there are no more readers.
402 if (_M_readers() == 0)
403 _M_gate2.notify_one();
404 // No need to notify gate1 because we give priority to the queued
405 // writer, and that writer will eventually notify gate1 after it
406 // clears the write-entered flag.
410 // Wake any thread that was blocked on reader overflow.
411 if (__prev == _S_max_readers)
412 _M_gate1.notify_one();
419 #ifdef __cpp_lib_shared_mutex
420 /// The standard shared mutex type.
424 shared_mutex() = default;
425 ~shared_mutex() = default;
427 shared_mutex(const shared_mutex&) = delete;
428 shared_mutex& operator=(const shared_mutex&) = delete;
430 // Exclusive ownership
432 void lock() { _M_impl.lock(); }
433 [[nodiscard]] bool try_lock() { return _M_impl.try_lock(); }
434 void unlock() { _M_impl.unlock(); }
438 void lock_shared() { _M_impl.lock_shared(); }
439 [[nodiscard]] bool try_lock_shared() { return _M_impl.try_lock_shared(); }
440 void unlock_shared() { _M_impl.unlock_shared(); }
442 #if _GLIBCXX_USE_PTHREAD_RWLOCK_T
443 typedef void* native_handle_type;
444 native_handle_type native_handle() { return _M_impl.native_handle(); }
447 __shared_mutex_pthread _M_impl;
450 __shared_mutex_cv _M_impl;
453 #endif // __cpp_lib_shared_mutex
455 /// @cond undocumented
456 #if _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK
457 using __shared_timed_mutex_base = __shared_mutex_pthread;
459 using __shared_timed_mutex_base = __shared_mutex_cv;
463 /// The standard shared timed mutex type.
464 class shared_timed_mutex
465 : private __shared_timed_mutex_base
467 using _Base = __shared_timed_mutex_base;
469 // Must use the same clock as condition_variable for __shared_mutex_cv.
470 #ifdef _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK
471 using __clock_t = chrono::steady_clock;
473 using __clock_t = chrono::system_clock;
477 shared_timed_mutex() = default;
478 ~shared_timed_mutex() = default;
480 shared_timed_mutex(const shared_timed_mutex&) = delete;
481 shared_timed_mutex& operator=(const shared_timed_mutex&) = delete;
483 // Exclusive ownership
485 void lock() { _Base::lock(); }
486 _GLIBCXX_NODISCARD bool try_lock() { return _Base::try_lock(); }
487 void unlock() { _Base::unlock(); }
489 template<typename _Rep, typename _Period>
492 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
494 auto __rt = chrono::duration_cast<__clock_t::duration>(__rtime);
495 if (ratio_greater<__clock_t::period, _Period>())
497 return try_lock_until(__clock_t::now() + __rt);
502 void lock_shared() { _Base::lock_shared(); }
504 bool try_lock_shared() { return _Base::try_lock_shared(); }
505 void unlock_shared() { _Base::unlock_shared(); }
507 template<typename _Rep, typename _Period>
510 try_lock_shared_for(const chrono::duration<_Rep, _Period>& __rtime)
512 auto __rt = chrono::duration_cast<__clock_t::duration>(__rtime);
513 if (ratio_greater<__clock_t::period, _Period>())
515 return try_lock_shared_until(__clock_t::now() + __rt);
518 #if _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK
520 // Exclusive ownership
522 template<typename _Duration>
525 try_lock_until(const chrono::time_point<chrono::system_clock,
528 struct timespec __ts = chrono::__to_timeout_timespec(__atime);
529 int __ret = __glibcxx_rwlock_timedwrlock(&_M_rwlock, &__ts);
532 if (__ret == ETIMEDOUT)
534 // Errors not handled: EINVAL, EDEADLK
535 __glibcxx_assert(__ret == 0);
539 #ifdef _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK
540 template<typename _Duration>
543 try_lock_until(const chrono::time_point<chrono::steady_clock,
546 struct timespec __ts = chrono::__to_timeout_timespec(__atime);
547 int __ret = pthread_rwlock_clockwrlock(&_M_rwlock, CLOCK_MONOTONIC,
551 if (__ret == ETIMEDOUT)
553 // Errors not handled: EINVAL, EDEADLK
554 __glibcxx_assert(__ret == 0);
559 template<typename _Clock, typename _Duration>
562 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
564 #if __cplusplus > 201703L
565 static_assert(chrono::is_clock_v<_Clock>);
567 // The user-supplied clock may not tick at the same rate as
568 // steady_clock, so we must loop in order to guarantee that
569 // the timeout has expired before returning false.
570 typename _Clock::time_point __now = _Clock::now();
572 auto __rtime = __atime - __now;
573 if (try_lock_for(__rtime))
575 __now = _Clock::now();
576 } while (__atime > __now);
582 template<typename _Duration>
585 try_lock_shared_until(const chrono::time_point<chrono::system_clock,
588 struct timespec __ts = chrono::__to_timeout_timespec(__atime);
591 // Unlike for lock(), we are not allowed to throw an exception so if
592 // the maximum number of read locks has been exceeded, or we would
593 // deadlock, we just try to acquire the lock again (and will time out
595 // In cases where we would exceed the maximum number of read locks
596 // throughout the whole time until the timeout, we will fail to
597 // acquire the lock even if it would be logically free; however, this
598 // is allowed by the standard, and we made a "strong effort"
599 // (see C++14 30.4.1.4p26).
601 __ret = __glibcxx_rwlock_timedrdlock(&_M_rwlock, &__ts);
602 while (__ret == EAGAIN);
605 if (__ret == ETIMEDOUT)
607 // Errors not handled: EINVAL, EDEADLK
608 __glibcxx_assert(__ret == 0);
612 #ifdef _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK
613 template<typename _Duration>
616 try_lock_shared_until(const chrono::time_point<chrono::steady_clock,
619 struct timespec __ts = chrono::__to_timeout_timespec(__atime);
620 int __ret = pthread_rwlock_clockrdlock(&_M_rwlock, CLOCK_MONOTONIC,
622 // On self-deadlock, if _GLIBCXX_ASSERTIONS is not defined, we just
623 // fail to acquire the lock. Technically, the program violated the
627 if (__ret == ETIMEDOUT)
629 // Errors not handled: EINVAL, EDEADLK
630 __glibcxx_assert(__ret == 0);
635 template<typename _Clock, typename _Duration>
638 try_lock_shared_until(const chrono::time_point<_Clock,
641 #if __cplusplus > 201703L
642 static_assert(chrono::is_clock_v<_Clock>);
644 // The user-supplied clock may not tick at the same rate as
645 // steady_clock, so we must loop in order to guarantee that
646 // the timeout has expired before returning false.
647 typename _Clock::time_point __now = _Clock::now();
649 auto __rtime = __atime - __now;
650 if (try_lock_shared_for(__rtime))
652 __now = _Clock::now();
653 } while (__atime > __now);
657 #else // ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK)
659 // Exclusive ownership
661 template<typename _Clock, typename _Duration>
664 try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time)
666 unique_lock<mutex> __lk(_M_mut);
667 if (!_M_gate1.wait_until(__lk, __abs_time,
668 [this]{ return !_M_write_entered(); }))
672 _M_state |= _S_write_entered;
673 if (!_M_gate2.wait_until(__lk, __abs_time,
674 [this]{ return _M_readers() == 0; }))
676 _M_state ^= _S_write_entered;
677 // Wake all threads blocked while the write-entered flag was set.
678 _M_gate1.notify_all();
686 template <typename _Clock, typename _Duration>
689 try_lock_shared_until(const chrono::time_point<_Clock,
690 _Duration>& __abs_time)
692 unique_lock<mutex> __lk(_M_mut);
693 if (!_M_gate1.wait_until(__lk, __abs_time,
694 [this]{ return _M_state < _S_max_readers; }))
702 #endif // _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK
704 #endif // _GLIBCXX_HAS_GTHREADS
707 template<typename _Mutex>
711 typedef _Mutex mutex_type;
715 shared_lock() noexcept : _M_pm(nullptr), _M_owns(false) { }
718 shared_lock(mutex_type& __m)
719 : _M_pm(std::__addressof(__m)), _M_owns(true)
720 { __m.lock_shared(); }
722 shared_lock(mutex_type& __m, defer_lock_t) noexcept
723 : _M_pm(std::__addressof(__m)), _M_owns(false) { }
725 shared_lock(mutex_type& __m, try_to_lock_t)
726 : _M_pm(std::__addressof(__m)), _M_owns(__m.try_lock_shared()) { }
728 shared_lock(mutex_type& __m, adopt_lock_t)
729 : _M_pm(std::__addressof(__m)), _M_owns(true) { }
731 template<typename _Clock, typename _Duration>
732 shared_lock(mutex_type& __m,
733 const chrono::time_point<_Clock, _Duration>& __abs_time)
734 : _M_pm(std::__addressof(__m)),
735 _M_owns(__m.try_lock_shared_until(__abs_time)) { }
737 template<typename _Rep, typename _Period>
738 shared_lock(mutex_type& __m,
739 const chrono::duration<_Rep, _Period>& __rel_time)
740 : _M_pm(std::__addressof(__m)),
741 _M_owns(__m.try_lock_shared_for(__rel_time)) { }
746 _M_pm->unlock_shared();
749 shared_lock(shared_lock const&) = delete;
750 shared_lock& operator=(shared_lock const&) = delete;
752 shared_lock(shared_lock&& __sl) noexcept : shared_lock()
756 operator=(shared_lock&& __sl) noexcept
758 // _GLIBCXX_RESOLVE_LIB_DEFECTS
759 // 4172. unique_lock self-move-assignment is broken
760 shared_lock(std::move(__sl)).swap(*this);
768 _M_pm->lock_shared();
777 return _M_owns = _M_pm->try_lock_shared();
780 template<typename _Rep, typename _Period>
783 try_lock_for(const chrono::duration<_Rep, _Period>& __rel_time)
786 return _M_owns = _M_pm->try_lock_shared_for(__rel_time);
789 template<typename _Clock, typename _Duration>
792 try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time)
795 return _M_owns = _M_pm->try_lock_shared_until(__abs_time);
802 __throw_system_error(int(errc::operation_not_permitted));
803 _M_pm->unlock_shared();
810 swap(shared_lock& __u) noexcept
812 std::swap(_M_pm, __u._M_pm);
813 std::swap(_M_owns, __u._M_owns);
820 return std::__exchange(_M_pm, nullptr);
826 bool owns_lock() const noexcept { return _M_owns; }
828 explicit operator bool() const noexcept { return _M_owns; }
831 mutex_type* mutex() const noexcept { return _M_pm; }
837 if (_M_pm == nullptr)
838 __throw_system_error(int(errc::operation_not_permitted));
840 __throw_system_error(int(errc::resource_deadlock_would_occur));
847 /// Swap specialization for shared_lock
848 /// @relates shared_mutex
849 template<typename _Mutex>
851 swap(shared_lock<_Mutex>& __x, shared_lock<_Mutex>& __y) noexcept
855 _GLIBCXX_END_NAMESPACE_VERSION
860 #endif // _GLIBCXX_SHARED_MUTEX