future 50 KB

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