1 // <future> -*- C++ -*-
3 // Copyright (C) 2009-2016 Free Software Foundation, Inc.
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)
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.
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.
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/>.
25 /** @file include/future
26 * This is a Standard C++ Library header.
29 #ifndef _GLIBCXX_FUTURE
30 #define _GLIBCXX_FUTURE 1
32 #pragma GCC system_header
34 #if __cplusplus < 201103L
35 # include <bits/c++0x_warning.h>
40 #include <condition_variable>
41 #include <system_error>
43 #include <bits/atomic_futex.h>
44 #include <bits/functexcept.h>
45 #include <bits/invoke.h>
46 #include <bits/unique_ptr.h>
47 #include <bits/shared_ptr.h>
48 #include <bits/std_function.h>
49 #include <bits/uses_allocator.h>
50 #include <bits/allocated_ptr.h>
51 #include <ext/aligned_buffer.h>
53 namespace std _GLIBCXX_VISIBILITY(default)
55 _GLIBCXX_BEGIN_NAMESPACE_VERSION
58 * @defgroup futures Futures
59 * @ingroup concurrency
61 * Classes for futures support.
65 /// Error code for futures
66 enum class future_errc
68 future_already_retrieved = 1,
69 promise_already_satisfied,
76 struct is_error_code_enum<future_errc> : public true_type { };
78 /// Points to a statically-allocated object derived from error_category.
80 future_category() noexcept;
82 /// Overload for make_error_code.
84 make_error_code(future_errc __errc) noexcept
85 { return error_code(static_cast<int>(__errc), future_category()); }
87 /// Overload for make_error_condition.
88 inline error_condition
89 make_error_condition(future_errc __errc) noexcept
90 { return error_condition(static_cast<int>(__errc), future_category()); }
93 * @brief Exception type thrown by futures.
96 class future_error : public logic_error
101 explicit future_error(error_code __ec)
102 : logic_error("std::future_error: " + __ec.message()), _M_code(__ec)
105 virtual ~future_error() noexcept;
108 what() const noexcept;
111 code() const noexcept { return _M_code; }
114 // Forward declarations.
115 template<typename _Res>
118 template<typename _Res>
121 template<typename _Signature>
124 template<typename _Res>
127 /// Launch code for futures
134 constexpr launch operator&(launch __x, launch __y)
136 return static_cast<launch>(
137 static_cast<int>(__x) & static_cast<int>(__y));
140 constexpr launch operator|(launch __x, launch __y)
142 return static_cast<launch>(
143 static_cast<int>(__x) | static_cast<int>(__y));
146 constexpr launch operator^(launch __x, launch __y)
148 return static_cast<launch>(
149 static_cast<int>(__x) ^ static_cast<int>(__y));
152 constexpr launch operator~(launch __x)
153 { return static_cast<launch>(~static_cast<int>(__x)); }
155 inline launch& operator&=(launch& __x, launch __y)
156 { return __x = __x & __y; }
158 inline launch& operator|=(launch& __x, launch __y)
159 { return __x = __x | __y; }
161 inline launch& operator^=(launch& __x, launch __y)
162 { return __x = __x ^ __y; }
164 /// Status code for futures
165 enum class future_status
172 // _GLIBCXX_RESOLVE_LIB_DEFECTS
173 // 2021. Further incorrect usages of result_of
174 template<typename _Fn, typename... _Args>
175 using __async_result_of = typename result_of<
176 typename decay<_Fn>::type(typename decay<_Args>::type...)>::type;
178 template<typename _Fn, typename... _Args>
179 future<__async_result_of<_Fn, _Args...>>
180 async(launch __policy, _Fn&& __fn, _Args&&... __args);
182 template<typename _Fn, typename... _Args>
183 future<__async_result_of<_Fn, _Args...>>
184 async(_Fn&& __fn, _Args&&... __args);
186 #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) \
187 && (ATOMIC_INT_LOCK_FREE > 1)
189 /// Base class and enclosing scope.
192 /// Base class for results.
195 exception_ptr _M_error;
197 _Result_base(const _Result_base&) = delete;
198 _Result_base& operator=(const _Result_base&) = delete;
200 // _M_destroy() allows derived classes to control deallocation
201 virtual void _M_destroy() = 0;
205 void operator()(_Result_base* __fr) const { __fr->_M_destroy(); }
210 virtual ~_Result_base();
213 /// A unique_ptr for result objects.
214 template<typename _Res>
215 using _Ptr = unique_ptr<_Res, _Result_base::_Deleter>;
217 /// A result object that has storage for an object of type _Res.
218 template<typename _Res>
219 struct _Result : _Result_base
222 __gnu_cxx::__aligned_buffer<_Res> _M_storage;
226 typedef _Res result_type;
228 _Result() noexcept : _M_initialized() { }
236 // Return lvalue, future will add const or rvalue-reference
238 _M_value() noexcept { return *_M_storage._M_ptr(); }
241 _M_set(const _Res& __res)
243 ::new (_M_storage._M_addr()) _Res(__res);
244 _M_initialized = true;
250 ::new (_M_storage._M_addr()) _Res(std::move(__res));
251 _M_initialized = true;
255 void _M_destroy() { delete this; }
258 /// A result object that uses an allocator.
259 template<typename _Res, typename _Alloc>
260 struct _Result_alloc final : _Result<_Res>, _Alloc
262 using __allocator_type = __alloc_rebind<_Alloc, _Result_alloc>;
265 _Result_alloc(const _Alloc& __a) : _Result<_Res>(), _Alloc(__a)
271 __allocator_type __a(*this);
272 __allocated_ptr<__allocator_type> __guard_ptr{ __a, this };
273 this->~_Result_alloc();
277 // Create a result object that uses an allocator.
278 template<typename _Res, typename _Allocator>
279 static _Ptr<_Result_alloc<_Res, _Allocator>>
280 _S_allocate_result(const _Allocator& __a)
282 using __result_type = _Result_alloc<_Res, _Allocator>;
283 typename __result_type::__allocator_type __a2(__a);
284 auto __guard = std::__allocate_guarded(__a2);
285 __result_type* __p = ::new((void*)__guard.get()) __result_type{__a};
287 return _Ptr<__result_type>(__p);
290 // Keep it simple for std::allocator.
291 template<typename _Res, typename _Tp>
292 static _Ptr<_Result<_Res>>
293 _S_allocate_result(const std::allocator<_Tp>& __a)
295 return _Ptr<_Result<_Res>>(new _Result<_Res>);
298 // Base class for various types of shared state created by an
299 // asynchronous provider (such as a std::promise) and shared with one
300 // or more associated futures.
303 typedef _Ptr<_Result_base> _Ptr_type;
305 enum _Status : unsigned {
311 __atomic_futex_unsigned<> _M_status;
312 atomic_flag _M_retrieved = ATOMIC_FLAG_INIT;
316 _State_baseV2() noexcept : _M_result(), _M_status(_Status::__not_ready)
318 _State_baseV2(const _State_baseV2&) = delete;
319 _State_baseV2& operator=(const _State_baseV2&) = delete;
320 virtual ~_State_baseV2() = default;
325 // Run any deferred function or join any asynchronous thread:
327 // Acquire MO makes sure this synchronizes with the thread that made
329 _M_status._M_load_when_equal(_Status::__ready, memory_order_acquire);
333 template<typename _Rep, typename _Period>
335 wait_for(const chrono::duration<_Rep, _Period>& __rel)
337 // First, check if the future has been made ready. Use acquire MO
338 // to synchronize with the thread that made it ready.
339 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
340 return future_status::ready;
341 if (_M_is_deferred_future())
342 return future_status::deferred;
343 if (_M_status._M_load_when_equal_for(_Status::__ready,
344 memory_order_acquire, __rel))
346 // _GLIBCXX_RESOLVE_LIB_DEFECTS
347 // 2100. timed waiting functions must also join
348 // This call is a no-op by default except on an async future,
349 // in which case the async thread is joined. It's also not a
350 // no-op for a deferred future, but such a future will never
351 // reach this point because it returns future_status::deferred
352 // instead of waiting for the future to become ready (see
353 // above). Async futures synchronize in this call, so we need
354 // no further synchronization here.
357 return future_status::ready;
359 return future_status::timeout;
362 template<typename _Clock, typename _Duration>
364 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
366 // First, check if the future has been made ready. Use acquire MO
367 // to synchronize with the thread that made it ready.
368 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
369 return future_status::ready;
370 if (_M_is_deferred_future())
371 return future_status::deferred;
372 if (_M_status._M_load_when_equal_until(_Status::__ready,
373 memory_order_acquire, __abs))
375 // _GLIBCXX_RESOLVE_LIB_DEFECTS
376 // 2100. timed waiting functions must also join
377 // See wait_for(...) above.
380 return future_status::ready;
382 return future_status::timeout;
385 // Provide a result to the shared state and make it ready.
386 // Calls at most once: _M_result = __res();
388 _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
390 bool __did_set = false;
391 // all calls to this function are serialized,
392 // side-effects of invoking __res only happen once
393 call_once(_M_once, &_State_baseV2::_M_do_set, this,
394 std::__addressof(__res), std::__addressof(__did_set));
396 // Use release MO to synchronize with observers of the ready state.
397 _M_status._M_store_notify_all(_Status::__ready,
398 memory_order_release);
399 else if (!__ignore_failure)
400 __throw_future_error(int(future_errc::promise_already_satisfied));
403 // Provide a result to the shared state but delay making it ready
404 // until the calling thread exits.
405 // Calls at most once: _M_result = __res();
407 _M_set_delayed_result(function<_Ptr_type()> __res,
408 weak_ptr<_State_baseV2> __self)
410 bool __did_set = false;
411 unique_ptr<_Make_ready> __mr{new _Make_ready};
412 // all calls to this function are serialized,
413 // side-effects of invoking __res only happen once
414 call_once(_M_once, &_State_baseV2::_M_do_set, this,
415 std::__addressof(__res), std::__addressof(__did_set));
417 __throw_future_error(int(future_errc::promise_already_satisfied));
418 __mr->_M_shared_state = std::move(__self);
423 // Abandon this shared state.
425 _M_break_promise(_Ptr_type __res)
427 if (static_cast<bool>(__res))
429 error_code __ec(make_error_code(future_errc::broken_promise));
430 __res->_M_error = make_exception_ptr(future_error(__ec));
431 // This function is only called when the last asynchronous result
432 // provider is abandoning this shared state, so noone can be
433 // trying to make the shared state ready at the same time, and
434 // we can access _M_result directly instead of through call_once.
435 _M_result.swap(__res);
436 // Use release MO to synchronize with observers of the ready state.
437 _M_status._M_store_notify_all(_Status::__ready,
438 memory_order_release);
442 // Called when this object is first passed to a future.
444 _M_set_retrieved_flag()
446 if (_M_retrieved.test_and_set())
447 __throw_future_error(int(future_errc::future_already_retrieved));
450 template<typename _Res, typename _Arg>
454 template<typename _Res, typename _Arg>
455 struct _Setter<_Res, _Arg&>
457 // check this is only used by promise<R>::set_value(const R&)
458 // or promise<R&>::set_value(R&)
459 static_assert(is_same<_Res, _Arg&>::value // promise<R&>
460 || is_same<const _Res, _Arg>::value, // promise<R>
461 "Invalid specialisation");
463 // Used by std::promise to copy construct the result.
464 typename promise<_Res>::_Ptr_type operator()() const
466 _State_baseV2::_S_check(_M_promise->_M_future);
467 _M_promise->_M_storage->_M_set(*_M_arg);
468 return std::move(_M_promise->_M_storage);
470 promise<_Res>* _M_promise;
475 template<typename _Res>
476 struct _Setter<_Res, _Res&&>
478 // Used by std::promise to move construct the result.
479 typename promise<_Res>::_Ptr_type operator()() const
481 _State_baseV2::_S_check(_M_promise->_M_future);
482 _M_promise->_M_storage->_M_set(std::move(*_M_arg));
483 return std::move(_M_promise->_M_storage);
485 promise<_Res>* _M_promise;
489 struct __exception_ptr_tag { };
492 template<typename _Res>
493 struct _Setter<_Res, __exception_ptr_tag>
495 // Used by std::promise to store an exception as the result.
496 typename promise<_Res>::_Ptr_type operator()() const
498 _State_baseV2::_S_check(_M_promise->_M_future);
499 _M_promise->_M_storage->_M_error = *_M_ex;
500 return std::move(_M_promise->_M_storage);
503 promise<_Res>* _M_promise;
504 exception_ptr* _M_ex;
507 template<typename _Res, typename _Arg>
508 static _Setter<_Res, _Arg&&>
509 __setter(promise<_Res>* __prom, _Arg&& __arg)
511 return _Setter<_Res, _Arg&&>{ __prom, std::__addressof(__arg) };
514 template<typename _Res>
515 static _Setter<_Res, __exception_ptr_tag>
516 __setter(exception_ptr& __ex, promise<_Res>* __prom)
518 return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex };
521 template<typename _Tp>
523 _S_check(const shared_ptr<_Tp>& __p)
525 if (!static_cast<bool>(__p))
526 __throw_future_error((int)future_errc::no_state);
530 // The function invoked with std::call_once(_M_once, ...).
532 _M_do_set(function<_Ptr_type()>* __f, bool* __did_set)
534 _Ptr_type __res = (*__f)();
535 // Notify the caller that we did try to set; if we do not throw an
536 // exception, the caller will be aware that it did set (e.g., see
539 _M_result.swap(__res); // nothrow
542 // Wait for completion of async function.
543 virtual void _M_complete_async() { }
545 // Return true if state corresponds to a deferred function.
546 virtual bool _M_is_deferred_future() const { return false; }
548 struct _Make_ready final : __at_thread_exit_elt
550 weak_ptr<_State_baseV2> _M_shared_state;
551 static void _S_run(void*);
556 #ifdef _GLIBCXX_ASYNC_ABI_COMPAT
558 class _Async_state_common;
560 using _State_base = _State_baseV2;
561 class _Async_state_commonV2;
564 template<typename _BoundFn,
565 typename _Res = decltype(std::declval<_BoundFn&>()())>
566 class _Deferred_state;
568 template<typename _BoundFn,
569 typename _Res = decltype(std::declval<_BoundFn&>()())>
570 class _Async_state_impl;
572 template<typename _Signature>
573 class _Task_state_base;
575 template<typename _Fn, typename _Alloc, typename _Signature>
578 template<typename _BoundFn>
579 static std::shared_ptr<_State_base>
580 _S_make_deferred_state(_BoundFn&& __fn);
582 template<typename _BoundFn>
583 static std::shared_ptr<_State_base>
584 _S_make_async_state(_BoundFn&& __fn);
586 template<typename _Res_ptr, typename _Fn,
587 typename _Res = typename _Res_ptr::element_type::result_type>
590 template<typename _Res_ptr, typename _BoundFn>
591 static _Task_setter<_Res_ptr, _BoundFn>
592 _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call)
594 return { std::__addressof(__ptr), std::__addressof(__call) };
598 /// Partial specialization for reference types.
599 template<typename _Res>
600 struct __future_base::_Result<_Res&> : __future_base::_Result_base
602 typedef _Res& result_type;
604 _Result() noexcept : _M_value_ptr() { }
607 _M_set(_Res& __res) noexcept
608 { _M_value_ptr = std::addressof(__res); }
610 _Res& _M_get() noexcept { return *_M_value_ptr; }
615 void _M_destroy() { delete this; }
618 /// Explicit specialization for void.
620 struct __future_base::_Result<void> : __future_base::_Result_base
622 typedef void result_type;
625 void _M_destroy() { delete this; }
628 #ifndef _GLIBCXX_ASYNC_ABI_COMPAT
630 // Allow _Setter objects to be stored locally in std::function
631 template<typename _Res, typename _Arg>
632 struct __is_location_invariant
633 <__future_base::_State_base::_Setter<_Res, _Arg>>
636 // Allow _Task_setter objects to be stored locally in std::function
637 template<typename _Res_ptr, typename _Fn, typename _Res>
638 struct __is_location_invariant
639 <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>>
642 /// Common implementation for future and shared_future.
643 template<typename _Res>
644 class __basic_future : public __future_base
647 typedef shared_ptr<_State_base> __state_type;
648 typedef __future_base::_Result<_Res>& __result_type;
651 __state_type _M_state;
655 __basic_future(const __basic_future&) = delete;
656 __basic_future& operator=(const __basic_future&) = delete;
659 valid() const noexcept { return static_cast<bool>(_M_state); }
664 _State_base::_S_check(_M_state);
668 template<typename _Rep, typename _Period>
670 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
672 _State_base::_S_check(_M_state);
673 return _M_state->wait_for(__rel);
676 template<typename _Clock, typename _Duration>
678 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
680 _State_base::_S_check(_M_state);
681 return _M_state->wait_until(__abs);
685 /// Wait for the state to be ready and rethrow any stored exception
687 _M_get_result() const
689 _State_base::_S_check(_M_state);
690 _Result_base& __res = _M_state->wait();
691 if (!(__res._M_error == 0))
692 rethrow_exception(__res._M_error);
693 return static_cast<__result_type>(__res);
696 void _M_swap(__basic_future& __that) noexcept
698 _M_state.swap(__that._M_state);
701 // Construction of a future by promise::get_future()
703 __basic_future(const __state_type& __state) : _M_state(__state)
705 _State_base::_S_check(_M_state);
706 _M_state->_M_set_retrieved_flag();
709 // Copy construction from a shared_future
711 __basic_future(const shared_future<_Res>&) noexcept;
713 // Move construction from a shared_future
715 __basic_future(shared_future<_Res>&&) noexcept;
717 // Move construction from a future
719 __basic_future(future<_Res>&&) noexcept;
721 constexpr __basic_future() noexcept : _M_state() { }
725 explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { }
726 ~_Reset() { _M_fut._M_state.reset(); }
727 __basic_future& _M_fut;
732 /// Primary template for future.
733 template<typename _Res>
734 class future : public __basic_future<_Res>
736 friend class promise<_Res>;
737 template<typename> friend class packaged_task;
738 template<typename _Fn, typename... _Args>
739 friend future<__async_result_of<_Fn, _Args...>>
740 async(launch, _Fn&&, _Args&&...);
742 typedef __basic_future<_Res> _Base_type;
743 typedef typename _Base_type::__state_type __state_type;
746 future(const __state_type& __state) : _Base_type(__state) { }
749 constexpr future() noexcept : _Base_type() { }
752 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
755 future(const future&) = delete;
756 future& operator=(const future&) = delete;
758 future& operator=(future&& __fut) noexcept
760 future(std::move(__fut))._M_swap(*this);
764 /// Retrieving the value
768 typename _Base_type::_Reset __reset(*this);
769 return std::move(this->_M_get_result()._M_value());
772 shared_future<_Res> share();
775 /// Partial specialization for future<R&>
776 template<typename _Res>
777 class future<_Res&> : public __basic_future<_Res&>
779 friend class promise<_Res&>;
780 template<typename> friend class packaged_task;
781 template<typename _Fn, typename... _Args>
782 friend future<__async_result_of<_Fn, _Args...>>
783 async(launch, _Fn&&, _Args&&...);
785 typedef __basic_future<_Res&> _Base_type;
786 typedef typename _Base_type::__state_type __state_type;
789 future(const __state_type& __state) : _Base_type(__state) { }
792 constexpr future() noexcept : _Base_type() { }
795 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
798 future(const future&) = delete;
799 future& operator=(const future&) = delete;
801 future& operator=(future&& __fut) noexcept
803 future(std::move(__fut))._M_swap(*this);
807 /// Retrieving the value
811 typename _Base_type::_Reset __reset(*this);
812 return this->_M_get_result()._M_get();
815 shared_future<_Res&> share();
818 /// Explicit specialization for future<void>
820 class future<void> : public __basic_future<void>
822 friend class promise<void>;
823 template<typename> friend class packaged_task;
824 template<typename _Fn, typename... _Args>
825 friend future<__async_result_of<_Fn, _Args...>>
826 async(launch, _Fn&&, _Args&&...);
828 typedef __basic_future<void> _Base_type;
829 typedef typename _Base_type::__state_type __state_type;
832 future(const __state_type& __state) : _Base_type(__state) { }
835 constexpr future() noexcept : _Base_type() { }
838 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
841 future(const future&) = delete;
842 future& operator=(const future&) = delete;
844 future& operator=(future&& __fut) noexcept
846 future(std::move(__fut))._M_swap(*this);
850 /// Retrieving the value
854 typename _Base_type::_Reset __reset(*this);
855 this->_M_get_result();
858 shared_future<void> share();
862 /// Primary template for shared_future.
863 template<typename _Res>
864 class shared_future : public __basic_future<_Res>
866 typedef __basic_future<_Res> _Base_type;
869 constexpr shared_future() noexcept : _Base_type() { }
872 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
874 /// Construct from a future rvalue
875 shared_future(future<_Res>&& __uf) noexcept
876 : _Base_type(std::move(__uf))
879 /// Construct from a shared_future rvalue
880 shared_future(shared_future&& __sf) noexcept
881 : _Base_type(std::move(__sf))
884 shared_future& operator=(const shared_future& __sf)
886 shared_future(__sf)._M_swap(*this);
890 shared_future& operator=(shared_future&& __sf) noexcept
892 shared_future(std::move(__sf))._M_swap(*this);
896 /// Retrieving the value
898 get() const { return this->_M_get_result()._M_value(); }
901 /// Partial specialization for shared_future<R&>
902 template<typename _Res>
903 class shared_future<_Res&> : public __basic_future<_Res&>
905 typedef __basic_future<_Res&> _Base_type;
908 constexpr shared_future() noexcept : _Base_type() { }
911 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
913 /// Construct from a future rvalue
914 shared_future(future<_Res&>&& __uf) noexcept
915 : _Base_type(std::move(__uf))
918 /// Construct from a shared_future rvalue
919 shared_future(shared_future&& __sf) noexcept
920 : _Base_type(std::move(__sf))
923 shared_future& operator=(const shared_future& __sf)
925 shared_future(__sf)._M_swap(*this);
929 shared_future& operator=(shared_future&& __sf) noexcept
931 shared_future(std::move(__sf))._M_swap(*this);
935 /// Retrieving the value
937 get() const { return this->_M_get_result()._M_get(); }
940 /// Explicit specialization for shared_future<void>
942 class shared_future<void> : public __basic_future<void>
944 typedef __basic_future<void> _Base_type;
947 constexpr shared_future() noexcept : _Base_type() { }
950 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
952 /// Construct from a future rvalue
953 shared_future(future<void>&& __uf) noexcept
954 : _Base_type(std::move(__uf))
957 /// Construct from a shared_future rvalue
958 shared_future(shared_future&& __sf) noexcept
959 : _Base_type(std::move(__sf))
962 shared_future& operator=(const shared_future& __sf)
964 shared_future(__sf)._M_swap(*this);
968 shared_future& operator=(shared_future&& __sf) noexcept
970 shared_future(std::move(__sf))._M_swap(*this);
974 // Retrieving the value
976 get() const { this->_M_get_result(); }
979 // Now we can define the protected __basic_future constructors.
980 template<typename _Res>
981 inline __basic_future<_Res>::
982 __basic_future(const shared_future<_Res>& __sf) noexcept
983 : _M_state(__sf._M_state)
986 template<typename _Res>
987 inline __basic_future<_Res>::
988 __basic_future(shared_future<_Res>&& __sf) noexcept
989 : _M_state(std::move(__sf._M_state))
992 template<typename _Res>
993 inline __basic_future<_Res>::
994 __basic_future(future<_Res>&& __uf) noexcept
995 : _M_state(std::move(__uf._M_state))
998 template<typename _Res>
999 inline shared_future<_Res>
1000 future<_Res>::share()
1001 { return shared_future<_Res>(std::move(*this)); }
1003 template<typename _Res>
1004 inline shared_future<_Res&>
1005 future<_Res&>::share()
1006 { return shared_future<_Res&>(std::move(*this)); }
1008 inline shared_future<void>
1009 future<void>::share()
1010 { return shared_future<void>(std::move(*this)); }
1012 /// Primary template for promise
1013 template<typename _Res>
1016 typedef __future_base::_State_base _State;
1017 typedef __future_base::_Result<_Res> _Res_type;
1018 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1019 template<typename, typename> friend class _State::_Setter;
1021 shared_ptr<_State> _M_future;
1022 _Ptr_type _M_storage;
1026 : _M_future(std::make_shared<_State>()),
1027 _M_storage(new _Res_type())
1030 promise(promise&& __rhs) noexcept
1031 : _M_future(std::move(__rhs._M_future)),
1032 _M_storage(std::move(__rhs._M_storage))
1035 template<typename _Allocator>
1036 promise(allocator_arg_t, const _Allocator& __a)
1037 : _M_future(std::allocate_shared<_State>(__a)),
1038 _M_storage(__future_base::_S_allocate_result<_Res>(__a))
1041 template<typename _Allocator>
1042 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1043 : _M_future(std::move(__rhs._M_future)),
1044 _M_storage(std::move(__rhs._M_storage))
1047 promise(const promise&) = delete;
1051 if (static_cast<bool>(_M_future) && !_M_future.unique())
1052 _M_future->_M_break_promise(std::move(_M_storage));
1057 operator=(promise&& __rhs) noexcept
1059 promise(std::move(__rhs)).swap(*this);
1063 promise& operator=(const promise&) = delete;
1066 swap(promise& __rhs) noexcept
1068 _M_future.swap(__rhs._M_future);
1069 _M_storage.swap(__rhs._M_storage);
1072 // Retrieving the result
1075 { return future<_Res>(_M_future); }
1077 // Setting the result
1079 set_value(const _Res& __r)
1080 { _M_future->_M_set_result(_State::__setter(this, __r)); }
1083 set_value(_Res&& __r)
1084 { _M_future->_M_set_result(_State::__setter(this, std::move(__r))); }
1087 set_exception(exception_ptr __p)
1088 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1091 set_value_at_thread_exit(const _Res& __r)
1093 _M_future->_M_set_delayed_result(_State::__setter(this, __r),
1098 set_value_at_thread_exit(_Res&& __r)
1100 _M_future->_M_set_delayed_result(
1101 _State::__setter(this, std::move(__r)), _M_future);
1105 set_exception_at_thread_exit(exception_ptr __p)
1107 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1112 template<typename _Res>
1114 swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
1117 template<typename _Res, typename _Alloc>
1118 struct uses_allocator<promise<_Res>, _Alloc>
1119 : public true_type { };
1122 /// Partial specialization for promise<R&>
1123 template<typename _Res>
1124 class promise<_Res&>
1126 typedef __future_base::_State_base _State;
1127 typedef __future_base::_Result<_Res&> _Res_type;
1128 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1129 template<typename, typename> friend class _State::_Setter;
1131 shared_ptr<_State> _M_future;
1132 _Ptr_type _M_storage;
1136 : _M_future(std::make_shared<_State>()),
1137 _M_storage(new _Res_type())
1140 promise(promise&& __rhs) noexcept
1141 : _M_future(std::move(__rhs._M_future)),
1142 _M_storage(std::move(__rhs._M_storage))
1145 template<typename _Allocator>
1146 promise(allocator_arg_t, const _Allocator& __a)
1147 : _M_future(std::allocate_shared<_State>(__a)),
1148 _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
1151 template<typename _Allocator>
1152 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1153 : _M_future(std::move(__rhs._M_future)),
1154 _M_storage(std::move(__rhs._M_storage))
1157 promise(const promise&) = delete;
1161 if (static_cast<bool>(_M_future) && !_M_future.unique())
1162 _M_future->_M_break_promise(std::move(_M_storage));
1167 operator=(promise&& __rhs) noexcept
1169 promise(std::move(__rhs)).swap(*this);
1173 promise& operator=(const promise&) = delete;
1176 swap(promise& __rhs) noexcept
1178 _M_future.swap(__rhs._M_future);
1179 _M_storage.swap(__rhs._M_storage);
1182 // Retrieving the result
1185 { return future<_Res&>(_M_future); }
1187 // Setting the result
1189 set_value(_Res& __r)
1190 { _M_future->_M_set_result(_State::__setter(this, __r)); }
1193 set_exception(exception_ptr __p)
1194 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1197 set_value_at_thread_exit(_Res& __r)
1199 _M_future->_M_set_delayed_result(_State::__setter(this, __r),
1204 set_exception_at_thread_exit(exception_ptr __p)
1206 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1211 /// Explicit specialization for promise<void>
1215 typedef __future_base::_State_base _State;
1216 typedef __future_base::_Result<void> _Res_type;
1217 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1218 template<typename, typename> friend class _State::_Setter;
1220 shared_ptr<_State> _M_future;
1221 _Ptr_type _M_storage;
1225 : _M_future(std::make_shared<_State>()),
1226 _M_storage(new _Res_type())
1229 promise(promise&& __rhs) noexcept
1230 : _M_future(std::move(__rhs._M_future)),
1231 _M_storage(std::move(__rhs._M_storage))
1234 template<typename _Allocator>
1235 promise(allocator_arg_t, const _Allocator& __a)
1236 : _M_future(std::allocate_shared<_State>(__a)),
1237 _M_storage(__future_base::_S_allocate_result<void>(__a))
1240 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1241 // 2095. missing constructors needed for uses-allocator construction
1242 template<typename _Allocator>
1243 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1244 : _M_future(std::move(__rhs._M_future)),
1245 _M_storage(std::move(__rhs._M_storage))
1248 promise(const promise&) = delete;
1252 if (static_cast<bool>(_M_future) && !_M_future.unique())
1253 _M_future->_M_break_promise(std::move(_M_storage));
1258 operator=(promise&& __rhs) noexcept
1260 promise(std::move(__rhs)).swap(*this);
1264 promise& operator=(const promise&) = delete;
1267 swap(promise& __rhs) noexcept
1269 _M_future.swap(__rhs._M_future);
1270 _M_storage.swap(__rhs._M_storage);
1273 // Retrieving the result
1276 { return future<void>(_M_future); }
1278 // Setting the result
1282 set_exception(exception_ptr __p)
1283 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1286 set_value_at_thread_exit();
1289 set_exception_at_thread_exit(exception_ptr __p)
1291 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1298 struct __future_base::_State_base::_Setter<void, void>
1300 promise<void>::_Ptr_type operator()() const
1302 _State_base::_S_check(_M_promise->_M_future);
1303 return std::move(_M_promise->_M_storage);
1306 promise<void>* _M_promise;
1310 promise<void>::set_value()
1311 { _M_future->_M_set_result(_State::_Setter<void, void>{ this }); }
1314 promise<void>::set_value_at_thread_exit()
1316 _M_future->_M_set_delayed_result(_State::_Setter<void, void>{this},
1320 template<typename _Ptr_type, typename _Fn, typename _Res>
1321 struct __future_base::_Task_setter
1323 // Invoke the function and provide the result to the caller.
1324 _Ptr_type operator()() const
1328 (*_M_result)->_M_set((*_M_fn)());
1330 __catch(const __cxxabiv1::__forced_unwind&)
1332 __throw_exception_again; // will cause broken_promise
1336 (*_M_result)->_M_error = current_exception();
1338 return std::move(*_M_result);
1340 _Ptr_type* _M_result;
1344 template<typename _Ptr_type, typename _Fn>
1345 struct __future_base::_Task_setter<_Ptr_type, _Fn, void>
1347 _Ptr_type operator()() const
1353 __catch(const __cxxabiv1::__forced_unwind&)
1355 __throw_exception_again; // will cause broken_promise
1359 (*_M_result)->_M_error = current_exception();
1361 return std::move(*_M_result);
1363 _Ptr_type* _M_result;
1367 // Holds storage for a packaged_task's result.
1368 template<typename _Res, typename... _Args>
1369 struct __future_base::_Task_state_base<_Res(_Args...)>
1370 : __future_base::_State_base
1372 typedef _Res _Res_type;
1374 template<typename _Alloc>
1375 _Task_state_base(const _Alloc& __a)
1376 : _M_result(_S_allocate_result<_Res>(__a))
1379 // Invoke the stored task and make the state ready.
1381 _M_run(_Args&&... __args) = 0;
1383 // Invoke the stored task and make the state ready at thread exit.
1385 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0;
1387 virtual shared_ptr<_Task_state_base>
1390 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1391 _Ptr_type _M_result;
1394 // Holds a packaged_task's stored task.
1395 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1396 struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final
1397 : __future_base::_Task_state_base<_Res(_Args...)>
1399 template<typename _Fn2>
1400 _Task_state(_Fn2&& __fn, const _Alloc& __a)
1401 : _Task_state_base<_Res(_Args...)>(__a),
1402 _M_impl(std::forward<_Fn2>(__fn), __a)
1407 _M_run(_Args&&... __args)
1409 auto __boundfn = [&] () -> typename result_of<_Fn(_Args&&...)>::type {
1410 return std::__invoke(_M_impl._M_fn, std::forward<_Args>(__args)...);
1412 this->_M_set_result(_S_task_setter(this->_M_result, __boundfn));
1416 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self)
1418 auto __boundfn = [&] () -> typename result_of<_Fn(_Args&&...)>::type {
1419 return std::__invoke(_M_impl._M_fn, std::forward<_Args>(__args)...);
1421 this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn),
1425 virtual shared_ptr<_Task_state_base<_Res(_Args...)>>
1428 struct _Impl : _Alloc
1430 template<typename _Fn2>
1431 _Impl(_Fn2&& __fn, const _Alloc& __a)
1432 : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { }
1437 template<typename _Signature, typename _Fn, typename _Alloc>
1438 static shared_ptr<__future_base::_Task_state_base<_Signature>>
1439 __create_task_state(_Fn&& __fn, const _Alloc& __a)
1441 typedef typename decay<_Fn>::type _Fn2;
1442 typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State;
1443 return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a);
1446 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1447 shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>>
1448 __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset()
1450 return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn),
1451 static_cast<_Alloc&>(_M_impl));
1454 template<typename _Task, typename _Fn, bool
1455 = is_same<_Task, typename decay<_Fn>::type>::value>
1456 struct __constrain_pkgdtask
1457 { typedef void __type; };
1459 template<typename _Task, typename _Fn>
1460 struct __constrain_pkgdtask<_Task, _Fn, true>
1464 template<typename _Res, typename... _ArgTypes>
1465 class packaged_task<_Res(_ArgTypes...)>
1467 typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type;
1468 shared_ptr<_State_type> _M_state;
1471 // Construction and destruction
1472 packaged_task() noexcept { }
1474 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1475 // 2095. missing constructors needed for uses-allocator construction
1476 template<typename _Allocator>
1477 packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
1480 template<typename _Fn, typename = typename
1481 __constrain_pkgdtask<packaged_task, _Fn>::__type>
1483 packaged_task(_Fn&& __fn)
1484 : packaged_task(allocator_arg, std::allocator<int>(),
1485 std::forward<_Fn>(__fn))
1488 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1489 // 2097. packaged_task constructors should be constrained
1490 // 2407. [this constructor should not be] explicit
1491 template<typename _Fn, typename _Alloc, typename = typename
1492 __constrain_pkgdtask<packaged_task, _Fn>::__type>
1493 packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn)
1494 : _M_state(__create_task_state<_Res(_ArgTypes...)>(
1495 std::forward<_Fn>(__fn), __a))
1500 if (static_cast<bool>(_M_state) && !_M_state.unique())
1501 _M_state->_M_break_promise(std::move(_M_state->_M_result));
1505 packaged_task(const packaged_task&) = delete;
1506 packaged_task& operator=(const packaged_task&) = delete;
1508 template<typename _Allocator>
1509 packaged_task(allocator_arg_t, const _Allocator&,
1510 const packaged_task&) = delete;
1513 packaged_task(packaged_task&& __other) noexcept
1514 { this->swap(__other); }
1516 template<typename _Allocator>
1517 packaged_task(allocator_arg_t, const _Allocator&,
1518 packaged_task&& __other) noexcept
1519 { this->swap(__other); }
1521 packaged_task& operator=(packaged_task&& __other) noexcept
1523 packaged_task(std::move(__other)).swap(*this);
1528 swap(packaged_task& __other) noexcept
1529 { _M_state.swap(__other._M_state); }
1532 valid() const noexcept
1533 { return static_cast<bool>(_M_state); }
1538 { return future<_Res>(_M_state); }
1542 operator()(_ArgTypes... __args)
1544 __future_base::_State_base::_S_check(_M_state);
1545 _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
1549 make_ready_at_thread_exit(_ArgTypes... __args)
1551 __future_base::_State_base::_S_check(_M_state);
1552 _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state);
1558 __future_base::_State_base::_S_check(_M_state);
1559 packaged_task __tmp;
1560 __tmp._M_state = _M_state;
1561 _M_state = _M_state->_M_reset();
1566 template<typename _Res, typename... _ArgTypes>
1568 swap(packaged_task<_Res(_ArgTypes...)>& __x,
1569 packaged_task<_Res(_ArgTypes...)>& __y) noexcept
1572 template<typename _Res, typename _Alloc>
1573 struct uses_allocator<packaged_task<_Res>, _Alloc>
1574 : public true_type { };
1577 // Shared state created by std::async().
1578 // Holds a deferred function and storage for its result.
1579 template<typename _BoundFn, typename _Res>
1580 class __future_base::_Deferred_state final
1581 : public __future_base::_State_base
1585 _Deferred_state(_BoundFn&& __fn)
1586 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1590 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1591 _Ptr_type _M_result;
1594 // Run the deferred function.
1598 // Multiple threads can call a waiting function on the future and
1599 // reach this point at the same time. The call_once in _M_set_result
1600 // ensures only the first one run the deferred function, stores the
1601 // result in _M_result, swaps that with the base _M_result and makes
1602 // the state ready. Tell _M_set_result to ignore failure so all later
1603 // calls do nothing.
1604 _M_set_result(_S_task_setter(_M_result, _M_fn), true);
1607 // Caller should check whether the state is ready first, because this
1608 // function will return true even after the deferred function has run.
1609 virtual bool _M_is_deferred_future() const { return true; }
1612 // Common functionality hoisted out of the _Async_state_impl template.
1613 class __future_base::_Async_state_commonV2
1614 : public __future_base::_State_base
1617 ~_Async_state_commonV2() = default;
1619 // Make waiting functions block until the thread completes, as if joined.
1621 // This function is used by wait() to satisfy the first requirement below
1622 // and by wait_for() / wait_until() to satisfy the second.
1626 // — a call to a waiting function on an asynchronous return object that
1627 // shares the shared state created by this async call shall block until
1628 // the associated thread has completed, as if joined, or else time out.
1630 // — the associated thread completion synchronizes with the return from
1631 // the first function that successfully detects the ready status of the
1632 // shared state or with the return from the last function that releases
1633 // the shared state, whichever happens first.
1634 virtual void _M_complete_async() { _M_join(); }
1636 void _M_join() { std::call_once(_M_once, &thread::join, &_M_thread); }
1642 // Shared state created by std::async().
1643 // Starts a new thread that runs a function and makes the shared state ready.
1644 template<typename _BoundFn, typename _Res>
1645 class __future_base::_Async_state_impl final
1646 : public __future_base::_Async_state_commonV2
1650 _Async_state_impl(_BoundFn&& __fn)
1651 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1653 _M_thread = std::thread{ [this] {
1656 _M_set_result(_S_task_setter(_M_result, _M_fn));
1658 __catch (const __cxxabiv1::__forced_unwind&)
1660 // make the shared state ready on thread cancellation
1661 if (static_cast<bool>(_M_result))
1662 this->_M_break_promise(std::move(_M_result));
1663 __throw_exception_again;
1668 // Must not destroy _M_result and _M_fn until the thread finishes.
1669 // Call join() directly rather than through _M_join() because no other
1670 // thread can be referring to this state if it is being destroyed.
1671 ~_Async_state_impl() { if (_M_thread.joinable()) _M_thread.join(); }
1674 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1675 _Ptr_type _M_result;
1679 template<typename _BoundFn>
1680 inline std::shared_ptr<__future_base::_State_base>
1681 __future_base::_S_make_deferred_state(_BoundFn&& __fn)
1683 typedef typename remove_reference<_BoundFn>::type __fn_type;
1684 typedef _Deferred_state<__fn_type> __state_type;
1685 return std::make_shared<__state_type>(std::move(__fn));
1688 template<typename _BoundFn>
1689 inline std::shared_ptr<__future_base::_State_base>
1690 __future_base::_S_make_async_state(_BoundFn&& __fn)
1692 typedef typename remove_reference<_BoundFn>::type __fn_type;
1693 typedef _Async_state_impl<__fn_type> __state_type;
1694 return std::make_shared<__state_type>(std::move(__fn));
1699 template<typename _Fn, typename... _Args>
1700 future<__async_result_of<_Fn, _Args...>>
1701 async(launch __policy, _Fn&& __fn, _Args&&... __args)
1703 std::shared_ptr<__future_base::_State_base> __state;
1704 if ((__policy & launch::async) == launch::async)
1708 __state = __future_base::_S_make_async_state(
1709 std::thread::__make_invoker(std::forward<_Fn>(__fn),
1710 std::forward<_Args>(__args)...)
1713 #if __cpp_exceptions
1714 catch(const system_error& __e)
1716 if (__e.code() != errc::resource_unavailable_try_again
1717 || (__policy & launch::deferred) != launch::deferred)
1724 __state = __future_base::_S_make_deferred_state(
1725 std::thread::__make_invoker(std::forward<_Fn>(__fn),
1726 std::forward<_Args>(__args)...));
1728 return future<__async_result_of<_Fn, _Args...>>(__state);
1731 /// async, potential overload
1732 template<typename _Fn, typename... _Args>
1733 inline future<__async_result_of<_Fn, _Args...>>
1734 async(_Fn&& __fn, _Args&&... __args)
1736 return std::async(launch::async|launch::deferred,
1737 std::forward<_Fn>(__fn),
1738 std::forward<_Args>(__args)...);
1741 #endif // _GLIBCXX_ASYNC_ABI_COMPAT
1742 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
1743 // && ATOMIC_INT_LOCK_FREE
1746 _GLIBCXX_END_NAMESPACE_VERSION
1751 #endif // _GLIBCXX_FUTURE