libstdc++
shared_mutex
Go to the documentation of this file.
1// <shared_mutex> -*- C++ -*-
2
3// Copyright (C) 2013-2022 Free Software Foundation, Inc.
4//
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)
9// any later version.
10
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.
15
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.
19
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/>.
24
25/** @file include/shared_mutex
26 * This is a Standard C++ Library header.
27 */
28
29#ifndef _GLIBCXX_SHARED_MUTEX
30#define _GLIBCXX_SHARED_MUTEX 1
31
32#pragma GCC system_header
33
34#include <bits/requires_hosted.h> // concurrency
35
36#if __cplusplus >= 201402L
37
38#include <bits/chrono.h>
39#include <bits/functexcept.h>
40#include <bits/move.h> // move, __exchange
41#include <bits/std_mutex.h> // defer_lock_t
42
43#if ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK)
44# include <condition_variable>
45#endif
46
47namespace std _GLIBCXX_VISIBILITY(default)
48{
49_GLIBCXX_BEGIN_NAMESPACE_VERSION
50
51 /**
52 * @addtogroup mutexes
53 * @{
54 */
55
56#ifdef _GLIBCXX_HAS_GTHREADS
57
58#if __cplusplus >= 201703L
59#define __cpp_lib_shared_mutex 201505L
60 class shared_mutex;
61#endif
62
63#define __cpp_lib_shared_timed_mutex 201402L
64 class shared_timed_mutex;
65
66 /// @cond undocumented
67
68#if _GLIBCXX_USE_PTHREAD_RWLOCK_T
69#ifdef __gthrw
70#define _GLIBCXX_GTHRW(name) \
71 __gthrw(pthread_ ## name); \
72 static inline int \
73 __glibcxx_ ## name (pthread_rwlock_t *__rwlock) \
74 { \
75 if (__gthread_active_p ()) \
76 return __gthrw_(pthread_ ## name) (__rwlock); \
77 else \
78 return 0; \
79 }
80 _GLIBCXX_GTHRW(rwlock_rdlock)
81 _GLIBCXX_GTHRW(rwlock_tryrdlock)
82 _GLIBCXX_GTHRW(rwlock_wrlock)
83 _GLIBCXX_GTHRW(rwlock_trywrlock)
84 _GLIBCXX_GTHRW(rwlock_unlock)
85# ifndef PTHREAD_RWLOCK_INITIALIZER
86 _GLIBCXX_GTHRW(rwlock_destroy)
87 __gthrw(pthread_rwlock_init);
88 static inline int
89 __glibcxx_rwlock_init (pthread_rwlock_t *__rwlock)
90 {
91 if (__gthread_active_p ())
92 return __gthrw_(pthread_rwlock_init) (__rwlock, NULL);
93 else
94 return 0;
95 }
96# endif
97# if _GTHREAD_USE_MUTEX_TIMEDLOCK
98 __gthrw(pthread_rwlock_timedrdlock);
99 static inline int
100 __glibcxx_rwlock_timedrdlock (pthread_rwlock_t *__rwlock,
101 const timespec *__ts)
102 {
103 if (__gthread_active_p ())
104 return __gthrw_(pthread_rwlock_timedrdlock) (__rwlock, __ts);
105 else
106 return 0;
107 }
108 __gthrw(pthread_rwlock_timedwrlock);
109 static inline int
110 __glibcxx_rwlock_timedwrlock (pthread_rwlock_t *__rwlock,
111 const timespec *__ts)
112 {
113 if (__gthread_active_p ())
114 return __gthrw_(pthread_rwlock_timedwrlock) (__rwlock, __ts);
115 else
116 return 0;
117 }
118# endif
119#else
120 static inline int
121 __glibcxx_rwlock_rdlock (pthread_rwlock_t *__rwlock)
122 { return pthread_rwlock_rdlock (__rwlock); }
123 static inline int
124 __glibcxx_rwlock_tryrdlock (pthread_rwlock_t *__rwlock)
125 { return pthread_rwlock_tryrdlock (__rwlock); }
126 static inline int
127 __glibcxx_rwlock_wrlock (pthread_rwlock_t *__rwlock)
128 { return pthread_rwlock_wrlock (__rwlock); }
129 static inline int
130 __glibcxx_rwlock_trywrlock (pthread_rwlock_t *__rwlock)
131 { return pthread_rwlock_trywrlock (__rwlock); }
132 static inline int
133 __glibcxx_rwlock_unlock (pthread_rwlock_t *__rwlock)
134 { return pthread_rwlock_unlock (__rwlock); }
135 static inline int
136 __glibcxx_rwlock_destroy(pthread_rwlock_t *__rwlock)
137 { return pthread_rwlock_destroy (__rwlock); }
138 static inline int
139 __glibcxx_rwlock_init(pthread_rwlock_t *__rwlock)
140 { return pthread_rwlock_init (__rwlock, NULL); }
141# if _GTHREAD_USE_MUTEX_TIMEDLOCK
142 static inline int
143 __glibcxx_rwlock_timedrdlock (pthread_rwlock_t *__rwlock,
144 const timespec *__ts)
145 { return pthread_rwlock_timedrdlock (__rwlock, __ts); }
146 static inline int
147 __glibcxx_rwlock_timedwrlock (pthread_rwlock_t *__rwlock,
148 const timespec *__ts)
149 { return pthread_rwlock_timedwrlock (__rwlock, __ts); }
150# endif
151#endif
152
153 /// A shared mutex type implemented using pthread_rwlock_t.
154 class __shared_mutex_pthread
155 {
156 friend class shared_timed_mutex;
157
158#ifdef PTHREAD_RWLOCK_INITIALIZER
159 pthread_rwlock_t _M_rwlock = PTHREAD_RWLOCK_INITIALIZER;
160
161 public:
162 __shared_mutex_pthread() = default;
163 ~__shared_mutex_pthread() = default;
164#else
165 pthread_rwlock_t _M_rwlock;
166
167 public:
168 __shared_mutex_pthread()
169 {
170 int __ret = __glibcxx_rwlock_init(&_M_rwlock);
171 if (__ret == ENOMEM)
172 __throw_bad_alloc();
173 else if (__ret == EAGAIN)
174 __throw_system_error(int(errc::resource_unavailable_try_again));
175 else if (__ret == EPERM)
176 __throw_system_error(int(errc::operation_not_permitted));
177 // Errors not handled: EBUSY, EINVAL
178 __glibcxx_assert(__ret == 0);
179 }
180
181 ~__shared_mutex_pthread()
182 {
183 int __ret __attribute((__unused__)) = __glibcxx_rwlock_destroy(&_M_rwlock);
184 // Errors not handled: EBUSY, EINVAL
185 __glibcxx_assert(__ret == 0);
186 }
187#endif
188
189 __shared_mutex_pthread(const __shared_mutex_pthread&) = delete;
190 __shared_mutex_pthread& operator=(const __shared_mutex_pthread&) = delete;
191
192 void
193 lock()
194 {
195 int __ret = __glibcxx_rwlock_wrlock(&_M_rwlock);
196 if (__ret == EDEADLK)
197 __throw_system_error(int(errc::resource_deadlock_would_occur));
198 // Errors not handled: EINVAL
199 __glibcxx_assert(__ret == 0);
200 }
201
202 bool
203 try_lock()
204 {
205 int __ret = __glibcxx_rwlock_trywrlock(&_M_rwlock);
206 if (__ret == EBUSY) return false;
207 // Errors not handled: EINVAL
208 __glibcxx_assert(__ret == 0);
209 return true;
210 }
211
212 void
213 unlock()
214 {
215 int __ret __attribute((__unused__)) = __glibcxx_rwlock_unlock(&_M_rwlock);
216 // Errors not handled: EPERM, EBUSY, EINVAL
217 __glibcxx_assert(__ret == 0);
218 }
219
220 // Shared ownership
221
222 void
223 lock_shared()
224 {
225 int __ret;
226 // We retry if we exceeded the maximum number of read locks supported by
227 // the POSIX implementation; this can result in busy-waiting, but this
228 // is okay based on the current specification of forward progress
229 // guarantees by the standard.
230 do
231 __ret = __glibcxx_rwlock_rdlock(&_M_rwlock);
232 while (__ret == EAGAIN);
233 if (__ret == EDEADLK)
234 __throw_system_error(int(errc::resource_deadlock_would_occur));
235 // Errors not handled: EINVAL
236 __glibcxx_assert(__ret == 0);
237 }
238
239 bool
240 try_lock_shared()
241 {
242 int __ret = __glibcxx_rwlock_tryrdlock(&_M_rwlock);
243 // If the maximum number of read locks has been exceeded, we just fail
244 // to acquire the lock. Unlike for lock(), we are not allowed to throw
245 // an exception.
246 if (__ret == EBUSY || __ret == EAGAIN) return false;
247 // Errors not handled: EINVAL
248 __glibcxx_assert(__ret == 0);
249 return true;
250 }
251
252 void
253 unlock_shared()
254 {
255 unlock();
256 }
257
258 void* native_handle() { return &_M_rwlock; }
259 };
260#endif
261
262#if ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK)
263 /// A shared mutex type implemented using std::condition_variable.
264 class __shared_mutex_cv
265 {
266 friend class shared_timed_mutex;
267
268 // Based on Howard Hinnant's reference implementation from N2406.
269
270 // The high bit of _M_state is the write-entered flag which is set to
271 // indicate a writer has taken the lock or is queuing to take the lock.
272 // The remaining bits are the count of reader locks.
273 //
274 // To take a reader lock, block on gate1 while the write-entered flag is
275 // set or the maximum number of reader locks is held, then increment the
276 // reader lock count.
277 // To release, decrement the count, then if the write-entered flag is set
278 // and the count is zero then signal gate2 to wake a queued writer,
279 // otherwise if the maximum number of reader locks was held signal gate1
280 // to wake a reader.
281 //
282 // To take a writer lock, block on gate1 while the write-entered flag is
283 // set, then set the write-entered flag to start queueing, then block on
284 // gate2 while the number of reader locks is non-zero.
285 // To release, unset the write-entered flag and signal gate1 to wake all
286 // blocked readers and writers.
287 //
288 // This means that when no reader locks are held readers and writers get
289 // equal priority. When one or more reader locks is held a writer gets
290 // priority and no more reader locks can be taken while the writer is
291 // queued.
292
293 // Only locked when accessing _M_state or waiting on condition variables.
294 mutex _M_mut;
295 // Used to block while write-entered is set or reader count at maximum.
296 condition_variable _M_gate1;
297 // Used to block queued writers while reader count is non-zero.
298 condition_variable _M_gate2;
299 // The write-entered flag and reader count.
300 unsigned _M_state;
301
302 static constexpr unsigned _S_write_entered
303 = 1U << (sizeof(unsigned)*__CHAR_BIT__ - 1);
304 static constexpr unsigned _S_max_readers = ~_S_write_entered;
305
306 // Test whether the write-entered flag is set. _M_mut must be locked.
307 bool _M_write_entered() const { return _M_state & _S_write_entered; }
308
309 // The number of reader locks currently held. _M_mut must be locked.
310 unsigned _M_readers() const { return _M_state & _S_max_readers; }
311
312 public:
313 __shared_mutex_cv() : _M_state(0) {}
314
315 ~__shared_mutex_cv()
316 {
317 __glibcxx_assert( _M_state == 0 );
318 }
319
320 __shared_mutex_cv(const __shared_mutex_cv&) = delete;
321 __shared_mutex_cv& operator=(const __shared_mutex_cv&) = delete;
322
323 // Exclusive ownership
324
325 void
326 lock()
327 {
328 unique_lock<mutex> __lk(_M_mut);
329 // Wait until we can set the write-entered flag.
330 _M_gate1.wait(__lk, [=]{ return !_M_write_entered(); });
331 _M_state |= _S_write_entered;
332 // Then wait until there are no more readers.
333 _M_gate2.wait(__lk, [=]{ return _M_readers() == 0; });
334 }
335
336 bool
337 try_lock()
338 {
339 unique_lock<mutex> __lk(_M_mut, try_to_lock);
340 if (__lk.owns_lock() && _M_state == 0)
341 {
342 _M_state = _S_write_entered;
343 return true;
344 }
345 return false;
346 }
347
348 void
349 unlock()
350 {
351 lock_guard<mutex> __lk(_M_mut);
352 __glibcxx_assert( _M_write_entered() );
353 _M_state = 0;
354 // call notify_all() while mutex is held so that another thread can't
355 // lock and unlock the mutex then destroy *this before we make the call.
356 _M_gate1.notify_all();
357 }
358
359 // Shared ownership
360
361 void
362 lock_shared()
363 {
364 unique_lock<mutex> __lk(_M_mut);
365 _M_gate1.wait(__lk, [=]{ return _M_state < _S_max_readers; });
366 ++_M_state;
367 }
368
369 bool
370 try_lock_shared()
371 {
372 unique_lock<mutex> __lk(_M_mut, try_to_lock);
373 if (!__lk.owns_lock())
374 return false;
375 if (_M_state < _S_max_readers)
376 {
377 ++_M_state;
378 return true;
379 }
380 return false;
381 }
382
383 void
384 unlock_shared()
385 {
386 lock_guard<mutex> __lk(_M_mut);
387 __glibcxx_assert( _M_readers() > 0 );
388 auto __prev = _M_state--;
389 if (_M_write_entered())
390 {
391 // Wake the queued writer if there are no more readers.
392 if (_M_readers() == 0)
393 _M_gate2.notify_one();
394 // No need to notify gate1 because we give priority to the queued
395 // writer, and that writer will eventually notify gate1 after it
396 // clears the write-entered flag.
397 }
398 else
399 {
400 // Wake any thread that was blocked on reader overflow.
401 if (__prev == _S_max_readers)
402 _M_gate1.notify_one();
403 }
404 }
405 };
406#endif
407 /// @endcond
408
409#if __cplusplus >= 201703L
410 /// The standard shared mutex type.
412 {
413 public:
414 shared_mutex() = default;
415 ~shared_mutex() = default;
416
417 shared_mutex(const shared_mutex&) = delete;
418 shared_mutex& operator=(const shared_mutex&) = delete;
419
420 // Exclusive ownership
421
422 void lock() { _M_impl.lock(); }
423 bool try_lock() { return _M_impl.try_lock(); }
424 void unlock() { _M_impl.unlock(); }
425
426 // Shared ownership
427
428 void lock_shared() { _M_impl.lock_shared(); }
429 bool try_lock_shared() { return _M_impl.try_lock_shared(); }
430 void unlock_shared() { _M_impl.unlock_shared(); }
431
432#if _GLIBCXX_USE_PTHREAD_RWLOCK_T
433 typedef void* native_handle_type;
434 native_handle_type native_handle() { return _M_impl.native_handle(); }
435
436 private:
437 __shared_mutex_pthread _M_impl;
438#else
439 private:
440 __shared_mutex_cv _M_impl;
441#endif
442 };
443#endif // C++17
444
445 /// @cond undocumented
446#if _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK
447 using __shared_timed_mutex_base = __shared_mutex_pthread;
448#else
449 using __shared_timed_mutex_base = __shared_mutex_cv;
450#endif
451 /// @endcond
452
453 /// The standard shared timed mutex type.
455 : private __shared_timed_mutex_base
456 {
457 using _Base = __shared_timed_mutex_base;
458
459 // Must use the same clock as condition_variable for __shared_mutex_cv.
460#ifdef _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK
462#else
464#endif
465
466 public:
467 shared_timed_mutex() = default;
468 ~shared_timed_mutex() = default;
469
470 shared_timed_mutex(const shared_timed_mutex&) = delete;
471 shared_timed_mutex& operator=(const shared_timed_mutex&) = delete;
472
473 // Exclusive ownership
474
475 void lock() { _Base::lock(); }
476 bool try_lock() { return _Base::try_lock(); }
477 void unlock() { _Base::unlock(); }
478
479 template<typename _Rep, typename _Period>
480 bool
481 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
482 {
483 auto __rt = chrono::duration_cast<__clock_t::duration>(__rtime);
485 ++__rt;
486 return try_lock_until(__clock_t::now() + __rt);
487 }
488
489 // Shared ownership
490
491 void lock_shared() { _Base::lock_shared(); }
492 bool try_lock_shared() { return _Base::try_lock_shared(); }
493 void unlock_shared() { _Base::unlock_shared(); }
494
495 template<typename _Rep, typename _Period>
496 bool
497 try_lock_shared_for(const chrono::duration<_Rep, _Period>& __rtime)
498 {
499 auto __rt = chrono::duration_cast<__clock_t::duration>(__rtime);
501 ++__rt;
502 return try_lock_shared_until(__clock_t::now() + __rt);
503 }
504
505#if _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK
506
507 // Exclusive ownership
508
509 template<typename _Duration>
510 bool
511 try_lock_until(const chrono::time_point<chrono::system_clock,
512 _Duration>& __atime)
513 {
514 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
515 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
516
517 __gthread_time_t __ts =
518 {
519 static_cast<std::time_t>(__s.time_since_epoch().count()),
520 static_cast<long>(__ns.count())
521 };
522
523 int __ret = __glibcxx_rwlock_timedwrlock(&_M_rwlock, &__ts);
524 // On self-deadlock, we just fail to acquire the lock. Technically,
525 // the program violated the precondition.
526 if (__ret == ETIMEDOUT || __ret == EDEADLK)
527 return false;
528 // Errors not handled: EINVAL
529 __glibcxx_assert(__ret == 0);
530 return true;
531 }
532
533#ifdef _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK
534 template<typename _Duration>
535 bool
536 try_lock_until(const chrono::time_point<chrono::steady_clock,
537 _Duration>& __atime)
538 {
539 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
540 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
541
542 __gthread_time_t __ts =
543 {
544 static_cast<std::time_t>(__s.time_since_epoch().count()),
545 static_cast<long>(__ns.count())
546 };
547
548 int __ret = pthread_rwlock_clockwrlock(&_M_rwlock, CLOCK_MONOTONIC,
549 &__ts);
550 // On self-deadlock, we just fail to acquire the lock. Technically,
551 // the program violated the precondition.
552 if (__ret == ETIMEDOUT || __ret == EDEADLK)
553 return false;
554 // Errors not handled: EINVAL
555 __glibcxx_assert(__ret == 0);
556 return true;
557 }
558#endif
559
560 template<typename _Clock, typename _Duration>
561 bool
562 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
563 {
564#if __cplusplus > 201703L
565 static_assert(chrono::is_clock_v<_Clock>);
566#endif
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();
571 do {
572 auto __rtime = __atime - __now;
573 if (try_lock_for(__rtime))
574 return true;
575 __now = _Clock::now();
576 } while (__atime > __now);
577 return false;
578 }
579
580 // Shared ownership
581
582 template<typename _Duration>
583 bool
584 try_lock_shared_until(const chrono::time_point<chrono::system_clock,
585 _Duration>& __atime)
586 {
587 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
588 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
589
590 __gthread_time_t __ts =
591 {
592 static_cast<std::time_t>(__s.time_since_epoch().count()),
593 static_cast<long>(__ns.count())
594 };
595
596 int __ret;
597 // Unlike for lock(), we are not allowed to throw an exception so if
598 // the maximum number of read locks has been exceeded, or we would
599 // deadlock, we just try to acquire the lock again (and will time out
600 // eventually).
601 // In cases where we would exceed the maximum number of read locks
602 // throughout the whole time until the timeout, we will fail to
603 // acquire the lock even if it would be logically free; however, this
604 // is allowed by the standard, and we made a "strong effort"
605 // (see C++14 30.4.1.4p26).
606 // For cases where the implementation detects a deadlock we
607 // intentionally block and timeout so that an early return isn't
608 // mistaken for a spurious failure, which might help users realise
609 // there is a deadlock.
610 do
611 __ret = __glibcxx_rwlock_timedrdlock(&_M_rwlock, &__ts);
612 while (__ret == EAGAIN || __ret == EDEADLK);
613 if (__ret == ETIMEDOUT)
614 return false;
615 // Errors not handled: EINVAL
616 __glibcxx_assert(__ret == 0);
617 return true;
618 }
619
620#ifdef _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK
621 template<typename _Duration>
622 bool
623 try_lock_shared_until(const chrono::time_point<chrono::steady_clock,
624 _Duration>& __atime)
625 {
626 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
627 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
628
629 __gthread_time_t __ts =
630 {
631 static_cast<std::time_t>(__s.time_since_epoch().count()),
632 static_cast<long>(__ns.count())
633 };
634
635 int __ret = pthread_rwlock_clockrdlock(&_M_rwlock, CLOCK_MONOTONIC,
636 &__ts);
637 // On self-deadlock, we just fail to acquire the lock. Technically,
638 // the program violated the precondition.
639 if (__ret == ETIMEDOUT || __ret == EDEADLK)
640 return false;
641 // Errors not handled: EINVAL
642 __glibcxx_assert(__ret == 0);
643 return true;
644 }
645#endif
646
647 template<typename _Clock, typename _Duration>
648 bool
649 try_lock_shared_until(const chrono::time_point<_Clock,
650 _Duration>& __atime)
651 {
652#if __cplusplus > 201703L
653 static_assert(chrono::is_clock_v<_Clock>);
654#endif
655 // The user-supplied clock may not tick at the same rate as
656 // steady_clock, so we must loop in order to guarantee that
657 // the timeout has expired before returning false.
658 typename _Clock::time_point __now = _Clock::now();
659 do {
660 auto __rtime = __atime - __now;
661 if (try_lock_shared_for(__rtime))
662 return true;
663 __now = _Clock::now();
664 } while (__atime > __now);
665 return false;
666 }
667
668#else // ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK)
669
670 // Exclusive ownership
671
672 template<typename _Clock, typename _Duration>
673 bool
674 try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time)
675 {
676 unique_lock<mutex> __lk(_M_mut);
677 if (!_M_gate1.wait_until(__lk, __abs_time,
678 [=]{ return !_M_write_entered(); }))
679 {
680 return false;
681 }
682 _M_state |= _S_write_entered;
683 if (!_M_gate2.wait_until(__lk, __abs_time,
684 [=]{ return _M_readers() == 0; }))
685 {
686 _M_state ^= _S_write_entered;
687 // Wake all threads blocked while the write-entered flag was set.
688 _M_gate1.notify_all();
689 return false;
690 }
691 return true;
692 }
693
694 // Shared ownership
695
696 template <typename _Clock, typename _Duration>
697 bool
698 try_lock_shared_until(const chrono::time_point<_Clock,
699 _Duration>& __abs_time)
700 {
701 unique_lock<mutex> __lk(_M_mut);
702 if (!_M_gate1.wait_until(__lk, __abs_time,
703 [=]{ return _M_state < _S_max_readers; }))
704 {
705 return false;
706 }
707 ++_M_state;
708 return true;
709 }
710
711#endif // _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK
712 };
713#endif // _GLIBCXX_HAS_GTHREADS
714
715 /// shared_lock
716 template<typename _Mutex>
718 {
719 public:
720 typedef _Mutex mutex_type;
721
722 // Shared locking
723
724 shared_lock() noexcept : _M_pm(nullptr), _M_owns(false) { }
725
726 explicit
727 shared_lock(mutex_type& __m)
728 : _M_pm(std::__addressof(__m)), _M_owns(true)
729 { __m.lock_shared(); }
730
731 shared_lock(mutex_type& __m, defer_lock_t) noexcept
732 : _M_pm(std::__addressof(__m)), _M_owns(false) { }
733
734 shared_lock(mutex_type& __m, try_to_lock_t)
735 : _M_pm(std::__addressof(__m)), _M_owns(__m.try_lock_shared()) { }
736
737 shared_lock(mutex_type& __m, adopt_lock_t)
738 : _M_pm(std::__addressof(__m)), _M_owns(true) { }
739
740 template<typename _Clock, typename _Duration>
741 shared_lock(mutex_type& __m,
743 : _M_pm(std::__addressof(__m)),
744 _M_owns(__m.try_lock_shared_until(__abs_time)) { }
745
746 template<typename _Rep, typename _Period>
747 shared_lock(mutex_type& __m,
748 const chrono::duration<_Rep, _Period>& __rel_time)
749 : _M_pm(std::__addressof(__m)),
750 _M_owns(__m.try_lock_shared_for(__rel_time)) { }
751
753 {
754 if (_M_owns)
755 _M_pm->unlock_shared();
756 }
757
758 shared_lock(shared_lock const&) = delete;
759 shared_lock& operator=(shared_lock const&) = delete;
760
761 shared_lock(shared_lock&& __sl) noexcept : shared_lock()
762 { swap(__sl); }
763
765 operator=(shared_lock&& __sl) noexcept
766 {
767 shared_lock(std::move(__sl)).swap(*this);
768 return *this;
769 }
770
771 void
772 lock()
773 {
774 _M_lockable();
775 _M_pm->lock_shared();
776 _M_owns = true;
777 }
778
779 bool
780 try_lock()
781 {
782 _M_lockable();
783 return _M_owns = _M_pm->try_lock_shared();
784 }
785
786 template<typename _Rep, typename _Period>
787 bool
788 try_lock_for(const chrono::duration<_Rep, _Period>& __rel_time)
789 {
790 _M_lockable();
791 return _M_owns = _M_pm->try_lock_shared_for(__rel_time);
792 }
793
794 template<typename _Clock, typename _Duration>
795 bool
796 try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time)
797 {
798 _M_lockable();
799 return _M_owns = _M_pm->try_lock_shared_until(__abs_time);
800 }
801
802 void
803 unlock()
804 {
805 if (!_M_owns)
806 __throw_system_error(int(errc::resource_deadlock_would_occur));
807 _M_pm->unlock_shared();
808 _M_owns = false;
809 }
810
811 // Setters
812
813 void
814 swap(shared_lock& __u) noexcept
815 {
816 std::swap(_M_pm, __u._M_pm);
817 std::swap(_M_owns, __u._M_owns);
818 }
819
820 mutex_type*
821 release() noexcept
822 {
823 _M_owns = false;
824 return std::__exchange(_M_pm, nullptr);
825 }
826
827 // Getters
828
829 bool owns_lock() const noexcept { return _M_owns; }
830
831 explicit operator bool() const noexcept { return _M_owns; }
832
833 mutex_type* mutex() const noexcept { return _M_pm; }
834
835 private:
836 void
837 _M_lockable() const
838 {
839 if (_M_pm == nullptr)
840 __throw_system_error(int(errc::operation_not_permitted));
841 if (_M_owns)
842 __throw_system_error(int(errc::resource_deadlock_would_occur));
843 }
844
845 mutex_type* _M_pm;
846 bool _M_owns;
847 };
848
849 /// Swap specialization for shared_lock
850 /// @relates shared_mutex
851 template<typename _Mutex>
852 void
854 { __x.swap(__y); }
855
856 /// @} group mutexes
857_GLIBCXX_END_NAMESPACE_VERSION
858} // namespace
859
860#endif // C++14
861
862#endif // _GLIBCXX_SHARED_MUTEX
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition: move.h:104
void swap(any &__x, any &__y) noexcept
Exchange the states of two any objects.
Definition: any:429
constexpr _Tp * __addressof(_Tp &__r) noexcept
Same as C++11 std::addressof.
Definition: move.h:49
void swap(shared_lock< _Mutex > &__x, shared_lock< _Mutex > &__y) noexcept
Swap specialization for shared_lock.
Definition: shared_mutex:853
void lock(_L1 &__l1, _L2 &__l2, _L3 &... __l3)
Generic lock.
Definition: mutex:679
constexpr try_to_lock_t try_to_lock
Tag used to prevent a scoped lock from blocking if a mutex is locked.
Definition: std_mutex.h:228
int try_lock(_L1 &__l1, _L2 &__l2, _L3 &... __l3)
Generic try_lock.
Definition: mutex:620
ISO C++ entities toplevel namespace is std.
ratio_greater
Definition: ratio:417
The standard shared mutex type.
Definition: shared_mutex:412
The standard shared timed mutex type.
Definition: shared_mutex:456
shared_lock
Definition: shared_mutex:718
chrono::duration represents a distance between two points in time
Definition: chrono.h:435
chrono::time_point represents a point in time as measured by a clock
Definition: chrono.h:848
Monotonic clock.
Definition: chrono.h:1142
Do not acquire ownership of the mutex.
Definition: std_mutex.h:215
Try to acquire ownership of the mutex without blocking.
Definition: std_mutex.h:218
Assume the calling thread has already obtained mutex ownership and manage it.
Definition: std_mutex.h:222
A movable scoped lock type.
Definition: unique_lock.h:60