future 49 KB

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