3// Copyright (C) 2009-2021 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>
38#include <mutex> // call_once
39#include <condition_variable> // __at_thread_exit_elt
40#include <system_error>
42#include <bits/allocated_ptr.h>
43#include <bits/atomic_futex.h>
44#include <bits/invoke.h>
45#include <bits/unique_ptr.h>
46#include <bits/shared_ptr.h>
47#include <bits/std_function.h>
48#include <bits/std_thread.h>
49#include <bits/uses_allocator.h>
50#include <ext/aligned_buffer.h>
52namespace std _GLIBCXX_VISIBILITY(default)
54_GLIBCXX_BEGIN_NAMESPACE_VERSION
57 * @defgroup futures Futures
58 * @ingroup concurrency
60 * Classes for futures support.
64 /// Error code for futures
65 enum class future_errc
67 future_already_retrieved = 1,
68 promise_already_satisfied,
75 struct is_error_code_enum<future_errc> : public true_type { };
77 /// Points to a statically-allocated object derived from error_category.
79 future_category() noexcept;
81 /// Overload for make_error_code.
83 make_error_code(future_errc __errc) noexcept
84 { return error_code(static_cast<int>(__errc), future_category()); }
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()); }
92 * @brief Exception type thrown by futures.
95 class future_error : public logic_error
99 future_error(future_errc __errc)
100 : future_error(std::make_error_code(__errc))
103 virtual ~future_error() noexcept;
106 what() const noexcept;
109 code() const noexcept { return _M_code; }
113 future_error(error_code __ec)
114 : logic_error("std::future_error: " + __ec.message()), _M_code(__ec)
117 friend void __throw_future_error(int);
122 // Forward declarations.
123 template<typename _Res>
126 template<typename _Res>
129 template<typename _Signature>
132 template<typename _Res>
135 /// Launch code for futures
142 constexpr launch operator&(launch __x, launch __y) noexcept
144 return static_cast<launch>(
145 static_cast<int>(__x) & static_cast<int>(__y));
148 constexpr launch operator|(launch __x, launch __y) noexcept
150 return static_cast<launch>(
151 static_cast<int>(__x) | static_cast<int>(__y));
154 constexpr launch operator^(launch __x, launch __y) noexcept
156 return static_cast<launch>(
157 static_cast<int>(__x) ^ static_cast<int>(__y));
160 constexpr launch operator~(launch __x) noexcept
161 { return static_cast<launch>(~static_cast<int>(__x)); }
163 inline launch& operator&=(launch& __x, launch __y) noexcept
164 { return __x = __x & __y; }
166 inline launch& operator|=(launch& __x, launch __y) noexcept
167 { return __x = __x | __y; }
169 inline launch& operator^=(launch& __x, launch __y) noexcept
170 { return __x = __x ^ __y; }
172 /// Status code for futures
173 enum class future_status
180 // _GLIBCXX_RESOLVE_LIB_DEFECTS
181 // 2021. Further incorrect usages of result_of
182 template<typename _Fn, typename... _Args>
183 using __async_result_of = typename __invoke_result<
184 typename decay<_Fn>::type, typename decay<_Args>::type...>::type;
186 template<typename _Fn, typename... _Args>
187 future<__async_result_of<_Fn, _Args...>>
188 async(launch __policy, _Fn&& __fn, _Args&&... __args);
190 template<typename _Fn, typename... _Args>
191 future<__async_result_of<_Fn, _Args...>>
192 async(_Fn&& __fn, _Args&&... __args);
194#if defined(_GLIBCXX_HAS_GTHREADS)
196 /// Base class and enclosing scope.
199 /// Base class for results.
202 exception_ptr _M_error;
204 _Result_base(const _Result_base&) = delete;
205 _Result_base& operator=(const _Result_base&) = delete;
207 // _M_destroy() allows derived classes to control deallocation
208 virtual void _M_destroy() = 0;
212 void operator()(_Result_base* __fr) const { __fr->_M_destroy(); }
217 virtual ~_Result_base();
220 /// A unique_ptr for result objects.
221 template<typename _Res>
222 using _Ptr = unique_ptr<_Res, _Result_base::_Deleter>;
224 /// A result object that has storage for an object of type _Res.
225 template<typename _Res>
226 struct _Result : _Result_base
229 __gnu_cxx::__aligned_buffer<_Res> _M_storage;
233 typedef _Res result_type;
235 _Result() noexcept : _M_initialized() { }
243 // Return lvalue, future will add const or rvalue-reference
245 _M_value() noexcept { return *_M_storage._M_ptr(); }
248 _M_set(const _Res& __res)
250 ::new (_M_storage._M_addr()) _Res(__res);
251 _M_initialized = true;
257 ::new (_M_storage._M_addr()) _Res(std::move(__res));
258 _M_initialized = true;
262 void _M_destroy() { delete this; }
265 /// A result object that uses an allocator.
266 template<typename _Res, typename _Alloc>
267 struct _Result_alloc final : _Result<_Res>, _Alloc
269 using __allocator_type = __alloc_rebind<_Alloc, _Result_alloc>;
272 _Result_alloc(const _Alloc& __a) : _Result<_Res>(), _Alloc(__a)
278 __allocator_type __a(*this);
279 __allocated_ptr<__allocator_type> __guard_ptr{ __a, this };
280 this->~_Result_alloc();
284 // Create a result object that uses an allocator.
285 template<typename _Res, typename _Allocator>
286 static _Ptr<_Result_alloc<_Res, _Allocator>>
287 _S_allocate_result(const _Allocator& __a)
289 using __result_type = _Result_alloc<_Res, _Allocator>;
290 typename __result_type::__allocator_type __a2(__a);
291 auto __guard = std::__allocate_guarded(__a2);
292 __result_type* __p = ::new((void*)__guard.get()) __result_type{__a};
294 return _Ptr<__result_type>(__p);
297 // Keep it simple for std::allocator.
298 template<typename _Res, typename _Tp>
299 static _Ptr<_Result<_Res>>
300 _S_allocate_result(const std::allocator<_Tp>& __a)
302 return _Ptr<_Result<_Res>>(new _Result<_Res>);
305 // Base class for various types of shared state created by an
306 // asynchronous provider (such as a std::promise) and shared with one
307 // or more associated futures.
310 typedef _Ptr<_Result_base> _Ptr_type;
312 enum _Status : unsigned {
318 __atomic_futex_unsigned<> _M_status;
319 atomic_flag _M_retrieved = ATOMIC_FLAG_INIT;
323 _State_baseV2() noexcept : _M_result(), _M_status(_Status::__not_ready)
325 _State_baseV2(const _State_baseV2&) = delete;
326 _State_baseV2& operator=(const _State_baseV2&) = delete;
327 virtual ~_State_baseV2() = default;
332 // Run any deferred function or join any asynchronous thread:
334 // Acquire MO makes sure this synchronizes with the thread that made
336 _M_status._M_load_when_equal(_Status::__ready, memory_order_acquire);
340 template<typename _Rep, typename _Period>
342 wait_for(const chrono::duration<_Rep, _Period>& __rel)
344 // First, check if the future has been made ready. Use acquire MO
345 // to synchronize with the thread that made it ready.
346 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
347 return future_status::ready;
349 if (_M_is_deferred_future())
350 return future_status::deferred;
352 // Don't wait unless the relative time is greater than zero.
353 if (__rel > __rel.zero()
354 && _M_status._M_load_when_equal_for(_Status::__ready,
355 memory_order_acquire,
358 // _GLIBCXX_RESOLVE_LIB_DEFECTS
359 // 2100. timed waiting functions must also join
360 // This call is a no-op by default except on an async future,
361 // in which case the async thread is joined. It's also not a
362 // no-op for a deferred future, but such a future will never
363 // reach this point because it returns future_status::deferred
364 // instead of waiting for the future to become ready (see
365 // above). Async futures synchronize in this call, so we need
366 // no further synchronization here.
369 return future_status::ready;
371 return future_status::timeout;
374 template<typename _Clock, typename _Duration>
376 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
378#if __cplusplus > 201703L
379 static_assert(chrono::is_clock_v<_Clock>);
381 // First, check if the future has been made ready. Use acquire MO
382 // to synchronize with the thread that made it ready.
383 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
384 return future_status::ready;
386 if (_M_is_deferred_future())
387 return future_status::deferred;
389 if (_M_status._M_load_when_equal_until(_Status::__ready,
390 memory_order_acquire,
393 // _GLIBCXX_RESOLVE_LIB_DEFECTS
394 // 2100. timed waiting functions must also join
395 // See wait_for(...) above.
398 return future_status::ready;
400 return future_status::timeout;
403 // Provide a result to the shared state and make it ready.
404 // Calls at most once: _M_result = __res();
406 _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
408 bool __did_set = false;
409 // all calls to this function are serialized,
410 // side-effects of invoking __res only happen once
411 call_once(_M_once, &_State_baseV2::_M_do_set, this,
412 std::__addressof(__res), std::__addressof(__did_set));
414 // Use release MO to synchronize with observers of the ready state.
415 _M_status._M_store_notify_all(_Status::__ready,
416 memory_order_release);
417 else if (!__ignore_failure)
418 __throw_future_error(int(future_errc::promise_already_satisfied));
421 // Provide a result to the shared state but delay making it ready
422 // until the calling thread exits.
423 // Calls at most once: _M_result = __res();
425 _M_set_delayed_result(function<_Ptr_type()> __res,
426 weak_ptr<_State_baseV2> __self)
428 bool __did_set = false;
429 unique_ptr<_Make_ready> __mr{new _Make_ready};
430 // all calls to this function are serialized,
431 // side-effects of invoking __res only happen once
432 call_once(_M_once, &_State_baseV2::_M_do_set, this,
433 std::__addressof(__res), std::__addressof(__did_set));
435 __throw_future_error(int(future_errc::promise_already_satisfied));
436 __mr->_M_shared_state = std::move(__self);
441 // Abandon this shared state.
443 _M_break_promise(_Ptr_type __res)
445 if (static_cast<bool>(__res))
448 make_exception_ptr(future_error(future_errc::broken_promise));
449 // This function is only called when the last asynchronous result
450 // provider is abandoning this shared state, so noone can be
451 // trying to make the shared state ready at the same time, and
452 // we can access _M_result directly instead of through call_once.
453 _M_result.swap(__res);
454 // Use release MO to synchronize with observers of the ready state.
455 _M_status._M_store_notify_all(_Status::__ready,
456 memory_order_release);
460 // Called when this object is first passed to a future.
462 _M_set_retrieved_flag()
464 if (_M_retrieved.test_and_set())
465 __throw_future_error(int(future_errc::future_already_retrieved));
468 template<typename _Res, typename _Arg>
472 template<typename _Res, typename _Arg>
473 struct _Setter<_Res, _Arg&>
475 // check this is only used by promise<R>::set_value(const R&)
476 // or promise<R&>::set_value(R&)
477 static_assert(is_same<_Res, _Arg&>::value // promise<R&>
478 || is_same<const _Res, _Arg>::value, // promise<R>
479 "Invalid specialisation");
481 // Used by std::promise to copy construct the result.
482 typename promise<_Res>::_Ptr_type operator()() const
484 _M_promise->_M_storage->_M_set(*_M_arg);
485 return std::move(_M_promise->_M_storage);
487 promise<_Res>* _M_promise;
492 template<typename _Res>
493 struct _Setter<_Res, _Res&&>
495 // Used by std::promise to move construct the result.
496 typename promise<_Res>::_Ptr_type operator()() const
498 _M_promise->_M_storage->_M_set(std::move(*_M_arg));
499 return std::move(_M_promise->_M_storage);
501 promise<_Res>* _M_promise;
506 template<typename _Res>
507 struct _Setter<_Res, void>
509 static_assert(is_void<_Res>::value, "Only used for promise<void>");
511 typename promise<_Res>::_Ptr_type operator()() const
512 { return std::move(_M_promise->_M_storage); }
514 promise<_Res>* _M_promise;
517 struct __exception_ptr_tag { };
520 template<typename _Res>
521 struct _Setter<_Res, __exception_ptr_tag>
523 // Used by std::promise to store an exception as the result.
524 typename promise<_Res>::_Ptr_type operator()() const
526 _M_promise->_M_storage->_M_error = *_M_ex;
527 return std::move(_M_promise->_M_storage);
530 promise<_Res>* _M_promise;
531 exception_ptr* _M_ex;
534 template<typename _Res, typename _Arg>
535 __attribute__((__always_inline__))
536 static _Setter<_Res, _Arg&&>
537 __setter(promise<_Res>* __prom, _Arg&& __arg) noexcept
539 return _Setter<_Res, _Arg&&>{ __prom, std::__addressof(__arg) };
542 template<typename _Res>
543 __attribute__((__always_inline__))
544 static _Setter<_Res, __exception_ptr_tag>
545 __setter(exception_ptr& __ex, promise<_Res>* __prom) noexcept
547 return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex };
550 template<typename _Res>
551 __attribute__((__always_inline__))
552 static _Setter<_Res, void>
553 __setter(promise<_Res>* __prom) noexcept
555 return _Setter<_Res, void>{ __prom };
558 template<typename _Tp>
560 _S_check(const shared_ptr<_Tp>& __p)
562 if (!static_cast<bool>(__p))
563 __throw_future_error((int)future_errc::no_state);
567 // The function invoked with std::call_once(_M_once, ...).
569 _M_do_set(function<_Ptr_type()>* __f, bool* __did_set)
571 _Ptr_type __res = (*__f)();
572 // Notify the caller that we did try to set; if we do not throw an
573 // exception, the caller will be aware that it did set (e.g., see
576 _M_result.swap(__res); // nothrow
579 // Wait for completion of async function.
580 virtual void _M_complete_async() { }
582 // Return true if state corresponds to a deferred function.
583 virtual bool _M_is_deferred_future() const { return false; }
585 struct _Make_ready final : __at_thread_exit_elt
587 weak_ptr<_State_baseV2> _M_shared_state;
588 static void _S_run(void*);
593#ifdef _GLIBCXX_ASYNC_ABI_COMPAT
595 class _Async_state_common;
597 using _State_base = _State_baseV2;
598 class _Async_state_commonV2;
601 template<typename _BoundFn,
602 typename _Res = decltype(std::declval<_BoundFn&>()())>
603 class _Deferred_state;
605 template<typename _BoundFn,
606 typename _Res = decltype(std::declval<_BoundFn&>()())>
607 class _Async_state_impl;
609 template<typename _Signature>
610 class _Task_state_base;
612 template<typename _Fn, typename _Alloc, typename _Signature>
615 template<typename _Res_ptr, typename _Fn,
616 typename _Res = typename _Res_ptr::element_type::result_type>
619 template<typename _Res_ptr, typename _BoundFn>
620 static _Task_setter<_Res_ptr, _BoundFn>
621 _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call)
623 return { std::__addressof(__ptr), std::__addressof(__call) };
627 /// Partial specialization for reference types.
628 template<typename _Res>
629 struct __future_base::_Result<_Res&> : __future_base::_Result_base
631 typedef _Res& result_type;
633 _Result() noexcept : _M_value_ptr() { }
636 _M_set(_Res& __res) noexcept
637 { _M_value_ptr = std::addressof(__res); }
639 _Res& _M_get() noexcept { return *_M_value_ptr; }
644 void _M_destroy() { delete this; }
647 /// Explicit specialization for void.
649 struct __future_base::_Result<void> : __future_base::_Result_base
651 typedef void result_type;
654 void _M_destroy() { delete this; }
657#ifndef _GLIBCXX_ASYNC_ABI_COMPAT
659 // Allow _Setter objects to be stored locally in std::function
660 template<typename _Res, typename _Arg>
661 struct __is_location_invariant
662 <__future_base::_State_base::_Setter<_Res, _Arg>>
665 // Allow _Task_setter objects to be stored locally in std::function
666 template<typename _Res_ptr, typename _Fn, typename _Res>
667 struct __is_location_invariant
668 <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>>
671 /// Common implementation for future and shared_future.
672 template<typename _Res>
673 class __basic_future : public __future_base
676 typedef shared_ptr<_State_base> __state_type;
677 typedef __future_base::_Result<_Res>& __result_type;
680 __state_type _M_state;
684 __basic_future(const __basic_future&) = delete;
685 __basic_future& operator=(const __basic_future&) = delete;
688 valid() const noexcept { return static_cast<bool>(_M_state); }
693 _State_base::_S_check(_M_state);
697 template<typename _Rep, typename _Period>
699 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
701 _State_base::_S_check(_M_state);
702 return _M_state->wait_for(__rel);
705 template<typename _Clock, typename _Duration>
707 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
709 _State_base::_S_check(_M_state);
710 return _M_state->wait_until(__abs);
714 /// Wait for the state to be ready and rethrow any stored exception
716 _M_get_result() const
718 _State_base::_S_check(_M_state);
719 _Result_base& __res = _M_state->wait();
720 if (!(__res._M_error == nullptr))
721 rethrow_exception(__res._M_error);
722 return static_cast<__result_type>(__res);
725 void _M_swap(__basic_future& __that) noexcept
727 _M_state.swap(__that._M_state);
730 // Construction of a future by promise::get_future()
732 __basic_future(const __state_type& __state) : _M_state(__state)
734 _State_base::_S_check(_M_state);
735 _M_state->_M_set_retrieved_flag();
738 // Copy construction from a shared_future
740 __basic_future(const shared_future<_Res>&) noexcept;
742 // Move construction from a shared_future
744 __basic_future(shared_future<_Res>&&) noexcept;
746 // Move construction from a future
748 __basic_future(future<_Res>&&) noexcept;
750 constexpr __basic_future() noexcept : _M_state() { }
754 explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { }
755 ~_Reset() { _M_fut._M_state.reset(); }
756 __basic_future& _M_fut;
761 /// Primary template for future.
762 template<typename _Res>
763 class future : public __basic_future<_Res>
765 // _GLIBCXX_RESOLVE_LIB_DEFECTS
766 // 3458. Is shared_future intended to work with arrays or function types?
767 static_assert(!is_array<_Res>{}, "result type must not be an array");
768 static_assert(!is_function<_Res>{}, "result type must not be a function");
769 static_assert(is_destructible<_Res>{},
770 "result type must be destructible");
772 friend class promise<_Res>;
773 template<typename> friend class packaged_task;
774 template<typename _Fn, typename... _Args>
775 friend future<__async_result_of<_Fn, _Args...>>
776 async(launch, _Fn&&, _Args&&...);
778 typedef __basic_future<_Res> _Base_type;
779 typedef typename _Base_type::__state_type __state_type;
782 future(const __state_type& __state) : _Base_type(__state) { }
785 constexpr future() noexcept : _Base_type() { }
788 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
791 future(const future&) = delete;
792 future& operator=(const future&) = delete;
794 future& operator=(future&& __fut) noexcept
796 future(std::move(__fut))._M_swap(*this);
800 /// Retrieving the value
804 typename _Base_type::_Reset __reset(*this);
805 return std::move(this->_M_get_result()._M_value());
808 shared_future<_Res> share() noexcept;
811 /// Partial specialization for future<R&>
812 template<typename _Res>
813 class future<_Res&> : public __basic_future<_Res&>
815 friend class promise<_Res&>;
816 template<typename> friend class packaged_task;
817 template<typename _Fn, typename... _Args>
818 friend future<__async_result_of<_Fn, _Args...>>
819 async(launch, _Fn&&, _Args&&...);
821 typedef __basic_future<_Res&> _Base_type;
822 typedef typename _Base_type::__state_type __state_type;
825 future(const __state_type& __state) : _Base_type(__state) { }
828 constexpr future() noexcept : _Base_type() { }
831 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
834 future(const future&) = delete;
835 future& operator=(const future&) = delete;
837 future& operator=(future&& __fut) noexcept
839 future(std::move(__fut))._M_swap(*this);
843 /// Retrieving the value
847 typename _Base_type::_Reset __reset(*this);
848 return this->_M_get_result()._M_get();
851 shared_future<_Res&> share() noexcept;
854 /// Explicit specialization for future<void>
856 class future<void> : public __basic_future<void>
858 friend class promise<void>;
859 template<typename> friend class packaged_task;
860 template<typename _Fn, typename... _Args>
861 friend future<__async_result_of<_Fn, _Args...>>
862 async(launch, _Fn&&, _Args&&...);
864 typedef __basic_future<void> _Base_type;
865 typedef typename _Base_type::__state_type __state_type;
868 future(const __state_type& __state) : _Base_type(__state) { }
871 constexpr future() noexcept : _Base_type() { }
874 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
877 future(const future&) = delete;
878 future& operator=(const future&) = delete;
880 future& operator=(future&& __fut) noexcept
882 future(std::move(__fut))._M_swap(*this);
886 /// Retrieving the value
890 typename _Base_type::_Reset __reset(*this);
891 this->_M_get_result();
894 shared_future<void> share() noexcept;
898 /// Primary template for shared_future.
899 template<typename _Res>
900 class shared_future : public __basic_future<_Res>
902 // _GLIBCXX_RESOLVE_LIB_DEFECTS
903 // 3458. Is shared_future intended to work with arrays or function types?
904 static_assert(!is_array<_Res>{}, "result type must not be an array");
905 static_assert(!is_function<_Res>{}, "result type must not be a function");
906 static_assert(is_destructible<_Res>{},
907 "result type must be destructible");
909 typedef __basic_future<_Res> _Base_type;
912 constexpr shared_future() noexcept : _Base_type() { }
915 shared_future(const shared_future& __sf) noexcept : _Base_type(__sf) { }
917 /// Construct from a future rvalue
918 shared_future(future<_Res>&& __uf) noexcept
919 : _Base_type(std::move(__uf))
922 /// Construct from a shared_future rvalue
923 shared_future(shared_future&& __sf) noexcept
924 : _Base_type(std::move(__sf))
927 shared_future& operator=(const shared_future& __sf) noexcept
929 shared_future(__sf)._M_swap(*this);
933 shared_future& operator=(shared_future&& __sf) noexcept
935 shared_future(std::move(__sf))._M_swap(*this);
939 /// Retrieving the value
941 get() const { return this->_M_get_result()._M_value(); }
944 /// Partial specialization for shared_future<R&>
945 template<typename _Res>
946 class shared_future<_Res&> : public __basic_future<_Res&>
948 typedef __basic_future<_Res&> _Base_type;
951 constexpr shared_future() noexcept : _Base_type() { }
954 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
956 /// Construct from a future rvalue
957 shared_future(future<_Res&>&& __uf) noexcept
958 : _Base_type(std::move(__uf))
961 /// Construct from a shared_future rvalue
962 shared_future(shared_future&& __sf) noexcept
963 : _Base_type(std::move(__sf))
966 shared_future& operator=(const shared_future& __sf)
968 shared_future(__sf)._M_swap(*this);
972 shared_future& operator=(shared_future&& __sf) noexcept
974 shared_future(std::move(__sf))._M_swap(*this);
978 /// Retrieving the value
980 get() const { return this->_M_get_result()._M_get(); }
983 /// Explicit specialization for shared_future<void>
985 class shared_future<void> : public __basic_future<void>
987 typedef __basic_future<void> _Base_type;
990 constexpr shared_future() noexcept : _Base_type() { }
993 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
995 /// Construct from a future rvalue
996 shared_future(future<void>&& __uf) noexcept
997 : _Base_type(std::move(__uf))
1000 /// Construct from a shared_future rvalue
1001 shared_future(shared_future&& __sf) noexcept
1002 : _Base_type(std::move(__sf))
1005 shared_future& operator=(const shared_future& __sf)
1007 shared_future(__sf)._M_swap(*this);
1011 shared_future& operator=(shared_future&& __sf) noexcept
1013 shared_future(std::move(__sf))._M_swap(*this);
1017 // Retrieving the value
1019 get() const { this->_M_get_result(); }
1022 // Now we can define the protected __basic_future constructors.
1023 template<typename _Res>
1024 inline __basic_future<_Res>::
1025 __basic_future(const shared_future<_Res>& __sf) noexcept
1026 : _M_state(__sf._M_state)
1029 template<typename _Res>
1030 inline __basic_future<_Res>::
1031 __basic_future(shared_future<_Res>&& __sf) noexcept
1032 : _M_state(std::move(__sf._M_state))
1035 template<typename _Res>
1036 inline __basic_future<_Res>::
1037 __basic_future(future<_Res>&& __uf) noexcept
1038 : _M_state(std::move(__uf._M_state))
1041 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1042 // 2556. Wide contract for future::share()
1043 template<typename _Res>
1044 inline shared_future<_Res>
1045 future<_Res>::share() noexcept
1046 { return shared_future<_Res>(std::move(*this)); }
1048 template<typename _Res>
1049 inline shared_future<_Res&>
1050 future<_Res&>::share() noexcept
1051 { return shared_future<_Res&>(std::move(*this)); }
1053 inline shared_future<void>
1054 future<void>::share() noexcept
1055 { return shared_future<void>(std::move(*this)); }
1057 /// Primary template for promise
1058 template<typename _Res>
1061 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1062 // 3466: Specify the requirements for promise/future/[...] consistently
1063 static_assert(!is_array<_Res>{}, "result type must not be an array");
1064 static_assert(!is_function<_Res>{}, "result type must not be a function");
1065 static_assert(is_destructible<_Res>{},
1066 "result type must be destructible");
1068 typedef __future_base::_State_base _State;
1069 typedef __future_base::_Result<_Res> _Res_type;
1070 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1071 template<typename, typename> friend struct _State::_Setter;
1074 shared_ptr<_State> _M_future;
1075 _Ptr_type _M_storage;
1079 : _M_future(std::make_shared<_State>()),
1080 _M_storage(new _Res_type())
1083 promise(promise&& __rhs) noexcept
1084 : _M_future(std::move(__rhs._M_future)),
1085 _M_storage(std::move(__rhs._M_storage))
1088 template<typename _Allocator>
1089 promise(allocator_arg_t, const _Allocator& __a)
1090 : _M_future(std::allocate_shared<_State>(__a)),
1091 _M_storage(__future_base::_S_allocate_result<_Res>(__a))
1094 template<typename _Allocator>
1095 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1096 : _M_future(std::move(__rhs._M_future)),
1097 _M_storage(std::move(__rhs._M_storage))
1100 promise(const promise&) = delete;
1104 if (static_cast<bool>(_M_future) && !_M_future.unique())
1105 _M_future->_M_break_promise(std::move(_M_storage));
1110 operator=(promise&& __rhs) noexcept
1112 promise(std::move(__rhs)).swap(*this);
1116 promise& operator=(const promise&) = delete;
1119 swap(promise& __rhs) noexcept
1121 _M_future.swap(__rhs._M_future);
1122 _M_storage.swap(__rhs._M_storage);
1125 // Retrieving the result
1128 { return future<_Res>(_M_future); }
1130 // Setting the result
1132 set_value(const _Res& __r)
1133 { _M_state()._M_set_result(_State::__setter(this, __r)); }
1136 set_value(_Res&& __r)
1137 { _M_state()._M_set_result(_State::__setter(this, std::move(__r))); }
1140 set_exception(exception_ptr __p)
1141 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1144 set_value_at_thread_exit(const _Res& __r)
1146 _M_state()._M_set_delayed_result(_State::__setter(this, __r),
1151 set_value_at_thread_exit(_Res&& __r)
1153 _M_state()._M_set_delayed_result(
1154 _State::__setter(this, std::move(__r)), _M_future);
1158 set_exception_at_thread_exit(exception_ptr __p)
1160 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1168 __future_base::_State_base::_S_check(_M_future);
1173 template<typename _Res>
1175 swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
1178 template<typename _Res, typename _Alloc>
1179 struct uses_allocator<promise<_Res>, _Alloc>
1180 : public true_type { };
1183 /// Partial specialization for promise<R&>
1184 template<typename _Res>
1185 class promise<_Res&>
1187 typedef __future_base::_State_base _State;
1188 typedef __future_base::_Result<_Res&> _Res_type;
1189 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1190 template<typename, typename> friend struct _State::_Setter;
1193 shared_ptr<_State> _M_future;
1194 _Ptr_type _M_storage;
1198 : _M_future(std::make_shared<_State>()),
1199 _M_storage(new _Res_type())
1202 promise(promise&& __rhs) noexcept
1203 : _M_future(std::move(__rhs._M_future)),
1204 _M_storage(std::move(__rhs._M_storage))
1207 template<typename _Allocator>
1208 promise(allocator_arg_t, const _Allocator& __a)
1209 : _M_future(std::allocate_shared<_State>(__a)),
1210 _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
1213 template<typename _Allocator>
1214 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1215 : _M_future(std::move(__rhs._M_future)),
1216 _M_storage(std::move(__rhs._M_storage))
1219 promise(const promise&) = delete;
1223 if (static_cast<bool>(_M_future) && !_M_future.unique())
1224 _M_future->_M_break_promise(std::move(_M_storage));
1229 operator=(promise&& __rhs) noexcept
1231 promise(std::move(__rhs)).swap(*this);
1235 promise& operator=(const promise&) = delete;
1238 swap(promise& __rhs) noexcept
1240 _M_future.swap(__rhs._M_future);
1241 _M_storage.swap(__rhs._M_storage);
1244 // Retrieving the result
1247 { return future<_Res&>(_M_future); }
1249 // Setting the result
1251 set_value(_Res& __r)
1252 { _M_state()._M_set_result(_State::__setter(this, __r)); }
1255 set_exception(exception_ptr __p)
1256 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1259 set_value_at_thread_exit(_Res& __r)
1261 _M_state()._M_set_delayed_result(_State::__setter(this, __r),
1266 set_exception_at_thread_exit(exception_ptr __p)
1268 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1276 __future_base::_State_base::_S_check(_M_future);
1281 /// Explicit specialization for promise<void>
1285 typedef __future_base::_State_base _State;
1286 typedef __future_base::_Result<void> _Res_type;
1287 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1288 template<typename, typename> friend struct _State::_Setter;
1291 shared_ptr<_State> _M_future;
1292 _Ptr_type _M_storage;
1296 : _M_future(std::make_shared<_State>()),
1297 _M_storage(new _Res_type())
1300 promise(promise&& __rhs) noexcept
1301 : _M_future(std::move(__rhs._M_future)),
1302 _M_storage(std::move(__rhs._M_storage))
1305 template<typename _Allocator>
1306 promise(allocator_arg_t, const _Allocator& __a)
1307 : _M_future(std::allocate_shared<_State>(__a)),
1308 _M_storage(__future_base::_S_allocate_result<void>(__a))
1311 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1312 // 2095. missing constructors needed for uses-allocator construction
1313 template<typename _Allocator>
1314 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1315 : _M_future(std::move(__rhs._M_future)),
1316 _M_storage(std::move(__rhs._M_storage))
1319 promise(const promise&) = delete;
1323 if (static_cast<bool>(_M_future) && !_M_future.unique())
1324 _M_future->_M_break_promise(std::move(_M_storage));
1329 operator=(promise&& __rhs) noexcept
1331 promise(std::move(__rhs)).swap(*this);
1335 promise& operator=(const promise&) = delete;
1338 swap(promise& __rhs) noexcept
1340 _M_future.swap(__rhs._M_future);
1341 _M_storage.swap(__rhs._M_storage);
1344 // Retrieving the result
1347 { return future<void>(_M_future); }
1349 // Setting the result
1352 { _M_state()._M_set_result(_State::__setter(this)); }
1355 set_exception(exception_ptr __p)
1356 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1359 set_value_at_thread_exit()
1360 { _M_state()._M_set_delayed_result(_State::__setter(this), _M_future); }
1363 set_exception_at_thread_exit(exception_ptr __p)
1365 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1373 __future_base::_State_base::_S_check(_M_future);
1378 template<typename _Ptr_type, typename _Fn, typename _Res>
1379 struct __future_base::_Task_setter
1381 // Invoke the function and provide the result to the caller.
1382 _Ptr_type operator()() const
1386 (*_M_result)->_M_set((*_M_fn)());
1388 __catch(const __cxxabiv1::__forced_unwind&)
1390 __throw_exception_again; // will cause broken_promise
1394 (*_M_result)->_M_error = current_exception();
1396 return std::move(*_M_result);
1398 _Ptr_type* _M_result;
1402 template<typename _Ptr_type, typename _Fn>
1403 struct __future_base::_Task_setter<_Ptr_type, _Fn, void>
1405 _Ptr_type operator()() const
1411 __catch(const __cxxabiv1::__forced_unwind&)
1413 __throw_exception_again; // will cause broken_promise
1417 (*_M_result)->_M_error = current_exception();
1419 return std::move(*_M_result);
1421 _Ptr_type* _M_result;
1425 // Holds storage for a packaged_task's result.
1426 template<typename _Res, typename... _Args>
1427 struct __future_base::_Task_state_base<_Res(_Args...)>
1428 : __future_base::_State_base
1430 typedef _Res _Res_type;
1432 template<typename _Alloc>
1433 _Task_state_base(const _Alloc& __a)
1434 : _M_result(_S_allocate_result<_Res>(__a))
1437 // Invoke the stored task and make the state ready.
1439 _M_run(_Args&&... __args) = 0;
1441 // Invoke the stored task and make the state ready at thread exit.
1443 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0;
1445 virtual shared_ptr<_Task_state_base>
1448 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1449 _Ptr_type _M_result;
1452 // Holds a packaged_task's stored task.
1453 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1454 struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final
1455 : __future_base::_Task_state_base<_Res(_Args...)>
1457 template<typename _Fn2>
1458 _Task_state(_Fn2&& __fn, const _Alloc& __a)
1459 : _Task_state_base<_Res(_Args...)>(__a),
1460 _M_impl(std::forward<_Fn2>(__fn), __a)
1465 _M_run(_Args&&... __args)
1467 auto __boundfn = [&] () -> _Res {
1468 return std::__invoke_r<_Res>(_M_impl._M_fn,
1469 std::forward<_Args>(__args)...);
1471 this->_M_set_result(_S_task_setter(this->_M_result, __boundfn));
1475 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self)
1477 auto __boundfn = [&] () -> _Res {
1478 return std::__invoke_r<_Res>(_M_impl._M_fn,
1479 std::forward<_Args>(__args)...);
1481 this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn),
1485 virtual shared_ptr<_Task_state_base<_Res(_Args...)>>
1488 struct _Impl : _Alloc
1490 template<typename _Fn2>
1491 _Impl(_Fn2&& __fn, const _Alloc& __a)
1492 : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { }
1497 template<typename _Signature, typename _Fn,
1498 typename _Alloc = std::allocator<int>>
1499 static shared_ptr<__future_base::_Task_state_base<_Signature>>
1500 __create_task_state(_Fn&& __fn, const _Alloc& __a = _Alloc())
1502 typedef typename decay<_Fn>::type _Fn2;
1503 typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State;
1504 return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a);
1507 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1508 shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>>
1509 __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset()
1511 return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn),
1512 static_cast<_Alloc&>(_M_impl));
1516 template<typename _Res, typename... _ArgTypes>
1517 class packaged_task<_Res(_ArgTypes...)>
1519 typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type;
1520 shared_ptr<_State_type> _M_state;
1522 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1523 // 3039. Unnecessary decay in thread and packaged_task
1524 template<typename _Fn, typename _Fn2 = __remove_cvref_t<_Fn>>
1526 = typename enable_if<!is_same<packaged_task, _Fn2>::value>::type;
1529 // Construction and destruction
1530 packaged_task() noexcept { }
1532 template<typename _Fn, typename = __not_same<_Fn>>
1534 packaged_task(_Fn&& __fn)
1536 __create_task_state<_Res(_ArgTypes...)>(std::forward<_Fn>(__fn)))
1539#if __cplusplus < 201703L
1540 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1541 // 2097. packaged_task constructors should be constrained
1542 // 2407. [this constructor should not be] explicit
1543 // 2921. packaged_task and type-erased allocators
1544 template<typename _Fn, typename _Alloc, typename = __not_same<_Fn>>
1545 packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn)
1546 : _M_state(__create_task_state<_Res(_ArgTypes...)>(
1547 std::forward<_Fn>(__fn), __a))
1550 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1551 // 2095. missing constructors needed for uses-allocator construction
1552 template<typename _Allocator>
1553 packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
1556 template<typename _Allocator>
1557 packaged_task(allocator_arg_t, const _Allocator&,
1558 const packaged_task&) = delete;
1560 template<typename _Allocator>
1561 packaged_task(allocator_arg_t, const _Allocator&,
1562 packaged_task&& __other) noexcept
1563 { this->swap(__other); }
1568 if (static_cast<bool>(_M_state) && !_M_state.unique())
1569 _M_state->_M_break_promise(std::move(_M_state->_M_result));
1573 packaged_task(const packaged_task&) = delete;
1574 packaged_task& operator=(const packaged_task&) = delete;
1577 packaged_task(packaged_task&& __other) noexcept
1578 { this->swap(__other); }
1580 packaged_task& operator=(packaged_task&& __other) noexcept
1582 packaged_task(std::move(__other)).swap(*this);
1587 swap(packaged_task& __other) noexcept
1588 { _M_state.swap(__other._M_state); }
1591 valid() const noexcept
1592 { return static_cast<bool>(_M_state); }
1597 { return future<_Res>(_M_state); }
1601 operator()(_ArgTypes... __args)
1603 __future_base::_State_base::_S_check(_M_state);
1604 _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
1608 make_ready_at_thread_exit(_ArgTypes... __args)
1610 __future_base::_State_base::_S_check(_M_state);
1611 _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state);
1617 __future_base::_State_base::_S_check(_M_state);
1618 packaged_task __tmp;
1619 __tmp._M_state = _M_state;
1620 _M_state = _M_state->_M_reset();
1624 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1625 // 3117. Missing packaged_task deduction guides
1626#if __cpp_deduction_guides >= 201606
1627 template<typename _Res, typename... _ArgTypes>
1628 packaged_task(_Res(*)(_ArgTypes...)) -> packaged_task<_Res(_ArgTypes...)>;
1630 template<typename _Fun, typename _Signature = typename
1631 __function_guide_helper<decltype(&_Fun::operator())>::type>
1632 packaged_task(_Fun) -> packaged_task<_Signature>;
1636 template<typename _Res, typename... _ArgTypes>
1638 swap(packaged_task<_Res(_ArgTypes...)>& __x,
1639 packaged_task<_Res(_ArgTypes...)>& __y) noexcept
1642#if __cplusplus < 201703L
1643 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1644 // 2976. Dangling uses_allocator specialization for packaged_task
1645 template<typename _Res, typename _Alloc>
1646 struct uses_allocator<packaged_task<_Res>, _Alloc>
1647 : public true_type { };
1650 // Shared state created by std::async().
1651 // Holds a deferred function and storage for its result.
1652 template<typename _BoundFn, typename _Res>
1653 class __future_base::_Deferred_state final
1654 : public __future_base::_State_base
1657 template<typename... _Args>
1659 _Deferred_state(_Args&&... __args)
1660 : _M_result(new _Result<_Res>()),
1661 _M_fn(std::forward<_Args>(__args)...)
1665 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1666 _Ptr_type _M_result;
1669 // Run the deferred function.
1673 // Multiple threads can call a waiting function on the future and
1674 // reach this point at the same time. The call_once in _M_set_result
1675 // ensures only the first one run the deferred function, stores the
1676 // result in _M_result, swaps that with the base _M_result and makes
1677 // the state ready. Tell _M_set_result to ignore failure so all later
1678 // calls do nothing.
1679 _M_set_result(_S_task_setter(_M_result, _M_fn), true);
1682 // Caller should check whether the state is ready first, because this
1683 // function will return true even after the deferred function has run.
1684 virtual bool _M_is_deferred_future() const { return true; }
1687 // Common functionality hoisted out of the _Async_state_impl template.
1688 class __future_base::_Async_state_commonV2
1689 : public __future_base::_State_base
1692 ~_Async_state_commonV2() = default;
1694 // Make waiting functions block until the thread completes, as if joined.
1696 // This function is used by wait() to satisfy the first requirement below
1697 // and by wait_for() / wait_until() to satisfy the second.
1701 // - a call to a waiting function on an asynchronous return object that
1702 // shares the shared state created by this async call shall block until
1703 // the associated thread has completed, as if joined, or else time out.
1705 // - the associated thread completion synchronizes with the return from
1706 // the first function that successfully detects the ready status of the
1707 // shared state or with the return from the last function that releases
1708 // the shared state, whichever happens first.
1709 virtual void _M_complete_async() { _M_join(); }
1711 void _M_join() { std::call_once(_M_once, &thread::join, &_M_thread); }
1717 // Shared state created by std::async().
1718 // Starts a new thread that runs a function and makes the shared state ready.
1719 template<typename _BoundFn, typename _Res>
1720 class __future_base::_Async_state_impl final
1721 : public __future_base::_Async_state_commonV2
1724 template<typename... _Args>
1726 _Async_state_impl(_Args&&... __args)
1727 : _M_result(new _Result<_Res>()),
1728 _M_fn(std::forward<_Args>(__args)...)
1730 _M_thread = std::thread{&_Async_state_impl::_M_run, this};
1733 // Must not destroy _M_result and _M_fn until the thread finishes.
1734 // Call join() directly rather than through _M_join() because no other
1735 // thread can be referring to this state if it is being destroyed.
1736 ~_Async_state_impl()
1738 if (_M_thread.joinable())
1748 _M_set_result(_S_task_setter(_M_result, _M_fn));
1750 __catch (const __cxxabiv1::__forced_unwind&)
1752 // make the shared state ready on thread cancellation
1753 if (static_cast<bool>(_M_result))
1754 this->_M_break_promise(std::move(_M_result));
1755 __throw_exception_again;
1759 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1760 _Ptr_type _M_result;
1766 template<typename _Fn, typename... _Args>
1767 _GLIBCXX_NODISCARD future<__async_result_of<_Fn, _Args...>>
1768 async(launch __policy, _Fn&& __fn, _Args&&... __args)
1770 using _Wr = std::thread::_Call_wrapper<_Fn, _Args...>;
1771 using _As = __future_base::_Async_state_impl<_Wr>;
1772 using _Ds = __future_base::_Deferred_state<_Wr>;
1774 std::shared_ptr<__future_base::_State_base> __state;
1775 if ((__policy & launch::async) == launch::async)
1779 __state = std::make_shared<_As>(std::forward<_Fn>(__fn),
1780 std::forward<_Args>(__args)...);
1783 catch(const system_error& __e)
1785 if (__e.code() != errc::resource_unavailable_try_again
1786 || (__policy & launch::deferred) != launch::deferred)
1793 __state = std::make_shared<_Ds>(std::forward<_Fn>(__fn),
1794 std::forward<_Args>(__args)...);
1796 return future<__async_result_of<_Fn, _Args...>>(std::move(__state));
1799 /// async, potential overload
1800 template<typename _Fn, typename... _Args>
1801 _GLIBCXX_NODISCARD inline future<__async_result_of<_Fn, _Args...>>
1802 async(_Fn&& __fn, _Args&&... __args)
1804 return std::async(launch::async|launch::deferred,
1805 std::forward<_Fn>(__fn),
1806 std::forward<_Args>(__args)...);
1809#endif // _GLIBCXX_ASYNC_ABI_COMPAT
1810#endif // _GLIBCXX_HAS_GTHREADS
1812 /// @} group futures
1813_GLIBCXX_END_NAMESPACE_VERSION
1818#endif // _GLIBCXX_FUTURE