future 50 KB

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