future 50 KB

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