future 51 KB

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