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