]> git.ipfire.org Git - thirdparty/gcc.git/blob - libstdc++-v3/include/std/shared_mutex
libstdc++: Add nodiscard attribute to mutex try_lock functions
[thirdparty/gcc.git] / libstdc++-v3 / include / std / shared_mutex
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
47 namespace 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.
411 class shared_mutex
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 [[nodiscard]] 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 [[nodiscard]] 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.
454 class shared_timed_mutex
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
461 using __clock_t = chrono::steady_clock;
462 #else
463 using __clock_t = chrono::system_clock;
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 _GLIBCXX_NODISCARD bool try_lock() { return _Base::try_lock(); }
477 void unlock() { _Base::unlock(); }
478
479 template<typename _Rep, typename _Period>
480 _GLIBCXX_NODISCARD
481 bool
482 try_lock_for(const chrono::duration<_Rep, _Period>& __rtime)
483 {
484 auto __rt = chrono::duration_cast<__clock_t::duration>(__rtime);
485 if (ratio_greater<__clock_t::period, _Period>())
486 ++__rt;
487 return try_lock_until(__clock_t::now() + __rt);
488 }
489
490 // Shared ownership
491
492 void lock_shared() { _Base::lock_shared(); }
493 _GLIBCXX_NODISCARD
494 bool try_lock_shared() { return _Base::try_lock_shared(); }
495 void unlock_shared() { _Base::unlock_shared(); }
496
497 template<typename _Rep, typename _Period>
498 _GLIBCXX_NODISCARD
499 bool
500 try_lock_shared_for(const chrono::duration<_Rep, _Period>& __rtime)
501 {
502 auto __rt = chrono::duration_cast<__clock_t::duration>(__rtime);
503 if (ratio_greater<__clock_t::period, _Period>())
504 ++__rt;
505 return try_lock_shared_until(__clock_t::now() + __rt);
506 }
507
508 #if _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK
509
510 // Exclusive ownership
511
512 template<typename _Duration>
513 _GLIBCXX_NODISCARD
514 bool
515 try_lock_until(const chrono::time_point<chrono::system_clock,
516 _Duration>& __atime)
517 {
518 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
519 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
520
521 __gthread_time_t __ts =
522 {
523 static_cast<std::time_t>(__s.time_since_epoch().count()),
524 static_cast<long>(__ns.count())
525 };
526
527 int __ret = __glibcxx_rwlock_timedwrlock(&_M_rwlock, &__ts);
528 // On self-deadlock, we just fail to acquire the lock. Technically,
529 // the program violated the precondition.
530 if (__ret == ETIMEDOUT || __ret == EDEADLK)
531 return false;
532 // Errors not handled: EINVAL
533 __glibcxx_assert(__ret == 0);
534 return true;
535 }
536
537 #ifdef _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK
538 template<typename _Duration>
539 _GLIBCXX_NODISCARD
540 bool
541 try_lock_until(const chrono::time_point<chrono::steady_clock,
542 _Duration>& __atime)
543 {
544 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
545 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
546
547 __gthread_time_t __ts =
548 {
549 static_cast<std::time_t>(__s.time_since_epoch().count()),
550 static_cast<long>(__ns.count())
551 };
552
553 int __ret = pthread_rwlock_clockwrlock(&_M_rwlock, CLOCK_MONOTONIC,
554 &__ts);
555 // On self-deadlock, we just fail to acquire the lock. Technically,
556 // the program violated the precondition.
557 if (__ret == ETIMEDOUT || __ret == EDEADLK)
558 return false;
559 // Errors not handled: EINVAL
560 __glibcxx_assert(__ret == 0);
561 return true;
562 }
563 #endif
564
565 template<typename _Clock, typename _Duration>
566 _GLIBCXX_NODISCARD
567 bool
568 try_lock_until(const chrono::time_point<_Clock, _Duration>& __atime)
569 {
570 #if __cplusplus > 201703L
571 static_assert(chrono::is_clock_v<_Clock>);
572 #endif
573 // The user-supplied clock may not tick at the same rate as
574 // steady_clock, so we must loop in order to guarantee that
575 // the timeout has expired before returning false.
576 typename _Clock::time_point __now = _Clock::now();
577 do {
578 auto __rtime = __atime - __now;
579 if (try_lock_for(__rtime))
580 return true;
581 __now = _Clock::now();
582 } while (__atime > __now);
583 return false;
584 }
585
586 // Shared ownership
587
588 template<typename _Duration>
589 _GLIBCXX_NODISCARD
590 bool
591 try_lock_shared_until(const chrono::time_point<chrono::system_clock,
592 _Duration>& __atime)
593 {
594 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
595 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
596
597 __gthread_time_t __ts =
598 {
599 static_cast<std::time_t>(__s.time_since_epoch().count()),
600 static_cast<long>(__ns.count())
601 };
602
603 int __ret;
604 // Unlike for lock(), we are not allowed to throw an exception so if
605 // the maximum number of read locks has been exceeded, or we would
606 // deadlock, we just try to acquire the lock again (and will time out
607 // eventually).
608 // In cases where we would exceed the maximum number of read locks
609 // throughout the whole time until the timeout, we will fail to
610 // acquire the lock even if it would be logically free; however, this
611 // is allowed by the standard, and we made a "strong effort"
612 // (see C++14 30.4.1.4p26).
613 // For cases where the implementation detects a deadlock we
614 // intentionally block and timeout so that an early return isn't
615 // mistaken for a spurious failure, which might help users realise
616 // there is a deadlock.
617 do
618 __ret = __glibcxx_rwlock_timedrdlock(&_M_rwlock, &__ts);
619 while (__ret == EAGAIN || __ret == EDEADLK);
620 if (__ret == ETIMEDOUT)
621 return false;
622 // Errors not handled: EINVAL
623 __glibcxx_assert(__ret == 0);
624 return true;
625 }
626
627 #ifdef _GLIBCXX_USE_PTHREAD_RWLOCK_CLOCKLOCK
628 template<typename _Duration>
629 _GLIBCXX_NODISCARD
630 bool
631 try_lock_shared_until(const chrono::time_point<chrono::steady_clock,
632 _Duration>& __atime)
633 {
634 auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
635 auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
636
637 __gthread_time_t __ts =
638 {
639 static_cast<std::time_t>(__s.time_since_epoch().count()),
640 static_cast<long>(__ns.count())
641 };
642
643 int __ret = pthread_rwlock_clockrdlock(&_M_rwlock, CLOCK_MONOTONIC,
644 &__ts);
645 // On self-deadlock, we just fail to acquire the lock. Technically,
646 // the program violated the precondition.
647 if (__ret == ETIMEDOUT || __ret == EDEADLK)
648 return false;
649 // Errors not handled: EINVAL
650 __glibcxx_assert(__ret == 0);
651 return true;
652 }
653 #endif
654
655 template<typename _Clock, typename _Duration>
656 _GLIBCXX_NODISCARD
657 bool
658 try_lock_shared_until(const chrono::time_point<_Clock,
659 _Duration>& __atime)
660 {
661 #if __cplusplus > 201703L
662 static_assert(chrono::is_clock_v<_Clock>);
663 #endif
664 // The user-supplied clock may not tick at the same rate as
665 // steady_clock, so we must loop in order to guarantee that
666 // the timeout has expired before returning false.
667 typename _Clock::time_point __now = _Clock::now();
668 do {
669 auto __rtime = __atime - __now;
670 if (try_lock_shared_for(__rtime))
671 return true;
672 __now = _Clock::now();
673 } while (__atime > __now);
674 return false;
675 }
676
677 #else // ! (_GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK)
678
679 // Exclusive ownership
680
681 template<typename _Clock, typename _Duration>
682 _GLIBCXX_NODISCARD
683 bool
684 try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time)
685 {
686 unique_lock<mutex> __lk(_M_mut);
687 if (!_M_gate1.wait_until(__lk, __abs_time,
688 [=]{ return !_M_write_entered(); }))
689 {
690 return false;
691 }
692 _M_state |= _S_write_entered;
693 if (!_M_gate2.wait_until(__lk, __abs_time,
694 [=]{ return _M_readers() == 0; }))
695 {
696 _M_state ^= _S_write_entered;
697 // Wake all threads blocked while the write-entered flag was set.
698 _M_gate1.notify_all();
699 return false;
700 }
701 return true;
702 }
703
704 // Shared ownership
705
706 template <typename _Clock, typename _Duration>
707 _GLIBCXX_NODISCARD
708 bool
709 try_lock_shared_until(const chrono::time_point<_Clock,
710 _Duration>& __abs_time)
711 {
712 unique_lock<mutex> __lk(_M_mut);
713 if (!_M_gate1.wait_until(__lk, __abs_time,
714 [=]{ return _M_state < _S_max_readers; }))
715 {
716 return false;
717 }
718 ++_M_state;
719 return true;
720 }
721
722 #endif // _GLIBCXX_USE_PTHREAD_RWLOCK_T && _GTHREAD_USE_MUTEX_TIMEDLOCK
723 };
724 #endif // _GLIBCXX_HAS_GTHREADS
725
726 /// shared_lock
727 template<typename _Mutex>
728 class shared_lock
729 {
730 public:
731 typedef _Mutex mutex_type;
732
733 // Shared locking
734
735 shared_lock() noexcept : _M_pm(nullptr), _M_owns(false) { }
736
737 explicit
738 shared_lock(mutex_type& __m)
739 : _M_pm(std::__addressof(__m)), _M_owns(true)
740 { __m.lock_shared(); }
741
742 shared_lock(mutex_type& __m, defer_lock_t) noexcept
743 : _M_pm(std::__addressof(__m)), _M_owns(false) { }
744
745 shared_lock(mutex_type& __m, try_to_lock_t)
746 : _M_pm(std::__addressof(__m)), _M_owns(__m.try_lock_shared()) { }
747
748 shared_lock(mutex_type& __m, adopt_lock_t)
749 : _M_pm(std::__addressof(__m)), _M_owns(true) { }
750
751 template<typename _Clock, typename _Duration>
752 shared_lock(mutex_type& __m,
753 const chrono::time_point<_Clock, _Duration>& __abs_time)
754 : _M_pm(std::__addressof(__m)),
755 _M_owns(__m.try_lock_shared_until(__abs_time)) { }
756
757 template<typename _Rep, typename _Period>
758 shared_lock(mutex_type& __m,
759 const chrono::duration<_Rep, _Period>& __rel_time)
760 : _M_pm(std::__addressof(__m)),
761 _M_owns(__m.try_lock_shared_for(__rel_time)) { }
762
763 ~shared_lock()
764 {
765 if (_M_owns)
766 _M_pm->unlock_shared();
767 }
768
769 shared_lock(shared_lock const&) = delete;
770 shared_lock& operator=(shared_lock const&) = delete;
771
772 shared_lock(shared_lock&& __sl) noexcept : shared_lock()
773 { swap(__sl); }
774
775 shared_lock&
776 operator=(shared_lock&& __sl) noexcept
777 {
778 shared_lock(std::move(__sl)).swap(*this);
779 return *this;
780 }
781
782 void
783 lock()
784 {
785 _M_lockable();
786 _M_pm->lock_shared();
787 _M_owns = true;
788 }
789
790 _GLIBCXX_NODISCARD
791 bool
792 try_lock()
793 {
794 _M_lockable();
795 return _M_owns = _M_pm->try_lock_shared();
796 }
797
798 template<typename _Rep, typename _Period>
799 _GLIBCXX_NODISCARD
800 bool
801 try_lock_for(const chrono::duration<_Rep, _Period>& __rel_time)
802 {
803 _M_lockable();
804 return _M_owns = _M_pm->try_lock_shared_for(__rel_time);
805 }
806
807 template<typename _Clock, typename _Duration>
808 _GLIBCXX_NODISCARD
809 bool
810 try_lock_until(const chrono::time_point<_Clock, _Duration>& __abs_time)
811 {
812 _M_lockable();
813 return _M_owns = _M_pm->try_lock_shared_until(__abs_time);
814 }
815
816 void
817 unlock()
818 {
819 if (!_M_owns)
820 __throw_system_error(int(errc::resource_deadlock_would_occur));
821 _M_pm->unlock_shared();
822 _M_owns = false;
823 }
824
825 // Setters
826
827 void
828 swap(shared_lock& __u) noexcept
829 {
830 std::swap(_M_pm, __u._M_pm);
831 std::swap(_M_owns, __u._M_owns);
832 }
833
834 mutex_type*
835 release() noexcept
836 {
837 _M_owns = false;
838 return std::__exchange(_M_pm, nullptr);
839 }
840
841 // Getters
842
843 _GLIBCXX_NODISCARD
844 bool owns_lock() const noexcept { return _M_owns; }
845
846 explicit operator bool() const noexcept { return _M_owns; }
847
848 _GLIBCXX_NODISCARD
849 mutex_type* mutex() const noexcept { return _M_pm; }
850
851 private:
852 void
853 _M_lockable() const
854 {
855 if (_M_pm == nullptr)
856 __throw_system_error(int(errc::operation_not_permitted));
857 if (_M_owns)
858 __throw_system_error(int(errc::resource_deadlock_would_occur));
859 }
860
861 mutex_type* _M_pm;
862 bool _M_owns;
863 };
864
865 /// Swap specialization for shared_lock
866 /// @relates shared_mutex
867 template<typename _Mutex>
868 void
869 swap(shared_lock<_Mutex>& __x, shared_lock<_Mutex>& __y) noexcept
870 { __x.swap(__y); }
871
872 /// @} group mutexes
873 _GLIBCXX_END_NAMESPACE_VERSION
874 } // namespace
875
876 #endif // C++14
877
878 #endif // _GLIBCXX_SHARED_MUTEX