future 52 KB

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