shared_mutex 25 KB

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