future 49 KB

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