stop_token 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. // <stop_token> -*- C++ -*-
  2. // Copyright (C) 2019-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/stop_token
  21. * This is a Standard C++ Library header.
  22. */
  23. #ifndef _GLIBCXX_STOP_TOKEN
  24. #define _GLIBCXX_STOP_TOKEN
  25. #if __cplusplus > 201703L
  26. #include <atomic>
  27. #include <bits/std_thread.h>
  28. #include <semaphore>
  29. #define __cpp_lib_jthread 201911L
  30. namespace std _GLIBCXX_VISIBILITY(default)
  31. {
  32. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  33. /// Tag type indicating a stop_source should have no shared-stop-state.
  34. struct nostopstate_t { explicit nostopstate_t() = default; };
  35. inline constexpr nostopstate_t nostopstate{};
  36. class stop_source;
  37. /// Allow testing whether a stop request has been made on a `stop_source`.
  38. class stop_token
  39. {
  40. public:
  41. stop_token() noexcept = default;
  42. stop_token(const stop_token&) noexcept = default;
  43. stop_token(stop_token&&) noexcept = default;
  44. ~stop_token() = default;
  45. stop_token&
  46. operator=(const stop_token&) noexcept = default;
  47. stop_token&
  48. operator=(stop_token&&) noexcept = default;
  49. [[nodiscard]]
  50. bool
  51. stop_possible() const noexcept
  52. {
  53. return static_cast<bool>(_M_state) && _M_state->_M_stop_possible();
  54. }
  55. [[nodiscard]]
  56. bool
  57. stop_requested() const noexcept
  58. {
  59. return static_cast<bool>(_M_state) && _M_state->_M_stop_requested();
  60. }
  61. void
  62. swap(stop_token& __rhs) noexcept
  63. { _M_state.swap(__rhs._M_state); }
  64. [[nodiscard]]
  65. friend bool
  66. operator==(const stop_token& __a, const stop_token& __b)
  67. { return __a._M_state == __b._M_state; }
  68. friend void
  69. swap(stop_token& __lhs, stop_token& __rhs) noexcept
  70. { __lhs.swap(__rhs); }
  71. private:
  72. friend class stop_source;
  73. template<typename _Callback>
  74. friend class stop_callback;
  75. static void
  76. _S_yield() noexcept
  77. {
  78. #if defined __i386__ || defined __x86_64__
  79. __builtin_ia32_pause();
  80. #endif
  81. this_thread::yield();
  82. }
  83. #ifndef __cpp_lib_semaphore
  84. struct binary_semaphore
  85. {
  86. explicit binary_semaphore(int __d) : _M_counter(__d > 0) { }
  87. void release() { _M_counter.fetch_add(1, memory_order::release); }
  88. void acquire()
  89. {
  90. int __old = 1;
  91. while (!_M_counter.compare_exchange_weak(__old, 0,
  92. memory_order::acquire,
  93. memory_order::relaxed))
  94. {
  95. __old = 1;
  96. _S_yield();
  97. }
  98. }
  99. atomic<int> _M_counter;
  100. };
  101. #endif
  102. struct _Stop_cb
  103. {
  104. using __cb_type = void(_Stop_cb*) noexcept;
  105. __cb_type* _M_callback;
  106. _Stop_cb* _M_prev = nullptr;
  107. _Stop_cb* _M_next = nullptr;
  108. bool* _M_destroyed = nullptr;
  109. binary_semaphore _M_done{0};
  110. [[__gnu__::__nonnull__]]
  111. explicit
  112. _Stop_cb(__cb_type* __cb)
  113. : _M_callback(__cb)
  114. { }
  115. void _M_run() noexcept { _M_callback(this); }
  116. };
  117. struct _Stop_state_t
  118. {
  119. using value_type = uint32_t;
  120. static constexpr value_type _S_stop_requested_bit = 1;
  121. static constexpr value_type _S_locked_bit = 2;
  122. static constexpr value_type _S_ssrc_counter_inc = 4;
  123. std::atomic<value_type> _M_owners{1};
  124. std::atomic<value_type> _M_value{_S_ssrc_counter_inc};
  125. _Stop_cb* _M_head = nullptr;
  126. std::thread::id _M_requester;
  127. _Stop_state_t() = default;
  128. bool
  129. _M_stop_possible() noexcept
  130. {
  131. // true if a stop request has already been made or there are still
  132. // stop_source objects that would allow one to be made.
  133. return _M_value.load(memory_order::acquire) & ~_S_locked_bit;
  134. }
  135. bool
  136. _M_stop_requested() noexcept
  137. {
  138. return _M_value.load(memory_order::acquire) & _S_stop_requested_bit;
  139. }
  140. void
  141. _M_add_owner() noexcept
  142. {
  143. _M_owners.fetch_add(1, memory_order::relaxed);
  144. }
  145. void
  146. _M_release_ownership() noexcept
  147. {
  148. if (_M_owners.fetch_sub(1, memory_order::acq_rel) == 1)
  149. delete this;
  150. }
  151. void
  152. _M_add_ssrc() noexcept
  153. {
  154. _M_value.fetch_add(_S_ssrc_counter_inc, memory_order::relaxed);
  155. }
  156. void
  157. _M_sub_ssrc() noexcept
  158. {
  159. _M_value.fetch_sub(_S_ssrc_counter_inc, memory_order::release);
  160. }
  161. // Obtain lock.
  162. void
  163. _M_lock() noexcept
  164. {
  165. // Can use relaxed loads to get the current value.
  166. // The successful call to _M_try_lock is an acquire operation.
  167. auto __old = _M_value.load(memory_order::relaxed);
  168. while (!_M_try_lock(__old, memory_order::relaxed))
  169. { }
  170. }
  171. // Precondition: calling thread holds the lock.
  172. void
  173. _M_unlock() noexcept
  174. {
  175. _M_value.fetch_sub(_S_locked_bit, memory_order::release);
  176. }
  177. bool
  178. _M_request_stop() noexcept
  179. {
  180. // obtain lock and set stop_requested bit
  181. auto __old = _M_value.load(memory_order::acquire);
  182. do
  183. {
  184. if (__old & _S_stop_requested_bit) // stop request already made
  185. return false;
  186. }
  187. while (!_M_try_lock_and_stop(__old));
  188. _M_requester = this_thread::get_id();
  189. while (_M_head)
  190. {
  191. bool __last_cb;
  192. _Stop_cb* __cb = _M_head;
  193. _M_head = _M_head->_M_next;
  194. if (_M_head)
  195. {
  196. _M_head->_M_prev = nullptr;
  197. __last_cb = false;
  198. }
  199. else
  200. __last_cb = true;
  201. // Allow other callbacks to be unregistered while __cb runs.
  202. _M_unlock();
  203. bool __destroyed = false;
  204. __cb->_M_destroyed = &__destroyed;
  205. // run callback
  206. __cb->_M_run();
  207. if (!__destroyed)
  208. {
  209. __cb->_M_destroyed = nullptr;
  210. // synchronize with destructor of stop_callback that owns *__cb
  211. if (!__gnu_cxx::__is_single_threaded())
  212. __cb->_M_done.release();
  213. }
  214. // Avoid relocking if we already know there are no more callbacks.
  215. if (__last_cb)
  216. return true;
  217. _M_lock();
  218. }
  219. _M_unlock();
  220. return true;
  221. }
  222. [[__gnu__::__nonnull__]]
  223. bool
  224. _M_register_callback(_Stop_cb* __cb) noexcept
  225. {
  226. auto __old = _M_value.load(memory_order::acquire);
  227. do
  228. {
  229. if (__old & _S_stop_requested_bit) // stop request already made
  230. {
  231. __cb->_M_run(); // run synchronously
  232. return false;
  233. }
  234. if (__old < _S_ssrc_counter_inc) // no stop_source owns *this
  235. // No need to register callback if no stop request can be made.
  236. // Returning false also means the stop_callback does not share
  237. // ownership of this state, but that's not observable.
  238. return false;
  239. }
  240. while (!_M_try_lock(__old));
  241. __cb->_M_next = _M_head;
  242. if (_M_head)
  243. {
  244. _M_head->_M_prev = __cb;
  245. }
  246. _M_head = __cb;
  247. _M_unlock();
  248. return true;
  249. }
  250. // Called by ~stop_callback just before destroying *__cb.
  251. [[__gnu__::__nonnull__]]
  252. void
  253. _M_remove_callback(_Stop_cb* __cb)
  254. {
  255. _M_lock();
  256. if (__cb == _M_head)
  257. {
  258. _M_head = _M_head->_M_next;
  259. if (_M_head)
  260. _M_head->_M_prev = nullptr;
  261. _M_unlock();
  262. return;
  263. }
  264. else if (__cb->_M_prev)
  265. {
  266. __cb->_M_prev->_M_next = __cb->_M_next;
  267. if (__cb->_M_next)
  268. __cb->_M_next->_M_prev = __cb->_M_prev;
  269. _M_unlock();
  270. return;
  271. }
  272. _M_unlock();
  273. // Callback is not in the list, so must have been removed by a call to
  274. // _M_request_stop.
  275. // Despite appearances there is no data race on _M_requester. The only
  276. // write to it happens before the callback is removed from the list,
  277. // and removing it from the list happens before this read.
  278. if (!(_M_requester == this_thread::get_id()))
  279. {
  280. // Synchronize with completion of callback.
  281. __cb->_M_done.acquire();
  282. // Safe for ~stop_callback to destroy *__cb now.
  283. return;
  284. }
  285. if (__cb->_M_destroyed)
  286. *__cb->_M_destroyed = true;
  287. }
  288. // Try to obtain the lock.
  289. // Returns true if the lock is acquired (with memory order acquire).
  290. // Otherwise, sets __curval = _M_value.load(__failure) and returns false.
  291. // Might fail spuriously, so must be called in a loop.
  292. bool
  293. _M_try_lock(value_type& __curval,
  294. memory_order __failure = memory_order::acquire) noexcept
  295. {
  296. return _M_do_try_lock(__curval, 0, memory_order::acquire, __failure);
  297. }
  298. // Try to obtain the lock to make a stop request.
  299. // Returns true if the lock is acquired and the _S_stop_requested_bit is
  300. // set (with memory order acq_rel so that other threads see the request).
  301. // Otherwise, sets __curval = _M_value.load(memory_order::acquire) and
  302. // returns false.
  303. // Might fail spuriously, so must be called in a loop.
  304. bool
  305. _M_try_lock_and_stop(value_type& __curval) noexcept
  306. {
  307. return _M_do_try_lock(__curval, _S_stop_requested_bit,
  308. memory_order::acq_rel, memory_order::acquire);
  309. }
  310. bool
  311. _M_do_try_lock(value_type& __curval, value_type __newbits,
  312. memory_order __success, memory_order __failure) noexcept
  313. {
  314. if (__curval & _S_locked_bit)
  315. {
  316. _S_yield();
  317. __curval = _M_value.load(__failure);
  318. return false;
  319. }
  320. __newbits |= _S_locked_bit;
  321. return _M_value.compare_exchange_weak(__curval, __curval | __newbits,
  322. __success, __failure);
  323. }
  324. };
  325. struct _Stop_state_ref
  326. {
  327. _Stop_state_ref() = default;
  328. explicit
  329. _Stop_state_ref(const stop_source&)
  330. : _M_ptr(new _Stop_state_t())
  331. { }
  332. _Stop_state_ref(const _Stop_state_ref& __other) noexcept
  333. : _M_ptr(__other._M_ptr)
  334. {
  335. if (_M_ptr)
  336. _M_ptr->_M_add_owner();
  337. }
  338. _Stop_state_ref(_Stop_state_ref&& __other) noexcept
  339. : _M_ptr(__other._M_ptr)
  340. {
  341. __other._M_ptr = nullptr;
  342. }
  343. _Stop_state_ref&
  344. operator=(const _Stop_state_ref& __other) noexcept
  345. {
  346. if (auto __ptr = __other._M_ptr; __ptr != _M_ptr)
  347. {
  348. if (__ptr)
  349. __ptr->_M_add_owner();
  350. if (_M_ptr)
  351. _M_ptr->_M_release_ownership();
  352. _M_ptr = __ptr;
  353. }
  354. return *this;
  355. }
  356. _Stop_state_ref&
  357. operator=(_Stop_state_ref&& __other) noexcept
  358. {
  359. _Stop_state_ref(std::move(__other)).swap(*this);
  360. return *this;
  361. }
  362. ~_Stop_state_ref()
  363. {
  364. if (_M_ptr)
  365. _M_ptr->_M_release_ownership();
  366. }
  367. void
  368. swap(_Stop_state_ref& __other) noexcept
  369. { std::swap(_M_ptr, __other._M_ptr); }
  370. explicit operator bool() const noexcept { return _M_ptr != nullptr; }
  371. _Stop_state_t* operator->() const noexcept { return _M_ptr; }
  372. #if __cpp_impl_three_way_comparison >= 201907L
  373. friend bool
  374. operator==(const _Stop_state_ref&, const _Stop_state_ref&) = default;
  375. #else
  376. friend bool
  377. operator==(const _Stop_state_ref& __lhs, const _Stop_state_ref& __rhs)
  378. noexcept
  379. { return __lhs._M_ptr == __rhs._M_ptr; }
  380. friend bool
  381. operator!=(const _Stop_state_ref& __lhs, const _Stop_state_ref& __rhs)
  382. noexcept
  383. { return __lhs._M_ptr != __rhs._M_ptr; }
  384. #endif
  385. private:
  386. _Stop_state_t* _M_ptr = nullptr;
  387. };
  388. _Stop_state_ref _M_state;
  389. explicit
  390. stop_token(const _Stop_state_ref& __state) noexcept
  391. : _M_state{__state}
  392. { }
  393. };
  394. /// A type that allows a stop request to be made.
  395. class stop_source
  396. {
  397. public:
  398. stop_source() : _M_state(*this)
  399. { }
  400. explicit stop_source(std::nostopstate_t) noexcept
  401. { }
  402. stop_source(const stop_source& __other) noexcept
  403. : _M_state(__other._M_state)
  404. {
  405. if (_M_state)
  406. _M_state->_M_add_ssrc();
  407. }
  408. stop_source(stop_source&&) noexcept = default;
  409. stop_source&
  410. operator=(const stop_source& __other) noexcept
  411. {
  412. if (_M_state != __other._M_state)
  413. {
  414. stop_source __sink(std::move(*this));
  415. _M_state = __other._M_state;
  416. if (_M_state)
  417. _M_state->_M_add_ssrc();
  418. }
  419. return *this;
  420. }
  421. stop_source&
  422. operator=(stop_source&&) noexcept = default;
  423. ~stop_source()
  424. {
  425. if (_M_state)
  426. _M_state->_M_sub_ssrc();
  427. }
  428. [[nodiscard]]
  429. bool
  430. stop_possible() const noexcept
  431. {
  432. return static_cast<bool>(_M_state);
  433. }
  434. [[nodiscard]]
  435. bool
  436. stop_requested() const noexcept
  437. {
  438. return static_cast<bool>(_M_state) && _M_state->_M_stop_requested();
  439. }
  440. bool
  441. request_stop() const noexcept
  442. {
  443. if (stop_possible())
  444. return _M_state->_M_request_stop();
  445. return false;
  446. }
  447. [[nodiscard]]
  448. stop_token
  449. get_token() const noexcept
  450. {
  451. return stop_token{_M_state};
  452. }
  453. void
  454. swap(stop_source& __other) noexcept
  455. {
  456. _M_state.swap(__other._M_state);
  457. }
  458. [[nodiscard]]
  459. friend bool
  460. operator==(const stop_source& __a, const stop_source& __b) noexcept
  461. {
  462. return __a._M_state == __b._M_state;
  463. }
  464. friend void
  465. swap(stop_source& __lhs, stop_source& __rhs) noexcept
  466. {
  467. __lhs.swap(__rhs);
  468. }
  469. private:
  470. stop_token::_Stop_state_ref _M_state;
  471. };
  472. /// A wrapper for callbacks to be run when a stop request is made.
  473. template<typename _Callback>
  474. class [[nodiscard]] stop_callback
  475. {
  476. static_assert(is_nothrow_destructible_v<_Callback>);
  477. static_assert(is_invocable_v<_Callback>);
  478. public:
  479. using callback_type = _Callback;
  480. template<typename _Cb,
  481. enable_if_t<is_constructible_v<_Callback, _Cb>, int> = 0>
  482. explicit
  483. stop_callback(const stop_token& __token, _Cb&& __cb)
  484. noexcept(is_nothrow_constructible_v<_Callback, _Cb>)
  485. : _M_cb(std::forward<_Cb>(__cb))
  486. {
  487. if (auto __state = __token._M_state)
  488. {
  489. if (__state->_M_register_callback(&_M_cb))
  490. _M_state.swap(__state);
  491. }
  492. }
  493. template<typename _Cb,
  494. enable_if_t<is_constructible_v<_Callback, _Cb>, int> = 0>
  495. explicit
  496. stop_callback(stop_token&& __token, _Cb&& __cb)
  497. noexcept(is_nothrow_constructible_v<_Callback, _Cb>)
  498. : _M_cb(std::forward<_Cb>(__cb))
  499. {
  500. if (auto& __state = __token._M_state)
  501. {
  502. if (__state->_M_register_callback(&_M_cb))
  503. _M_state.swap(__state);
  504. }
  505. }
  506. ~stop_callback()
  507. {
  508. if (_M_state)
  509. {
  510. _M_state->_M_remove_callback(&_M_cb);
  511. }
  512. }
  513. stop_callback(const stop_callback&) = delete;
  514. stop_callback& operator=(const stop_callback&) = delete;
  515. stop_callback(stop_callback&&) = delete;
  516. stop_callback& operator=(stop_callback&&) = delete;
  517. private:
  518. struct _Cb_impl : stop_token::_Stop_cb
  519. {
  520. template<typename _Cb>
  521. explicit
  522. _Cb_impl(_Cb&& __cb)
  523. : _Stop_cb(&_S_execute),
  524. _M_cb(std::forward<_Cb>(__cb))
  525. { }
  526. _Callback _M_cb;
  527. [[__gnu__::__nonnull__]]
  528. static void
  529. _S_execute(_Stop_cb* __that) noexcept
  530. {
  531. _Callback& __cb = static_cast<_Cb_impl*>(__that)->_M_cb;
  532. std::forward<_Callback>(__cb)();
  533. }
  534. };
  535. _Cb_impl _M_cb;
  536. stop_token::_Stop_state_ref _M_state;
  537. };
  538. template<typename _Callback>
  539. stop_callback(stop_token, _Callback) -> stop_callback<_Callback>;
  540. _GLIBCXX_END_NAMESPACE_VERSION
  541. } // namespace
  542. #endif // __cplusplus > 201703L
  543. #endif // _GLIBCXX_STOP_TOKEN