condition_variable 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. // <condition_variable> -*- C++ -*-
  2. // Copyright (C) 2008-2022 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/condition_variable
  21. * This is a Standard C++ Library header.
  22. */
  23. #ifndef _GLIBCXX_CONDITION_VARIABLE
  24. #define _GLIBCXX_CONDITION_VARIABLE 1
  25. #pragma GCC system_header
  26. #if __cplusplus < 201103L
  27. # include <bits/c++0x_warning.h>
  28. #else
  29. #include <bits/chrono.h>
  30. #include <bits/std_mutex.h>
  31. #include <bits/unique_lock.h>
  32. #include <bits/alloc_traits.h>
  33. #include <bits/shared_ptr.h>
  34. #include <bits/cxxabi_forced.h>
  35. #if __cplusplus > 201703L
  36. # include <stop_token>
  37. #endif
  38. #if defined(_GLIBCXX_HAS_GTHREADS)
  39. namespace std _GLIBCXX_VISIBILITY(default)
  40. {
  41. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  42. /**
  43. * @defgroup condition_variables Condition Variables
  44. * @ingroup concurrency
  45. *
  46. * Classes for condition_variable support.
  47. * @{
  48. */
  49. /// cv_status
  50. enum class cv_status { no_timeout, timeout };
  51. /// condition_variable
  52. class condition_variable
  53. {
  54. using steady_clock = chrono::steady_clock;
  55. using system_clock = chrono::system_clock;
  56. #ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
  57. using __clock_t = steady_clock;
  58. #else
  59. using __clock_t = system_clock;
  60. #endif
  61. __condvar _M_cond;
  62. public:
  63. typedef __gthread_cond_t* native_handle_type;
  64. condition_variable() noexcept;
  65. ~condition_variable() noexcept;
  66. condition_variable(const condition_variable&) = delete;
  67. condition_variable& operator=(const condition_variable&) = delete;
  68. void
  69. notify_one() noexcept;
  70. void
  71. notify_all() noexcept;
  72. void
  73. wait(unique_lock<mutex>& __lock);
  74. template<typename _Predicate>
  75. void
  76. wait(unique_lock<mutex>& __lock, _Predicate __p)
  77. {
  78. while (!__p())
  79. wait(__lock);
  80. }
  81. #ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
  82. template<typename _Duration>
  83. cv_status
  84. wait_until(unique_lock<mutex>& __lock,
  85. const chrono::time_point<steady_clock, _Duration>& __atime)
  86. { return __wait_until_impl(__lock, __atime); }
  87. #endif
  88. template<typename _Duration>
  89. cv_status
  90. wait_until(unique_lock<mutex>& __lock,
  91. const chrono::time_point<system_clock, _Duration>& __atime)
  92. { return __wait_until_impl(__lock, __atime); }
  93. template<typename _Clock, typename _Duration>
  94. cv_status
  95. wait_until(unique_lock<mutex>& __lock,
  96. const chrono::time_point<_Clock, _Duration>& __atime)
  97. {
  98. #if __cplusplus > 201703L
  99. static_assert(chrono::is_clock_v<_Clock>);
  100. #endif
  101. using __s_dur = typename __clock_t::duration;
  102. const typename _Clock::time_point __c_entry = _Clock::now();
  103. const __clock_t::time_point __s_entry = __clock_t::now();
  104. const auto __delta = __atime - __c_entry;
  105. const auto __s_atime = __s_entry +
  106. chrono::__detail::ceil<__s_dur>(__delta);
  107. if (__wait_until_impl(__lock, __s_atime) == cv_status::no_timeout)
  108. return cv_status::no_timeout;
  109. // We got a timeout when measured against __clock_t but
  110. // we need to check against the caller-supplied clock
  111. // to tell whether we should return a timeout.
  112. if (_Clock::now() < __atime)
  113. return cv_status::no_timeout;
  114. return cv_status::timeout;
  115. }
  116. template<typename _Clock, typename _Duration, typename _Predicate>
  117. bool
  118. wait_until(unique_lock<mutex>& __lock,
  119. const chrono::time_point<_Clock, _Duration>& __atime,
  120. _Predicate __p)
  121. {
  122. while (!__p())
  123. if (wait_until(__lock, __atime) == cv_status::timeout)
  124. return __p();
  125. return true;
  126. }
  127. template<typename _Rep, typename _Period>
  128. cv_status
  129. wait_for(unique_lock<mutex>& __lock,
  130. const chrono::duration<_Rep, _Period>& __rtime)
  131. {
  132. using __dur = typename steady_clock::duration;
  133. return wait_until(__lock,
  134. steady_clock::now() +
  135. chrono::__detail::ceil<__dur>(__rtime));
  136. }
  137. template<typename _Rep, typename _Period, typename _Predicate>
  138. bool
  139. wait_for(unique_lock<mutex>& __lock,
  140. const chrono::duration<_Rep, _Period>& __rtime,
  141. _Predicate __p)
  142. {
  143. using __dur = typename steady_clock::duration;
  144. return wait_until(__lock,
  145. steady_clock::now() +
  146. chrono::__detail::ceil<__dur>(__rtime),
  147. std::move(__p));
  148. }
  149. native_handle_type
  150. native_handle()
  151. { return _M_cond.native_handle(); }
  152. private:
  153. #ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
  154. template<typename _Dur>
  155. cv_status
  156. __wait_until_impl(unique_lock<mutex>& __lock,
  157. const chrono::time_point<steady_clock, _Dur>& __atime)
  158. {
  159. auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
  160. auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
  161. __gthread_time_t __ts =
  162. {
  163. static_cast<std::time_t>(__s.time_since_epoch().count()),
  164. static_cast<long>(__ns.count())
  165. };
  166. _M_cond.wait_until(*__lock.mutex(), CLOCK_MONOTONIC, __ts);
  167. return (steady_clock::now() < __atime
  168. ? cv_status::no_timeout : cv_status::timeout);
  169. }
  170. #endif
  171. template<typename _Dur>
  172. cv_status
  173. __wait_until_impl(unique_lock<mutex>& __lock,
  174. const chrono::time_point<system_clock, _Dur>& __atime)
  175. {
  176. auto __s = chrono::time_point_cast<chrono::seconds>(__atime);
  177. auto __ns = chrono::duration_cast<chrono::nanoseconds>(__atime - __s);
  178. __gthread_time_t __ts =
  179. {
  180. static_cast<std::time_t>(__s.time_since_epoch().count()),
  181. static_cast<long>(__ns.count())
  182. };
  183. _M_cond.wait_until(*__lock.mutex(), __ts);
  184. return (system_clock::now() < __atime
  185. ? cv_status::no_timeout : cv_status::timeout);
  186. }
  187. };
  188. void
  189. notify_all_at_thread_exit(condition_variable&, unique_lock<mutex>);
  190. struct __at_thread_exit_elt
  191. {
  192. __at_thread_exit_elt* _M_next;
  193. void (*_M_cb)(void*);
  194. };
  195. inline namespace _V2 {
  196. /// condition_variable_any
  197. // Like above, but mutex is not required to have try_lock.
  198. class condition_variable_any
  199. {
  200. #ifdef _GLIBCXX_USE_PTHREAD_COND_CLOCKWAIT
  201. using __clock_t = chrono::steady_clock;
  202. #else
  203. using __clock_t = chrono::system_clock;
  204. #endif
  205. condition_variable _M_cond;
  206. shared_ptr<mutex> _M_mutex;
  207. // scoped unlock - unlocks in ctor, re-locks in dtor
  208. template<typename _Lock>
  209. struct _Unlock
  210. {
  211. explicit _Unlock(_Lock& __lk) : _M_lock(__lk) { __lk.unlock(); }
  212. #pragma GCC diagnostic push
  213. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  214. ~_Unlock() noexcept(false)
  215. {
  216. if (uncaught_exception())
  217. {
  218. __try
  219. { _M_lock.lock(); }
  220. __catch(const __cxxabiv1::__forced_unwind&)
  221. { __throw_exception_again; }
  222. __catch(...)
  223. { }
  224. }
  225. else
  226. _M_lock.lock();
  227. }
  228. #pragma GCC diagnostic pop
  229. _Unlock(const _Unlock&) = delete;
  230. _Unlock& operator=(const _Unlock&) = delete;
  231. _Lock& _M_lock;
  232. };
  233. public:
  234. condition_variable_any() : _M_mutex(std::make_shared<mutex>()) { }
  235. ~condition_variable_any() = default;
  236. condition_variable_any(const condition_variable_any&) = delete;
  237. condition_variable_any& operator=(const condition_variable_any&) = delete;
  238. void
  239. notify_one() noexcept
  240. {
  241. lock_guard<mutex> __lock(*_M_mutex);
  242. _M_cond.notify_one();
  243. }
  244. void
  245. notify_all() noexcept
  246. {
  247. lock_guard<mutex> __lock(*_M_mutex);
  248. _M_cond.notify_all();
  249. }
  250. template<typename _Lock>
  251. void
  252. wait(_Lock& __lock)
  253. {
  254. shared_ptr<mutex> __mutex = _M_mutex;
  255. unique_lock<mutex> __my_lock(*__mutex);
  256. _Unlock<_Lock> __unlock(__lock);
  257. // *__mutex must be unlocked before re-locking __lock so move
  258. // ownership of *__mutex lock to an object with shorter lifetime.
  259. unique_lock<mutex> __my_lock2(std::move(__my_lock));
  260. _M_cond.wait(__my_lock2);
  261. }
  262. template<typename _Lock, typename _Predicate>
  263. void
  264. wait(_Lock& __lock, _Predicate __p)
  265. {
  266. while (!__p())
  267. wait(__lock);
  268. }
  269. template<typename _Lock, typename _Clock, typename _Duration>
  270. cv_status
  271. wait_until(_Lock& __lock,
  272. const chrono::time_point<_Clock, _Duration>& __atime)
  273. {
  274. shared_ptr<mutex> __mutex = _M_mutex;
  275. unique_lock<mutex> __my_lock(*__mutex);
  276. _Unlock<_Lock> __unlock(__lock);
  277. // *__mutex must be unlocked before re-locking __lock so move
  278. // ownership of *__mutex lock to an object with shorter lifetime.
  279. unique_lock<mutex> __my_lock2(std::move(__my_lock));
  280. return _M_cond.wait_until(__my_lock2, __atime);
  281. }
  282. template<typename _Lock, typename _Clock,
  283. typename _Duration, typename _Predicate>
  284. bool
  285. wait_until(_Lock& __lock,
  286. const chrono::time_point<_Clock, _Duration>& __atime,
  287. _Predicate __p)
  288. {
  289. while (!__p())
  290. if (wait_until(__lock, __atime) == cv_status::timeout)
  291. return __p();
  292. return true;
  293. }
  294. template<typename _Lock, typename _Rep, typename _Period>
  295. cv_status
  296. wait_for(_Lock& __lock, const chrono::duration<_Rep, _Period>& __rtime)
  297. { return wait_until(__lock, __clock_t::now() + __rtime); }
  298. template<typename _Lock, typename _Rep,
  299. typename _Period, typename _Predicate>
  300. bool
  301. wait_for(_Lock& __lock,
  302. const chrono::duration<_Rep, _Period>& __rtime, _Predicate __p)
  303. { return wait_until(__lock, __clock_t::now() + __rtime, std::move(__p)); }
  304. #ifdef __cpp_lib_jthread
  305. template <class _Lock, class _Predicate>
  306. bool wait(_Lock& __lock,
  307. stop_token __stoken,
  308. _Predicate __p)
  309. {
  310. if (__stoken.stop_requested())
  311. {
  312. return __p();
  313. }
  314. std::stop_callback __cb(__stoken, [this] { notify_all(); });
  315. shared_ptr<mutex> __mutex = _M_mutex;
  316. while (!__p())
  317. {
  318. unique_lock<mutex> __my_lock(*__mutex);
  319. if (__stoken.stop_requested())
  320. {
  321. return false;
  322. }
  323. // *__mutex must be unlocked before re-locking __lock so move
  324. // ownership of *__mutex lock to an object with shorter lifetime.
  325. _Unlock<_Lock> __unlock(__lock);
  326. unique_lock<mutex> __my_lock2(std::move(__my_lock));
  327. _M_cond.wait(__my_lock2);
  328. }
  329. return true;
  330. }
  331. template <class _Lock, class _Clock, class _Duration, class _Predicate>
  332. bool wait_until(_Lock& __lock,
  333. stop_token __stoken,
  334. const chrono::time_point<_Clock, _Duration>& __abs_time,
  335. _Predicate __p)
  336. {
  337. if (__stoken.stop_requested())
  338. {
  339. return __p();
  340. }
  341. std::stop_callback __cb(__stoken, [this] { notify_all(); });
  342. shared_ptr<mutex> __mutex = _M_mutex;
  343. while (!__p())
  344. {
  345. bool __stop;
  346. {
  347. unique_lock<mutex> __my_lock(*__mutex);
  348. if (__stoken.stop_requested())
  349. {
  350. return false;
  351. }
  352. _Unlock<_Lock> __u(__lock);
  353. unique_lock<mutex> __my_lock2(std::move(__my_lock));
  354. const auto __status = _M_cond.wait_until(__my_lock2, __abs_time);
  355. __stop = (__status == std::cv_status::timeout) || __stoken.stop_requested();
  356. }
  357. if (__stop)
  358. {
  359. return __p();
  360. }
  361. }
  362. return true;
  363. }
  364. template <class _Lock, class _Rep, class _Period, class _Predicate>
  365. bool wait_for(_Lock& __lock,
  366. stop_token __stoken,
  367. const chrono::duration<_Rep, _Period>& __rel_time,
  368. _Predicate __p)
  369. {
  370. auto __abst = std::chrono::steady_clock::now() + __rel_time;
  371. return wait_until(__lock,
  372. std::move(__stoken),
  373. __abst,
  374. std::move(__p));
  375. }
  376. #endif
  377. };
  378. } // end inline namespace
  379. /// @} group condition_variables
  380. _GLIBCXX_END_NAMESPACE_VERSION
  381. } // namespace
  382. #endif // _GLIBCXX_HAS_GTHREADS
  383. #endif // C++11
  384. #endif // _GLIBCXX_CONDITION_VARIABLE