condition_variable 13 KB

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