You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1769 lines
50KB

  1. // <future> -*- C++ -*-
  2. // Copyright (C) 2009-2020 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/future
  21. * This is a Standard C++ Library header.
  22. */
  23. #ifndef _GLIBCXX_FUTURE
  24. #define _GLIBCXX_FUTURE 1
  25. #pragma GCC system_header
  26. #if __cplusplus < 201103L
  27. # include <bits/c++0x_warning.h>
  28. #else
  29. #include <mutex>
  30. #include <thread>
  31. #include <condition_variable>
  32. #include <system_error>
  33. #include <atomic>
  34. #include <bits/atomic_futex.h>
  35. #include <bits/functexcept.h>
  36. #include <bits/invoke.h>
  37. #include <bits/unique_ptr.h>
  38. #include <bits/shared_ptr.h>
  39. #include <bits/std_function.h>
  40. #include <bits/uses_allocator.h>
  41. #include <bits/allocated_ptr.h>
  42. #include <ext/aligned_buffer.h>
  43. namespace std _GLIBCXX_VISIBILITY(default)
  44. {
  45. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  46. /**
  47. * @defgroup futures Futures
  48. * @ingroup concurrency
  49. *
  50. * Classes for futures support.
  51. * @{
  52. */
  53. /// Error code for futures
  54. enum class future_errc
  55. {
  56. future_already_retrieved = 1,
  57. promise_already_satisfied,
  58. no_state,
  59. broken_promise
  60. };
  61. /// Specialization.
  62. template<>
  63. struct is_error_code_enum<future_errc> : public true_type { };
  64. /// Points to a statically-allocated object derived from error_category.
  65. const error_category&
  66. future_category() noexcept;
  67. /// Overload for make_error_code.
  68. inline error_code
  69. make_error_code(future_errc __errc) noexcept
  70. { return error_code(static_cast<int>(__errc), future_category()); }
  71. /// Overload for make_error_condition.
  72. inline error_condition
  73. make_error_condition(future_errc __errc) noexcept
  74. { return error_condition(static_cast<int>(__errc), future_category()); }
  75. /**
  76. * @brief Exception type thrown by futures.
  77. * @ingroup exceptions
  78. */
  79. class future_error : public logic_error
  80. {
  81. public:
  82. explicit
  83. future_error(future_errc __errc)
  84. : future_error(std::make_error_code(__errc))
  85. { }
  86. virtual ~future_error() noexcept;
  87. virtual const char*
  88. what() const noexcept;
  89. const error_code&
  90. code() const noexcept { return _M_code; }
  91. private:
  92. explicit
  93. future_error(error_code __ec)
  94. : logic_error("std::future_error: " + __ec.message()), _M_code(__ec)
  95. { }
  96. friend void __throw_future_error(int);
  97. error_code _M_code;
  98. };
  99. // Forward declarations.
  100. template<typename _Res>
  101. class future;
  102. template<typename _Res>
  103. class shared_future;
  104. template<typename _Signature>
  105. class packaged_task;
  106. template<typename _Res>
  107. class promise;
  108. /// Launch code for futures
  109. enum class launch
  110. {
  111. async = 1,
  112. deferred = 2
  113. };
  114. constexpr launch operator&(launch __x, launch __y)
  115. {
  116. return static_cast<launch>(
  117. static_cast<int>(__x) & static_cast<int>(__y));
  118. }
  119. constexpr launch operator|(launch __x, launch __y)
  120. {
  121. return static_cast<launch>(
  122. static_cast<int>(__x) | static_cast<int>(__y));
  123. }
  124. constexpr launch operator^(launch __x, launch __y)
  125. {
  126. return static_cast<launch>(
  127. static_cast<int>(__x) ^ static_cast<int>(__y));
  128. }
  129. constexpr launch operator~(launch __x)
  130. { return static_cast<launch>(~static_cast<int>(__x)); }
  131. inline launch& operator&=(launch& __x, launch __y)
  132. { return __x = __x & __y; }
  133. inline launch& operator|=(launch& __x, launch __y)
  134. { return __x = __x | __y; }
  135. inline launch& operator^=(launch& __x, launch __y)
  136. { return __x = __x ^ __y; }
  137. /// Status code for futures
  138. enum class future_status
  139. {
  140. ready,
  141. timeout,
  142. deferred
  143. };
  144. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  145. // 2021. Further incorrect usages of result_of
  146. template<typename _Fn, typename... _Args>
  147. using __async_result_of = typename __invoke_result<
  148. typename decay<_Fn>::type, typename decay<_Args>::type...>::type;
  149. template<typename _Fn, typename... _Args>
  150. future<__async_result_of<_Fn, _Args...>>
  151. async(launch __policy, _Fn&& __fn, _Args&&... __args);
  152. template<typename _Fn, typename... _Args>
  153. future<__async_result_of<_Fn, _Args...>>
  154. async(_Fn&& __fn, _Args&&... __args);
  155. #if defined(_GLIBCXX_HAS_GTHREADS)
  156. /// Base class and enclosing scope.
  157. struct __future_base
  158. {
  159. /// Base class for results.
  160. struct _Result_base
  161. {
  162. exception_ptr _M_error;
  163. _Result_base(const _Result_base&) = delete;
  164. _Result_base& operator=(const _Result_base&) = delete;
  165. // _M_destroy() allows derived classes to control deallocation
  166. virtual void _M_destroy() = 0;
  167. struct _Deleter
  168. {
  169. void operator()(_Result_base* __fr) const { __fr->_M_destroy(); }
  170. };
  171. protected:
  172. _Result_base();
  173. virtual ~_Result_base();
  174. };
  175. /// A unique_ptr for result objects.
  176. template<typename _Res>
  177. using _Ptr = unique_ptr<_Res, _Result_base::_Deleter>;
  178. /// A result object that has storage for an object of type _Res.
  179. template<typename _Res>
  180. struct _Result : _Result_base
  181. {
  182. private:
  183. __gnu_cxx::__aligned_buffer<_Res> _M_storage;
  184. bool _M_initialized;
  185. public:
  186. typedef _Res result_type;
  187. _Result() noexcept : _M_initialized() { }
  188. ~_Result()
  189. {
  190. if (_M_initialized)
  191. _M_value().~_Res();
  192. }
  193. // Return lvalue, future will add const or rvalue-reference
  194. _Res&
  195. _M_value() noexcept { return *_M_storage._M_ptr(); }
  196. void
  197. _M_set(const _Res& __res)
  198. {
  199. ::new (_M_storage._M_addr()) _Res(__res);
  200. _M_initialized = true;
  201. }
  202. void
  203. _M_set(_Res&& __res)
  204. {
  205. ::new (_M_storage._M_addr()) _Res(std::move(__res));
  206. _M_initialized = true;
  207. }
  208. private:
  209. void _M_destroy() { delete this; }
  210. };
  211. /// A result object that uses an allocator.
  212. template<typename _Res, typename _Alloc>
  213. struct _Result_alloc final : _Result<_Res>, _Alloc
  214. {
  215. using __allocator_type = __alloc_rebind<_Alloc, _Result_alloc>;
  216. explicit
  217. _Result_alloc(const _Alloc& __a) : _Result<_Res>(), _Alloc(__a)
  218. { }
  219. private:
  220. void _M_destroy()
  221. {
  222. __allocator_type __a(*this);
  223. __allocated_ptr<__allocator_type> __guard_ptr{ __a, this };
  224. this->~_Result_alloc();
  225. }
  226. };
  227. // Create a result object that uses an allocator.
  228. template<typename _Res, typename _Allocator>
  229. static _Ptr<_Result_alloc<_Res, _Allocator>>
  230. _S_allocate_result(const _Allocator& __a)
  231. {
  232. using __result_type = _Result_alloc<_Res, _Allocator>;
  233. typename __result_type::__allocator_type __a2(__a);
  234. auto __guard = std::__allocate_guarded(__a2);
  235. __result_type* __p = ::new((void*)__guard.get()) __result_type{__a};
  236. __guard = nullptr;
  237. return _Ptr<__result_type>(__p);
  238. }
  239. // Keep it simple for std::allocator.
  240. template<typename _Res, typename _Tp>
  241. static _Ptr<_Result<_Res>>
  242. _S_allocate_result(const std::allocator<_Tp>& __a)
  243. {
  244. return _Ptr<_Result<_Res>>(new _Result<_Res>);
  245. }
  246. // Base class for various types of shared state created by an
  247. // asynchronous provider (such as a std::promise) and shared with one
  248. // or more associated futures.
  249. class _State_baseV2
  250. {
  251. typedef _Ptr<_Result_base> _Ptr_type;
  252. enum _Status : unsigned {
  253. __not_ready,
  254. __ready
  255. };
  256. _Ptr_type _M_result;
  257. __atomic_futex_unsigned<> _M_status;
  258. atomic_flag _M_retrieved = ATOMIC_FLAG_INIT;
  259. once_flag _M_once;
  260. public:
  261. _State_baseV2() noexcept : _M_result(), _M_status(_Status::__not_ready)
  262. { }
  263. _State_baseV2(const _State_baseV2&) = delete;
  264. _State_baseV2& operator=(const _State_baseV2&) = delete;
  265. virtual ~_State_baseV2() = default;
  266. _Result_base&
  267. wait()
  268. {
  269. // Run any deferred function or join any asynchronous thread:
  270. _M_complete_async();
  271. // Acquire MO makes sure this synchronizes with the thread that made
  272. // the future ready.
  273. _M_status._M_load_when_equal(_Status::__ready, memory_order_acquire);
  274. return *_M_result;
  275. }
  276. template<typename _Rep, typename _Period>
  277. future_status
  278. wait_for(const chrono::duration<_Rep, _Period>& __rel)
  279. {
  280. // First, check if the future has been made ready. Use acquire MO
  281. // to synchronize with the thread that made it ready.
  282. if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
  283. return future_status::ready;
  284. if (_M_is_deferred_future())
  285. return future_status::deferred;
  286. if (_M_status._M_load_when_equal_for(_Status::__ready,
  287. memory_order_acquire, __rel))
  288. {
  289. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  290. // 2100. timed waiting functions must also join
  291. // This call is a no-op by default except on an async future,
  292. // in which case the async thread is joined. It's also not a
  293. // no-op for a deferred future, but such a future will never
  294. // reach this point because it returns future_status::deferred
  295. // instead of waiting for the future to become ready (see
  296. // above). Async futures synchronize in this call, so we need
  297. // no further synchronization here.
  298. _M_complete_async();
  299. return future_status::ready;
  300. }
  301. return future_status::timeout;
  302. }
  303. template<typename _Clock, typename _Duration>
  304. future_status
  305. wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
  306. {
  307. #if __cplusplus > 201703L
  308. static_assert(chrono::is_clock_v<_Clock>);
  309. #endif
  310. // First, check if the future has been made ready. Use acquire MO
  311. // to synchronize with the thread that made it ready.
  312. if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
  313. return future_status::ready;
  314. if (_M_is_deferred_future())
  315. return future_status::deferred;
  316. if (_M_status._M_load_when_equal_until(_Status::__ready,
  317. memory_order_acquire, __abs))
  318. {
  319. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  320. // 2100. timed waiting functions must also join
  321. // See wait_for(...) above.
  322. _M_complete_async();
  323. return future_status::ready;
  324. }
  325. return future_status::timeout;
  326. }
  327. // Provide a result to the shared state and make it ready.
  328. // Calls at most once: _M_result = __res();
  329. void
  330. _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
  331. {
  332. bool __did_set = false;
  333. // all calls to this function are serialized,
  334. // side-effects of invoking __res only happen once
  335. call_once(_M_once, &_State_baseV2::_M_do_set, this,
  336. std::__addressof(__res), std::__addressof(__did_set));
  337. if (__did_set)
  338. // Use release MO to synchronize with observers of the ready state.
  339. _M_status._M_store_notify_all(_Status::__ready,
  340. memory_order_release);
  341. else if (!__ignore_failure)
  342. __throw_future_error(int(future_errc::promise_already_satisfied));
  343. }
  344. // Provide a result to the shared state but delay making it ready
  345. // until the calling thread exits.
  346. // Calls at most once: _M_result = __res();
  347. void
  348. _M_set_delayed_result(function<_Ptr_type()> __res,
  349. weak_ptr<_State_baseV2> __self)
  350. {
  351. bool __did_set = false;
  352. unique_ptr<_Make_ready> __mr{new _Make_ready};
  353. // all calls to this function are serialized,
  354. // side-effects of invoking __res only happen once
  355. call_once(_M_once, &_State_baseV2::_M_do_set, this,
  356. std::__addressof(__res), std::__addressof(__did_set));
  357. if (!__did_set)
  358. __throw_future_error(int(future_errc::promise_already_satisfied));
  359. __mr->_M_shared_state = std::move(__self);
  360. __mr->_M_set();
  361. __mr.release();
  362. }
  363. // Abandon this shared state.
  364. void
  365. _M_break_promise(_Ptr_type __res)
  366. {
  367. if (static_cast<bool>(__res))
  368. {
  369. __res->_M_error =
  370. make_exception_ptr(future_error(future_errc::broken_promise));
  371. // This function is only called when the last asynchronous result
  372. // provider is abandoning this shared state, so noone can be
  373. // trying to make the shared state ready at the same time, and
  374. // we can access _M_result directly instead of through call_once.
  375. _M_result.swap(__res);
  376. // Use release MO to synchronize with observers of the ready state.
  377. _M_status._M_store_notify_all(_Status::__ready,
  378. memory_order_release);
  379. }
  380. }
  381. // Called when this object is first passed to a future.
  382. void
  383. _M_set_retrieved_flag()
  384. {
  385. if (_M_retrieved.test_and_set())
  386. __throw_future_error(int(future_errc::future_already_retrieved));
  387. }
  388. template<typename _Res, typename _Arg>
  389. struct _Setter;
  390. // set lvalues
  391. template<typename _Res, typename _Arg>
  392. struct _Setter<_Res, _Arg&>
  393. {
  394. // check this is only used by promise<R>::set_value(const R&)
  395. // or promise<R&>::set_value(R&)
  396. static_assert(is_same<_Res, _Arg&>::value // promise<R&>
  397. || is_same<const _Res, _Arg>::value, // promise<R>
  398. "Invalid specialisation");
  399. // Used by std::promise to copy construct the result.
  400. typename promise<_Res>::_Ptr_type operator()() const
  401. {
  402. _M_promise->_M_storage->_M_set(*_M_arg);
  403. return std::move(_M_promise->_M_storage);
  404. }
  405. promise<_Res>* _M_promise;
  406. _Arg* _M_arg;
  407. };
  408. // set rvalues
  409. template<typename _Res>
  410. struct _Setter<_Res, _Res&&>
  411. {
  412. // Used by std::promise to move construct the result.
  413. typename promise<_Res>::_Ptr_type operator()() const
  414. {
  415. _M_promise->_M_storage->_M_set(std::move(*_M_arg));
  416. return std::move(_M_promise->_M_storage);
  417. }
  418. promise<_Res>* _M_promise;
  419. _Res* _M_arg;
  420. };
  421. // set void
  422. template<typename _Res>
  423. struct _Setter<_Res, void>
  424. {
  425. static_assert(is_void<_Res>::value, "Only used for promise<void>");
  426. typename promise<_Res>::_Ptr_type operator()() const
  427. { return std::move(_M_promise->_M_storage); }
  428. promise<_Res>* _M_promise;
  429. };
  430. struct __exception_ptr_tag { };
  431. // set exceptions
  432. template<typename _Res>
  433. struct _Setter<_Res, __exception_ptr_tag>
  434. {
  435. // Used by std::promise to store an exception as the result.
  436. typename promise<_Res>::_Ptr_type operator()() const
  437. {
  438. _M_promise->_M_storage->_M_error = *_M_ex;
  439. return std::move(_M_promise->_M_storage);
  440. }
  441. promise<_Res>* _M_promise;
  442. exception_ptr* _M_ex;
  443. };
  444. template<typename _Res, typename _Arg>
  445. static _Setter<_Res, _Arg&&>
  446. __setter(promise<_Res>* __prom, _Arg&& __arg)
  447. {
  448. _S_check(__prom->_M_future);
  449. return _Setter<_Res, _Arg&&>{ __prom, std::__addressof(__arg) };
  450. }
  451. template<typename _Res>
  452. static _Setter<_Res, __exception_ptr_tag>
  453. __setter(exception_ptr& __ex, promise<_Res>* __prom)
  454. {
  455. _S_check(__prom->_M_future);
  456. return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex };
  457. }
  458. template<typename _Res>
  459. static _Setter<_Res, void>
  460. __setter(promise<_Res>* __prom)
  461. {
  462. _S_check(__prom->_M_future);
  463. return _Setter<_Res, void>{ __prom };
  464. }
  465. template<typename _Tp>
  466. static void
  467. _S_check(const shared_ptr<_Tp>& __p)
  468. {
  469. if (!static_cast<bool>(__p))
  470. __throw_future_error((int)future_errc::no_state);
  471. }
  472. private:
  473. // The function invoked with std::call_once(_M_once, ...).
  474. void
  475. _M_do_set(function<_Ptr_type()>* __f, bool* __did_set)
  476. {
  477. _Ptr_type __res = (*__f)();
  478. // Notify the caller that we did try to set; if we do not throw an
  479. // exception, the caller will be aware that it did set (e.g., see
  480. // _M_set_result).
  481. *__did_set = true;
  482. _M_result.swap(__res); // nothrow
  483. }
  484. // Wait for completion of async function.
  485. virtual void _M_complete_async() { }
  486. // Return true if state corresponds to a deferred function.
  487. virtual bool _M_is_deferred_future() const { return false; }
  488. struct _Make_ready final : __at_thread_exit_elt
  489. {
  490. weak_ptr<_State_baseV2> _M_shared_state;
  491. static void _S_run(void*);
  492. void _M_set();
  493. };
  494. };
  495. #ifdef _GLIBCXX_ASYNC_ABI_COMPAT
  496. class _State_base;
  497. class _Async_state_common;
  498. #else
  499. using _State_base = _State_baseV2;
  500. class _Async_state_commonV2;
  501. #endif
  502. template<typename _BoundFn,
  503. typename _Res = decltype(std::declval<_BoundFn&>()())>
  504. class _Deferred_state;
  505. template<typename _BoundFn,
  506. typename _Res = decltype(std::declval<_BoundFn&>()())>
  507. class _Async_state_impl;
  508. template<typename _Signature>
  509. class _Task_state_base;
  510. template<typename _Fn, typename _Alloc, typename _Signature>
  511. class _Task_state;
  512. template<typename _BoundFn>
  513. static std::shared_ptr<_State_base>
  514. _S_make_deferred_state(_BoundFn&& __fn);
  515. template<typename _BoundFn>
  516. static std::shared_ptr<_State_base>
  517. _S_make_async_state(_BoundFn&& __fn);
  518. template<typename _Res_ptr, typename _Fn,
  519. typename _Res = typename _Res_ptr::element_type::result_type>
  520. struct _Task_setter;
  521. template<typename _Res_ptr, typename _BoundFn>
  522. static _Task_setter<_Res_ptr, _BoundFn>
  523. _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call)
  524. {
  525. return { std::__addressof(__ptr), std::__addressof(__call) };
  526. }
  527. };
  528. /// Partial specialization for reference types.
  529. template<typename _Res>
  530. struct __future_base::_Result<_Res&> : __future_base::_Result_base
  531. {
  532. typedef _Res& result_type;
  533. _Result() noexcept : _M_value_ptr() { }
  534. void
  535. _M_set(_Res& __res) noexcept
  536. { _M_value_ptr = std::addressof(__res); }
  537. _Res& _M_get() noexcept { return *_M_value_ptr; }
  538. private:
  539. _Res* _M_value_ptr;
  540. void _M_destroy() { delete this; }
  541. };
  542. /// Explicit specialization for void.
  543. template<>
  544. struct __future_base::_Result<void> : __future_base::_Result_base
  545. {
  546. typedef void result_type;
  547. private:
  548. void _M_destroy() { delete this; }
  549. };
  550. #ifndef _GLIBCXX_ASYNC_ABI_COMPAT
  551. // Allow _Setter objects to be stored locally in std::function
  552. template<typename _Res, typename _Arg>
  553. struct __is_location_invariant
  554. <__future_base::_State_base::_Setter<_Res, _Arg>>
  555. : true_type { };
  556. // Allow _Task_setter objects to be stored locally in std::function
  557. template<typename _Res_ptr, typename _Fn, typename _Res>
  558. struct __is_location_invariant
  559. <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>>
  560. : true_type { };
  561. /// Common implementation for future and shared_future.
  562. template<typename _Res>
  563. class __basic_future : public __future_base
  564. {
  565. protected:
  566. typedef shared_ptr<_State_base> __state_type;
  567. typedef __future_base::_Result<_Res>& __result_type;
  568. private:
  569. __state_type _M_state;
  570. public:
  571. // Disable copying.
  572. __basic_future(const __basic_future&) = delete;
  573. __basic_future& operator=(const __basic_future&) = delete;
  574. bool
  575. valid() const noexcept { return static_cast<bool>(_M_state); }
  576. void
  577. wait() const
  578. {
  579. _State_base::_S_check(_M_state);
  580. _M_state->wait();
  581. }
  582. template<typename _Rep, typename _Period>
  583. future_status
  584. wait_for(const chrono::duration<_Rep, _Period>& __rel) const
  585. {
  586. _State_base::_S_check(_M_state);
  587. return _M_state->wait_for(__rel);
  588. }
  589. template<typename _Clock, typename _Duration>
  590. future_status
  591. wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
  592. {
  593. _State_base::_S_check(_M_state);
  594. return _M_state->wait_until(__abs);
  595. }
  596. protected:
  597. /// Wait for the state to be ready and rethrow any stored exception
  598. __result_type
  599. _M_get_result() const
  600. {
  601. _State_base::_S_check(_M_state);
  602. _Result_base& __res = _M_state->wait();
  603. if (!(__res._M_error == 0))
  604. rethrow_exception(__res._M_error);
  605. return static_cast<__result_type>(__res);
  606. }
  607. void _M_swap(__basic_future& __that) noexcept
  608. {
  609. _M_state.swap(__that._M_state);
  610. }
  611. // Construction of a future by promise::get_future()
  612. explicit
  613. __basic_future(const __state_type& __state) : _M_state(__state)
  614. {
  615. _State_base::_S_check(_M_state);
  616. _M_state->_M_set_retrieved_flag();
  617. }
  618. // Copy construction from a shared_future
  619. explicit
  620. __basic_future(const shared_future<_Res>&) noexcept;
  621. // Move construction from a shared_future
  622. explicit
  623. __basic_future(shared_future<_Res>&&) noexcept;
  624. // Move construction from a future
  625. explicit
  626. __basic_future(future<_Res>&&) noexcept;
  627. constexpr __basic_future() noexcept : _M_state() { }
  628. struct _Reset
  629. {
  630. explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { }
  631. ~_Reset() { _M_fut._M_state.reset(); }
  632. __basic_future& _M_fut;
  633. };
  634. };
  635. /// Primary template for future.
  636. template<typename _Res>
  637. class future : public __basic_future<_Res>
  638. {
  639. friend class promise<_Res>;
  640. template<typename> friend class packaged_task;
  641. template<typename _Fn, typename... _Args>
  642. friend future<__async_result_of<_Fn, _Args...>>
  643. async(launch, _Fn&&, _Args&&...);
  644. typedef __basic_future<_Res> _Base_type;
  645. typedef typename _Base_type::__state_type __state_type;
  646. explicit
  647. future(const __state_type& __state) : _Base_type(__state) { }
  648. public:
  649. constexpr future() noexcept : _Base_type() { }
  650. /// Move constructor
  651. future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
  652. // Disable copying
  653. future(const future&) = delete;
  654. future& operator=(const future&) = delete;
  655. future& operator=(future&& __fut) noexcept
  656. {
  657. future(std::move(__fut))._M_swap(*this);
  658. return *this;
  659. }
  660. /// Retrieving the value
  661. _Res
  662. get()
  663. {
  664. typename _Base_type::_Reset __reset(*this);
  665. return std::move(this->_M_get_result()._M_value());
  666. }
  667. shared_future<_Res> share() noexcept;
  668. };
  669. /// Partial specialization for future<R&>
  670. template<typename _Res>
  671. class future<_Res&> : public __basic_future<_Res&>
  672. {
  673. friend class promise<_Res&>;
  674. template<typename> friend class packaged_task;
  675. template<typename _Fn, typename... _Args>
  676. friend future<__async_result_of<_Fn, _Args...>>
  677. async(launch, _Fn&&, _Args&&...);
  678. typedef __basic_future<_Res&> _Base_type;
  679. typedef typename _Base_type::__state_type __state_type;
  680. explicit
  681. future(const __state_type& __state) : _Base_type(__state) { }
  682. public:
  683. constexpr future() noexcept : _Base_type() { }
  684. /// Move constructor
  685. future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
  686. // Disable copying
  687. future(const future&) = delete;
  688. future& operator=(const future&) = delete;
  689. future& operator=(future&& __fut) noexcept
  690. {
  691. future(std::move(__fut))._M_swap(*this);
  692. return *this;
  693. }
  694. /// Retrieving the value
  695. _Res&
  696. get()
  697. {
  698. typename _Base_type::_Reset __reset(*this);
  699. return this->_M_get_result()._M_get();
  700. }
  701. shared_future<_Res&> share() noexcept;
  702. };
  703. /// Explicit specialization for future<void>
  704. template<>
  705. class future<void> : public __basic_future<void>
  706. {
  707. friend class promise<void>;
  708. template<typename> friend class packaged_task;
  709. template<typename _Fn, typename... _Args>
  710. friend future<__async_result_of<_Fn, _Args...>>
  711. async(launch, _Fn&&, _Args&&...);
  712. typedef __basic_future<void> _Base_type;
  713. typedef typename _Base_type::__state_type __state_type;
  714. explicit
  715. future(const __state_type& __state) : _Base_type(__state) { }
  716. public:
  717. constexpr future() noexcept : _Base_type() { }
  718. /// Move constructor
  719. future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
  720. // Disable copying
  721. future(const future&) = delete;
  722. future& operator=(const future&) = delete;
  723. future& operator=(future&& __fut) noexcept
  724. {
  725. future(std::move(__fut))._M_swap(*this);
  726. return *this;
  727. }
  728. /// Retrieving the value
  729. void
  730. get()
  731. {
  732. typename _Base_type::_Reset __reset(*this);
  733. this->_M_get_result();
  734. }
  735. shared_future<void> share() noexcept;
  736. };
  737. /// Primary template for shared_future.
  738. template<typename _Res>
  739. class shared_future : public __basic_future<_Res>
  740. {
  741. typedef __basic_future<_Res> _Base_type;
  742. public:
  743. constexpr shared_future() noexcept : _Base_type() { }
  744. /// Copy constructor
  745. shared_future(const shared_future& __sf) noexcept : _Base_type(__sf) { }
  746. /// Construct from a future rvalue
  747. shared_future(future<_Res>&& __uf) noexcept
  748. : _Base_type(std::move(__uf))
  749. { }
  750. /// Construct from a shared_future rvalue
  751. shared_future(shared_future&& __sf) noexcept
  752. : _Base_type(std::move(__sf))
  753. { }
  754. shared_future& operator=(const shared_future& __sf) noexcept
  755. {
  756. shared_future(__sf)._M_swap(*this);
  757. return *this;
  758. }
  759. shared_future& operator=(shared_future&& __sf) noexcept
  760. {
  761. shared_future(std::move(__sf))._M_swap(*this);
  762. return *this;
  763. }
  764. /// Retrieving the value
  765. const _Res&
  766. get() const { return this->_M_get_result()._M_value(); }
  767. };
  768. /// Partial specialization for shared_future<R&>
  769. template<typename _Res>
  770. class shared_future<_Res&> : public __basic_future<_Res&>
  771. {
  772. typedef __basic_future<_Res&> _Base_type;
  773. public:
  774. constexpr shared_future() noexcept : _Base_type() { }
  775. /// Copy constructor
  776. shared_future(const shared_future& __sf) : _Base_type(__sf) { }
  777. /// Construct from a future rvalue
  778. shared_future(future<_Res&>&& __uf) noexcept
  779. : _Base_type(std::move(__uf))
  780. { }
  781. /// Construct from a shared_future rvalue
  782. shared_future(shared_future&& __sf) noexcept
  783. : _Base_type(std::move(__sf))
  784. { }
  785. shared_future& operator=(const shared_future& __sf)
  786. {
  787. shared_future(__sf)._M_swap(*this);
  788. return *this;
  789. }
  790. shared_future& operator=(shared_future&& __sf) noexcept
  791. {
  792. shared_future(std::move(__sf))._M_swap(*this);
  793. return *this;
  794. }
  795. /// Retrieving the value
  796. _Res&
  797. get() const { return this->_M_get_result()._M_get(); }
  798. };
  799. /// Explicit specialization for shared_future<void>
  800. template<>
  801. class shared_future<void> : public __basic_future<void>
  802. {
  803. typedef __basic_future<void> _Base_type;
  804. public:
  805. constexpr shared_future() noexcept : _Base_type() { }
  806. /// Copy constructor
  807. shared_future(const shared_future& __sf) : _Base_type(__sf) { }
  808. /// Construct from a future rvalue
  809. shared_future(future<void>&& __uf) noexcept
  810. : _Base_type(std::move(__uf))
  811. { }
  812. /// Construct from a shared_future rvalue
  813. shared_future(shared_future&& __sf) noexcept
  814. : _Base_type(std::move(__sf))
  815. { }
  816. shared_future& operator=(const shared_future& __sf)
  817. {
  818. shared_future(__sf)._M_swap(*this);
  819. return *this;
  820. }
  821. shared_future& operator=(shared_future&& __sf) noexcept
  822. {
  823. shared_future(std::move(__sf))._M_swap(*this);
  824. return *this;
  825. }
  826. // Retrieving the value
  827. void
  828. get() const { this->_M_get_result(); }
  829. };
  830. // Now we can define the protected __basic_future constructors.
  831. template<typename _Res>
  832. inline __basic_future<_Res>::
  833. __basic_future(const shared_future<_Res>& __sf) noexcept
  834. : _M_state(__sf._M_state)
  835. { }
  836. template<typename _Res>
  837. inline __basic_future<_Res>::
  838. __basic_future(shared_future<_Res>&& __sf) noexcept
  839. : _M_state(std::move(__sf._M_state))
  840. { }
  841. template<typename _Res>
  842. inline __basic_future<_Res>::
  843. __basic_future(future<_Res>&& __uf) noexcept
  844. : _M_state(std::move(__uf._M_state))
  845. { }
  846. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  847. // 2556. Wide contract for future::share()
  848. template<typename _Res>
  849. inline shared_future<_Res>
  850. future<_Res>::share() noexcept
  851. { return shared_future<_Res>(std::move(*this)); }
  852. template<typename _Res>
  853. inline shared_future<_Res&>
  854. future<_Res&>::share() noexcept
  855. { return shared_future<_Res&>(std::move(*this)); }
  856. inline shared_future<void>
  857. future<void>::share() noexcept
  858. { return shared_future<void>(std::move(*this)); }
  859. /// Primary template for promise
  860. template<typename _Res>
  861. class promise
  862. {
  863. typedef __future_base::_State_base _State;
  864. typedef __future_base::_Result<_Res> _Res_type;
  865. typedef __future_base::_Ptr<_Res_type> _Ptr_type;
  866. template<typename, typename> friend class _State::_Setter;
  867. friend _State;
  868. shared_ptr<_State> _M_future;
  869. _Ptr_type _M_storage;
  870. public:
  871. promise()
  872. : _M_future(std::make_shared<_State>()),
  873. _M_storage(new _Res_type())
  874. { }
  875. promise(promise&& __rhs) noexcept
  876. : _M_future(std::move(__rhs._M_future)),
  877. _M_storage(std::move(__rhs._M_storage))
  878. { }
  879. template<typename _Allocator>
  880. promise(allocator_arg_t, const _Allocator& __a)
  881. : _M_future(std::allocate_shared<_State>(__a)),
  882. _M_storage(__future_base::_S_allocate_result<_Res>(__a))
  883. { }
  884. template<typename _Allocator>
  885. promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
  886. : _M_future(std::move(__rhs._M_future)),
  887. _M_storage(std::move(__rhs._M_storage))
  888. { }
  889. promise(const promise&) = delete;
  890. ~promise()
  891. {
  892. if (static_cast<bool>(_M_future) && !_M_future.unique())
  893. _M_future->_M_break_promise(std::move(_M_storage));
  894. }
  895. // Assignment
  896. promise&
  897. operator=(promise&& __rhs) noexcept
  898. {
  899. promise(std::move(__rhs)).swap(*this);
  900. return *this;
  901. }
  902. promise& operator=(const promise&) = delete;
  903. void
  904. swap(promise& __rhs) noexcept
  905. {
  906. _M_future.swap(__rhs._M_future);
  907. _M_storage.swap(__rhs._M_storage);
  908. }
  909. // Retrieving the result
  910. future<_Res>
  911. get_future()
  912. { return future<_Res>(_M_future); }
  913. // Setting the result
  914. void
  915. set_value(const _Res& __r)
  916. { _M_future->_M_set_result(_State::__setter(this, __r)); }
  917. void
  918. set_value(_Res&& __r)
  919. { _M_future->_M_set_result(_State::__setter(this, std::move(__r))); }
  920. void
  921. set_exception(exception_ptr __p)
  922. { _M_future->_M_set_result(_State::__setter(__p, this)); }
  923. void
  924. set_value_at_thread_exit(const _Res& __r)
  925. {
  926. _M_future->_M_set_delayed_result(_State::__setter(this, __r),
  927. _M_future);
  928. }
  929. void
  930. set_value_at_thread_exit(_Res&& __r)
  931. {
  932. _M_future->_M_set_delayed_result(
  933. _State::__setter(this, std::move(__r)), _M_future);
  934. }
  935. void
  936. set_exception_at_thread_exit(exception_ptr __p)
  937. {
  938. _M_future->_M_set_delayed_result(_State::__setter(__p, this),
  939. _M_future);
  940. }
  941. };
  942. template<typename _Res>
  943. inline void
  944. swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
  945. { __x.swap(__y); }
  946. template<typename _Res, typename _Alloc>
  947. struct uses_allocator<promise<_Res>, _Alloc>
  948. : public true_type { };
  949. /// Partial specialization for promise<R&>
  950. template<typename _Res>
  951. class promise<_Res&>
  952. {
  953. typedef __future_base::_State_base _State;
  954. typedef __future_base::_Result<_Res&> _Res_type;
  955. typedef __future_base::_Ptr<_Res_type> _Ptr_type;
  956. template<typename, typename> friend class _State::_Setter;
  957. friend _State;
  958. shared_ptr<_State> _M_future;
  959. _Ptr_type _M_storage;
  960. public:
  961. promise()
  962. : _M_future(std::make_shared<_State>()),
  963. _M_storage(new _Res_type())
  964. { }
  965. promise(promise&& __rhs) noexcept
  966. : _M_future(std::move(__rhs._M_future)),
  967. _M_storage(std::move(__rhs._M_storage))
  968. { }
  969. template<typename _Allocator>
  970. promise(allocator_arg_t, const _Allocator& __a)
  971. : _M_future(std::allocate_shared<_State>(__a)),
  972. _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
  973. { }
  974. template<typename _Allocator>
  975. promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
  976. : _M_future(std::move(__rhs._M_future)),
  977. _M_storage(std::move(__rhs._M_storage))
  978. { }
  979. promise(const promise&) = delete;
  980. ~promise()
  981. {
  982. if (static_cast<bool>(_M_future) && !_M_future.unique())
  983. _M_future->_M_break_promise(std::move(_M_storage));
  984. }
  985. // Assignment
  986. promise&
  987. operator=(promise&& __rhs) noexcept
  988. {
  989. promise(std::move(__rhs)).swap(*this);
  990. return *this;
  991. }
  992. promise& operator=(const promise&) = delete;
  993. void
  994. swap(promise& __rhs) noexcept
  995. {
  996. _M_future.swap(__rhs._M_future);
  997. _M_storage.swap(__rhs._M_storage);
  998. }
  999. // Retrieving the result
  1000. future<_Res&>
  1001. get_future()
  1002. { return future<_Res&>(_M_future); }
  1003. // Setting the result
  1004. void
  1005. set_value(_Res& __r)
  1006. { _M_future->_M_set_result(_State::__setter(this, __r)); }
  1007. void
  1008. set_exception(exception_ptr __p)
  1009. { _M_future->_M_set_result(_State::__setter(__p, this)); }
  1010. void
  1011. set_value_at_thread_exit(_Res& __r)
  1012. {
  1013. _M_future->_M_set_delayed_result(_State::__setter(this, __r),
  1014. _M_future);
  1015. }
  1016. void
  1017. set_exception_at_thread_exit(exception_ptr __p)
  1018. {
  1019. _M_future->_M_set_delayed_result(_State::__setter(__p, this),
  1020. _M_future);
  1021. }
  1022. };
  1023. /// Explicit specialization for promise<void>
  1024. template<>
  1025. class promise<void>
  1026. {
  1027. typedef __future_base::_State_base _State;
  1028. typedef __future_base::_Result<void> _Res_type;
  1029. typedef __future_base::_Ptr<_Res_type> _Ptr_type;
  1030. template<typename, typename> friend class _State::_Setter;
  1031. friend _State;
  1032. shared_ptr<_State> _M_future;
  1033. _Ptr_type _M_storage;
  1034. public:
  1035. promise()
  1036. : _M_future(std::make_shared<_State>()),
  1037. _M_storage(new _Res_type())
  1038. { }
  1039. promise(promise&& __rhs) noexcept
  1040. : _M_future(std::move(__rhs._M_future)),
  1041. _M_storage(std::move(__rhs._M_storage))
  1042. { }
  1043. template<typename _Allocator>
  1044. promise(allocator_arg_t, const _Allocator& __a)
  1045. : _M_future(std::allocate_shared<_State>(__a)),
  1046. _M_storage(__future_base::_S_allocate_result<void>(__a))
  1047. { }
  1048. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  1049. // 2095. missing constructors needed for uses-allocator construction
  1050. template<typename _Allocator>
  1051. promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
  1052. : _M_future(std::move(__rhs._M_future)),
  1053. _M_storage(std::move(__rhs._M_storage))
  1054. { }
  1055. promise(const promise&) = delete;
  1056. ~promise()
  1057. {
  1058. if (static_cast<bool>(_M_future) && !_M_future.unique())
  1059. _M_future->_M_break_promise(std::move(_M_storage));
  1060. }
  1061. // Assignment
  1062. promise&
  1063. operator=(promise&& __rhs) noexcept
  1064. {
  1065. promise(std::move(__rhs)).swap(*this);
  1066. return *this;
  1067. }
  1068. promise& operator=(const promise&) = delete;
  1069. void
  1070. swap(promise& __rhs) noexcept
  1071. {
  1072. _M_future.swap(__rhs._M_future);
  1073. _M_storage.swap(__rhs._M_storage);
  1074. }
  1075. // Retrieving the result
  1076. future<void>
  1077. get_future()
  1078. { return future<void>(_M_future); }
  1079. // Setting the result
  1080. void
  1081. set_value()
  1082. { _M_future->_M_set_result(_State::__setter(this)); }
  1083. void
  1084. set_exception(exception_ptr __p)
  1085. { _M_future->_M_set_result(_State::__setter(__p, this)); }
  1086. void
  1087. set_value_at_thread_exit()
  1088. { _M_future->_M_set_delayed_result(_State::__setter(this), _M_future); }
  1089. void
  1090. set_exception_at_thread_exit(exception_ptr __p)
  1091. {
  1092. _M_future->_M_set_delayed_result(_State::__setter(__p, this),
  1093. _M_future);
  1094. }
  1095. };
  1096. template<typename _Ptr_type, typename _Fn, typename _Res>
  1097. struct __future_base::_Task_setter
  1098. {
  1099. // Invoke the function and provide the result to the caller.
  1100. _Ptr_type operator()() const
  1101. {
  1102. __try
  1103. {
  1104. (*_M_result)->_M_set((*_M_fn)());
  1105. }
  1106. __catch(const __cxxabiv1::__forced_unwind&)
  1107. {
  1108. __throw_exception_again; // will cause broken_promise
  1109. }
  1110. __catch(...)
  1111. {
  1112. (*_M_result)->_M_error = current_exception();
  1113. }
  1114. return std::move(*_M_result);
  1115. }
  1116. _Ptr_type* _M_result;
  1117. _Fn* _M_fn;
  1118. };
  1119. template<typename _Ptr_type, typename _Fn>
  1120. struct __future_base::_Task_setter<_Ptr_type, _Fn, void>
  1121. {
  1122. _Ptr_type operator()() const
  1123. {
  1124. __try
  1125. {
  1126. (*_M_fn)();
  1127. }
  1128. __catch(const __cxxabiv1::__forced_unwind&)
  1129. {
  1130. __throw_exception_again; // will cause broken_promise
  1131. }
  1132. __catch(...)
  1133. {
  1134. (*_M_result)->_M_error = current_exception();
  1135. }
  1136. return std::move(*_M_result);
  1137. }
  1138. _Ptr_type* _M_result;
  1139. _Fn* _M_fn;
  1140. };
  1141. // Holds storage for a packaged_task's result.
  1142. template<typename _Res, typename... _Args>
  1143. struct __future_base::_Task_state_base<_Res(_Args...)>
  1144. : __future_base::_State_base
  1145. {
  1146. typedef _Res _Res_type;
  1147. template<typename _Alloc>
  1148. _Task_state_base(const _Alloc& __a)
  1149. : _M_result(_S_allocate_result<_Res>(__a))
  1150. { }
  1151. // Invoke the stored task and make the state ready.
  1152. virtual void
  1153. _M_run(_Args&&... __args) = 0;
  1154. // Invoke the stored task and make the state ready at thread exit.
  1155. virtual void
  1156. _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0;
  1157. virtual shared_ptr<_Task_state_base>
  1158. _M_reset() = 0;
  1159. typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
  1160. _Ptr_type _M_result;
  1161. };
  1162. // Holds a packaged_task's stored task.
  1163. template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
  1164. struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final
  1165. : __future_base::_Task_state_base<_Res(_Args...)>
  1166. {
  1167. template<typename _Fn2>
  1168. _Task_state(_Fn2&& __fn, const _Alloc& __a)
  1169. : _Task_state_base<_Res(_Args...)>(__a),
  1170. _M_impl(std::forward<_Fn2>(__fn), __a)
  1171. { }
  1172. private:
  1173. virtual void
  1174. _M_run(_Args&&... __args)
  1175. {
  1176. auto __boundfn = [&] () -> _Res {
  1177. return std::__invoke_r<_Res>(_M_impl._M_fn,
  1178. std::forward<_Args>(__args)...);
  1179. };
  1180. this->_M_set_result(_S_task_setter(this->_M_result, __boundfn));
  1181. }
  1182. virtual void
  1183. _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self)
  1184. {
  1185. auto __boundfn = [&] () -> _Res {
  1186. return std::__invoke_r<_Res>(_M_impl._M_fn,
  1187. std::forward<_Args>(__args)...);
  1188. };
  1189. this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn),
  1190. std::move(__self));
  1191. }
  1192. virtual shared_ptr<_Task_state_base<_Res(_Args...)>>
  1193. _M_reset();
  1194. struct _Impl : _Alloc
  1195. {
  1196. template<typename _Fn2>
  1197. _Impl(_Fn2&& __fn, const _Alloc& __a)
  1198. : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { }
  1199. _Fn _M_fn;
  1200. } _M_impl;
  1201. };
  1202. template<typename _Signature, typename _Fn,
  1203. typename _Alloc = std::allocator<int>>
  1204. static shared_ptr<__future_base::_Task_state_base<_Signature>>
  1205. __create_task_state(_Fn&& __fn, const _Alloc& __a = _Alloc())
  1206. {
  1207. typedef typename decay<_Fn>::type _Fn2;
  1208. typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State;
  1209. return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a);
  1210. }
  1211. template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
  1212. shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>>
  1213. __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset()
  1214. {
  1215. return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn),
  1216. static_cast<_Alloc&>(_M_impl));
  1217. }
  1218. /// packaged_task
  1219. template<typename _Res, typename... _ArgTypes>
  1220. class packaged_task<_Res(_ArgTypes...)>
  1221. {
  1222. typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type;
  1223. shared_ptr<_State_type> _M_state;
  1224. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  1225. // 3039. Unnecessary decay in thread and packaged_task
  1226. template<typename _Fn, typename _Fn2 = __remove_cvref_t<_Fn>>
  1227. using __not_same
  1228. = typename enable_if<!is_same<packaged_task, _Fn2>::value>::type;
  1229. public:
  1230. // Construction and destruction
  1231. packaged_task() noexcept { }
  1232. template<typename _Fn, typename = __not_same<_Fn>>
  1233. explicit
  1234. packaged_task(_Fn&& __fn)
  1235. : _M_state(
  1236. __create_task_state<_Res(_ArgTypes...)>(std::forward<_Fn>(__fn)))
  1237. { }
  1238. #if __cplusplus < 201703L
  1239. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  1240. // 2097. packaged_task constructors should be constrained
  1241. // 2407. [this constructor should not be] explicit
  1242. // 2921. packaged_task and type-erased allocators
  1243. template<typename _Fn, typename _Alloc, typename = __not_same<_Fn>>
  1244. packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn)
  1245. : _M_state(__create_task_state<_Res(_ArgTypes...)>(
  1246. std::forward<_Fn>(__fn), __a))
  1247. { }
  1248. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  1249. // 2095. missing constructors needed for uses-allocator construction
  1250. template<typename _Allocator>
  1251. packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
  1252. { }
  1253. template<typename _Allocator>
  1254. packaged_task(allocator_arg_t, const _Allocator&,
  1255. const packaged_task&) = delete;
  1256. template<typename _Allocator>
  1257. packaged_task(allocator_arg_t, const _Allocator&,
  1258. packaged_task&& __other) noexcept
  1259. { this->swap(__other); }
  1260. #endif
  1261. ~packaged_task()
  1262. {
  1263. if (static_cast<bool>(_M_state) && !_M_state.unique())
  1264. _M_state->_M_break_promise(std::move(_M_state->_M_result));
  1265. }
  1266. // No copy
  1267. packaged_task(const packaged_task&) = delete;
  1268. packaged_task& operator=(const packaged_task&) = delete;
  1269. // Move support
  1270. packaged_task(packaged_task&& __other) noexcept
  1271. { this->swap(__other); }
  1272. packaged_task& operator=(packaged_task&& __other) noexcept
  1273. {
  1274. packaged_task(std::move(__other)).swap(*this);
  1275. return *this;
  1276. }
  1277. void
  1278. swap(packaged_task& __other) noexcept
  1279. { _M_state.swap(__other._M_state); }
  1280. bool
  1281. valid() const noexcept
  1282. { return static_cast<bool>(_M_state); }
  1283. // Result retrieval
  1284. future<_Res>
  1285. get_future()
  1286. { return future<_Res>(_M_state); }
  1287. // Execution
  1288. void
  1289. operator()(_ArgTypes... __args)
  1290. {
  1291. __future_base::_State_base::_S_check(_M_state);
  1292. _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
  1293. }
  1294. void
  1295. make_ready_at_thread_exit(_ArgTypes... __args)
  1296. {
  1297. __future_base::_State_base::_S_check(_M_state);
  1298. _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state);
  1299. }
  1300. void
  1301. reset()
  1302. {
  1303. __future_base::_State_base::_S_check(_M_state);
  1304. packaged_task __tmp;
  1305. __tmp._M_state = _M_state;
  1306. _M_state = _M_state->_M_reset();
  1307. }
  1308. };
  1309. /// swap
  1310. template<typename _Res, typename... _ArgTypes>
  1311. inline void
  1312. swap(packaged_task<_Res(_ArgTypes...)>& __x,
  1313. packaged_task<_Res(_ArgTypes...)>& __y) noexcept
  1314. { __x.swap(__y); }
  1315. #if __cplusplus < 201703L
  1316. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  1317. // 2976. Dangling uses_allocator specialization for packaged_task
  1318. template<typename _Res, typename _Alloc>
  1319. struct uses_allocator<packaged_task<_Res>, _Alloc>
  1320. : public true_type { };
  1321. #endif
  1322. // Shared state created by std::async().
  1323. // Holds a deferred function and storage for its result.
  1324. template<typename _BoundFn, typename _Res>
  1325. class __future_base::_Deferred_state final
  1326. : public __future_base::_State_base
  1327. {
  1328. public:
  1329. explicit
  1330. _Deferred_state(_BoundFn&& __fn)
  1331. : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
  1332. { }
  1333. private:
  1334. typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
  1335. _Ptr_type _M_result;
  1336. _BoundFn _M_fn;
  1337. // Run the deferred function.
  1338. virtual void
  1339. _M_complete_async()
  1340. {
  1341. // Multiple threads can call a waiting function on the future and
  1342. // reach this point at the same time. The call_once in _M_set_result
  1343. // ensures only the first one run the deferred function, stores the
  1344. // result in _M_result, swaps that with the base _M_result and makes
  1345. // the state ready. Tell _M_set_result to ignore failure so all later
  1346. // calls do nothing.
  1347. _M_set_result(_S_task_setter(_M_result, _M_fn), true);
  1348. }
  1349. // Caller should check whether the state is ready first, because this
  1350. // function will return true even after the deferred function has run.
  1351. virtual bool _M_is_deferred_future() const { return true; }
  1352. };
  1353. // Common functionality hoisted out of the _Async_state_impl template.
  1354. class __future_base::_Async_state_commonV2
  1355. : public __future_base::_State_base
  1356. {
  1357. protected:
  1358. ~_Async_state_commonV2() = default;
  1359. // Make waiting functions block until the thread completes, as if joined.
  1360. //
  1361. // This function is used by wait() to satisfy the first requirement below
  1362. // and by wait_for() / wait_until() to satisfy the second.
  1363. //
  1364. // [futures.async]:
  1365. //
  1366. // - a call to a waiting function on an asynchronous return object that
  1367. // shares the shared state created by this async call shall block until
  1368. // the associated thread has completed, as if joined, or else time out.
  1369. //
  1370. // - the associated thread completion synchronizes with the return from
  1371. // the first function that successfully detects the ready status of the
  1372. // shared state or with the return from the last function that releases
  1373. // the shared state, whichever happens first.
  1374. virtual void _M_complete_async() { _M_join(); }
  1375. void _M_join() { std::call_once(_M_once, &thread::join, &_M_thread); }
  1376. thread _M_thread;
  1377. once_flag _M_once;
  1378. };
  1379. // Shared state created by std::async().
  1380. // Starts a new thread that runs a function and makes the shared state ready.
  1381. template<typename _BoundFn, typename _Res>
  1382. class __future_base::_Async_state_impl final
  1383. : public __future_base::_Async_state_commonV2
  1384. {
  1385. public:
  1386. explicit
  1387. _Async_state_impl(_BoundFn&& __fn)
  1388. : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
  1389. {
  1390. _M_thread = std::thread{ [this] {
  1391. __try
  1392. {
  1393. _M_set_result(_S_task_setter(_M_result, _M_fn));
  1394. }
  1395. __catch (const __cxxabiv1::__forced_unwind&)
  1396. {
  1397. // make the shared state ready on thread cancellation
  1398. if (static_cast<bool>(_M_result))
  1399. this->_M_break_promise(std::move(_M_result));
  1400. __throw_exception_again;
  1401. }
  1402. } };
  1403. }
  1404. // Must not destroy _M_result and _M_fn until the thread finishes.
  1405. // Call join() directly rather than through _M_join() because no other
  1406. // thread can be referring to this state if it is being destroyed.
  1407. ~_Async_state_impl() { if (_M_thread.joinable()) _M_thread.join(); }
  1408. private:
  1409. typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
  1410. _Ptr_type _M_result;
  1411. _BoundFn _M_fn;
  1412. };
  1413. template<typename _BoundFn>
  1414. inline std::shared_ptr<__future_base::_State_base>
  1415. __future_base::_S_make_deferred_state(_BoundFn&& __fn)
  1416. {
  1417. typedef typename remove_reference<_BoundFn>::type __fn_type;
  1418. typedef _Deferred_state<__fn_type> __state_type;
  1419. return std::make_shared<__state_type>(std::move(__fn));
  1420. }
  1421. template<typename _BoundFn>
  1422. inline std::shared_ptr<__future_base::_State_base>
  1423. __future_base::_S_make_async_state(_BoundFn&& __fn)
  1424. {
  1425. typedef typename remove_reference<_BoundFn>::type __fn_type;
  1426. typedef _Async_state_impl<__fn_type> __state_type;
  1427. return std::make_shared<__state_type>(std::move(__fn));
  1428. }
  1429. /// async
  1430. template<typename _Fn, typename... _Args>
  1431. _GLIBCXX_NODISCARD future<__async_result_of<_Fn, _Args...>>
  1432. async(launch __policy, _Fn&& __fn, _Args&&... __args)
  1433. {
  1434. std::shared_ptr<__future_base::_State_base> __state;
  1435. if ((__policy & launch::async) == launch::async)
  1436. {
  1437. __try
  1438. {
  1439. __state = __future_base::_S_make_async_state(
  1440. std::thread::__make_invoker(std::forward<_Fn>(__fn),
  1441. std::forward<_Args>(__args)...)
  1442. );
  1443. }
  1444. #if __cpp_exceptions
  1445. catch(const system_error& __e)
  1446. {
  1447. if (__e.code() != errc::resource_unavailable_try_again
  1448. || (__policy & launch::deferred) != launch::deferred)
  1449. throw;
  1450. }
  1451. #endif
  1452. }
  1453. if (!__state)
  1454. {
  1455. __state = __future_base::_S_make_deferred_state(
  1456. std::thread::__make_invoker(std::forward<_Fn>(__fn),
  1457. std::forward<_Args>(__args)...));
  1458. }
  1459. return future<__async_result_of<_Fn, _Args...>>(__state);
  1460. }
  1461. /// async, potential overload
  1462. template<typename _Fn, typename... _Args>
  1463. _GLIBCXX_NODISCARD inline future<__async_result_of<_Fn, _Args...>>
  1464. async(_Fn&& __fn, _Args&&... __args)
  1465. {
  1466. return std::async(launch::async|launch::deferred,
  1467. std::forward<_Fn>(__fn),
  1468. std::forward<_Args>(__args)...);
  1469. }
  1470. #endif // _GLIBCXX_ASYNC_ABI_COMPAT
  1471. #endif // _GLIBCXX_HAS_GTHREADS
  1472. // @} group futures
  1473. _GLIBCXX_END_NAMESPACE_VERSION
  1474. } // namespace
  1475. #endif // C++11
  1476. #endif // _GLIBCXX_FUTURE