future 51 KB

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