future 49 KB

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