3// Copyright (C) 2009-2023 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#include <bits/requires_hosted.h> // concurrency
36#if __cplusplus < 201103L
37# include <bits/c++0x_warning.h>
40#include <mutex> // call_once
41#include <condition_variable> // __at_thread_exit_elt
42#include <system_error>
43#include <bits/atomic_base.h> // atomic_flag
44#include <bits/allocated_ptr.h>
45#include <bits/atomic_futex.h>
46#include <bits/exception_defines.h>
47#include <bits/invoke.h>
48#include <bits/unique_ptr.h>
49#include <bits/shared_ptr.h>
50#include <bits/std_function.h>
51#include <bits/std_thread.h>
52#include <bits/uses_allocator.h>
53#include <ext/aligned_buffer.h>
55namespace std _GLIBCXX_VISIBILITY(default)
57_GLIBCXX_BEGIN_NAMESPACE_VERSION
60 * @defgroup futures Futures
61 * @ingroup concurrency
63 * Futures and promises provide support for retrieving the result from
64 * an asynchronous function, e.g. one that is running in another thread.
65 * A `std::future` represents an asynchronous result that will become
66 * ready at some later time. A consumer can wait on a future until the
67 * result is ready to be accessed.
73 /// Error code for futures
74 enum class future_errc
76 future_already_retrieved = 1,
77 promise_already_satisfied,
82 /// Specialization that allows `future_errc` to convert to `error_code`.
84 struct is_error_code_enum<future_errc> : public true_type { };
86 /// Points to a statically-allocated object derived from error_category.
87 [[__nodiscard__, __gnu__::__const__]]
89 future_category() noexcept;
91 /// Overload of make_error_code for `future_errc`.
94 make_error_code(future_errc __errc) noexcept
95 { return error_code(static_cast<int>(__errc), future_category()); }
97 /// Overload of make_error_condition for `future_errc`.
99 inline error_condition
100 make_error_condition(future_errc __errc) noexcept
101 { return error_condition(static_cast<int>(__errc), future_category()); }
104 * @brief Exception type thrown by futures.
105 * @ingroup exceptions
108 class future_error : public logic_error
112 future_error(future_errc __errc)
113 : future_error(std::make_error_code(__errc))
116 virtual ~future_error() noexcept;
119 what() const noexcept;
122 code() const noexcept { return _M_code; }
126 future_error(error_code __ec)
127 : logic_error("std::future_error: " + __ec.message()), _M_code(__ec)
130 friend void __throw_future_error(int);
135 // Forward declarations.
136 template<typename _Res>
139 template<typename _Res>
142 template<typename _Signature>
145 template<typename _Res>
148 /// Launch code for futures
155 constexpr launch operator&(launch __x, launch __y) noexcept
157 return static_cast<launch>(
158 static_cast<int>(__x) & static_cast<int>(__y));
161 constexpr launch operator|(launch __x, launch __y) noexcept
163 return static_cast<launch>(
164 static_cast<int>(__x) | static_cast<int>(__y));
167 constexpr launch operator^(launch __x, launch __y) noexcept
169 return static_cast<launch>(
170 static_cast<int>(__x) ^ static_cast<int>(__y));
173 constexpr launch operator~(launch __x) noexcept
174 { return static_cast<launch>(~static_cast<int>(__x)); }
176 inline launch& operator&=(launch& __x, launch __y) noexcept
177 { return __x = __x & __y; }
179 inline launch& operator|=(launch& __x, launch __y) noexcept
180 { return __x = __x | __y; }
182 inline launch& operator^=(launch& __x, launch __y) noexcept
183 { return __x = __x ^ __y; }
185 /// Status code for futures
186 enum class future_status
193 /// @cond undocumented
194 // _GLIBCXX_RESOLVE_LIB_DEFECTS
195 // 2021. Further incorrect usages of result_of
196 template<typename _Fn, typename... _Args>
197 using __async_result_of = typename __invoke_result<
198 typename decay<_Fn>::type, typename decay<_Args>::type...>::type;
201 template<typename _Fn, typename... _Args>
202 future<__async_result_of<_Fn, _Args...>>
203 async(launch __policy, _Fn&& __fn, _Args&&... __args);
205 template<typename _Fn, typename... _Args>
206 future<__async_result_of<_Fn, _Args...>>
207 async(_Fn&& __fn, _Args&&... __args);
209#if defined(_GLIBCXX_HAS_GTHREADS)
211 /// @cond undocumented
213 /// Base class and enclosing scope.
216 /// Base class for results.
219 exception_ptr _M_error;
221 _Result_base(const _Result_base&) = delete;
222 _Result_base& operator=(const _Result_base&) = delete;
224 // _M_destroy() allows derived classes to control deallocation
225 virtual void _M_destroy() = 0;
229 void operator()(_Result_base* __fr) const { __fr->_M_destroy(); }
234 virtual ~_Result_base();
237 /// A unique_ptr for result objects.
238 template<typename _Res>
239 using _Ptr = unique_ptr<_Res, _Result_base::_Deleter>;
241 /// A result object that has storage for an object of type _Res.
242 template<typename _Res>
243 struct _Result : _Result_base
246 __gnu_cxx::__aligned_buffer<_Res> _M_storage;
250 typedef _Res result_type;
252 _Result() noexcept : _M_initialized() { }
260 // Return lvalue, future will add const or rvalue-reference
262 _M_value() noexcept { return *_M_storage._M_ptr(); }
265 _M_set(const _Res& __res)
267 ::new (_M_storage._M_addr()) _Res(__res);
268 _M_initialized = true;
274 ::new (_M_storage._M_addr()) _Res(std::move(__res));
275 _M_initialized = true;
279 void _M_destroy() { delete this; }
282 /// A result object that uses an allocator.
283 template<typename _Res, typename _Alloc>
284 struct _Result_alloc final : _Result<_Res>, _Alloc
286 using __allocator_type = __alloc_rebind<_Alloc, _Result_alloc>;
289 _Result_alloc(const _Alloc& __a) : _Result<_Res>(), _Alloc(__a)
295 __allocator_type __a(*this);
296 __allocated_ptr<__allocator_type> __guard_ptr{ __a, this };
297 this->~_Result_alloc();
301 // Create a result object that uses an allocator.
302 template<typename _Res, typename _Allocator>
303 static _Ptr<_Result_alloc<_Res, _Allocator>>
304 _S_allocate_result(const _Allocator& __a)
306 using __result_type = _Result_alloc<_Res, _Allocator>;
307 typename __result_type::__allocator_type __a2(__a);
308 auto __guard = std::__allocate_guarded(__a2);
309 __result_type* __p = ::new((void*)__guard.get()) __result_type{__a};
311 return _Ptr<__result_type>(__p);
314 // Keep it simple for std::allocator.
315 template<typename _Res, typename _Tp>
316 static _Ptr<_Result<_Res>>
317 _S_allocate_result(const std::allocator<_Tp>& __a)
319 return _Ptr<_Result<_Res>>(new _Result<_Res>);
322 // Base class for various types of shared state created by an
323 // asynchronous provider (such as a std::promise) and shared with one
324 // or more associated futures.
327 typedef _Ptr<_Result_base> _Ptr_type;
329 enum _Status : unsigned {
335 __atomic_futex_unsigned<> _M_status;
336 atomic_flag _M_retrieved = ATOMIC_FLAG_INIT;
340 _State_baseV2() noexcept : _M_result(), _M_status(_Status::__not_ready)
342 _State_baseV2(const _State_baseV2&) = delete;
343 _State_baseV2& operator=(const _State_baseV2&) = delete;
344 virtual ~_State_baseV2() = default;
349 // Run any deferred function or join any asynchronous thread:
351 // Acquire MO makes sure this synchronizes with the thread that made
353 _M_status._M_load_when_equal(_Status::__ready, memory_order_acquire);
357 template<typename _Rep, typename _Period>
359 wait_for(const chrono::duration<_Rep, _Period>& __rel)
361 // First, check if the future has been made ready. Use acquire MO
362 // to synchronize with the thread that made it ready.
363 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
364 return future_status::ready;
366 if (_M_is_deferred_future())
367 return future_status::deferred;
369 // Don't wait unless the relative time is greater than zero.
370 if (__rel > __rel.zero()
371 && _M_status._M_load_when_equal_for(_Status::__ready,
372 memory_order_acquire,
375 // _GLIBCXX_RESOLVE_LIB_DEFECTS
376 // 2100. timed waiting functions must also join
377 // This call is a no-op by default except on an async future,
378 // in which case the async thread is joined. It's also not a
379 // no-op for a deferred future, but such a future will never
380 // reach this point because it returns future_status::deferred
381 // instead of waiting for the future to become ready (see
382 // above). Async futures synchronize in this call, so we need
383 // no further synchronization here.
386 return future_status::ready;
388 return future_status::timeout;
391 template<typename _Clock, typename _Duration>
393 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
395#if __cplusplus > 201703L
396 static_assert(chrono::is_clock_v<_Clock>);
398 // First, check if the future has been made ready. Use acquire MO
399 // to synchronize with the thread that made it ready.
400 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
401 return future_status::ready;
403 if (_M_is_deferred_future())
404 return future_status::deferred;
406 if (_M_status._M_load_when_equal_until(_Status::__ready,
407 memory_order_acquire,
410 // _GLIBCXX_RESOLVE_LIB_DEFECTS
411 // 2100. timed waiting functions must also join
412 // See wait_for(...) above.
415 return future_status::ready;
417 return future_status::timeout;
420 // Provide a result to the shared state and make it ready.
421 // Calls at most once: _M_result = __res();
423 _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
425 bool __did_set = false;
426 // all calls to this function are serialized,
427 // side-effects of invoking __res only happen once
428 call_once(_M_once, &_State_baseV2::_M_do_set, this,
429 std::__addressof(__res), std::__addressof(__did_set));
431 // Use release MO to synchronize with observers of the ready state.
432 _M_status._M_store_notify_all(_Status::__ready,
433 memory_order_release);
434 else if (!__ignore_failure)
435 __throw_future_error(int(future_errc::promise_already_satisfied));
438 // Provide a result to the shared state but delay making it ready
439 // until the calling thread exits.
440 // Calls at most once: _M_result = __res();
442 _M_set_delayed_result(function<_Ptr_type()> __res,
443 weak_ptr<_State_baseV2> __self)
445 bool __did_set = false;
446 unique_ptr<_Make_ready> __mr{new _Make_ready};
447 // all calls to this function are serialized,
448 // side-effects of invoking __res only happen once
449 call_once(_M_once, &_State_baseV2::_M_do_set, this,
450 std::__addressof(__res), std::__addressof(__did_set));
452 __throw_future_error(int(future_errc::promise_already_satisfied));
453 __mr->_M_shared_state = std::move(__self);
458 // Abandon this shared state.
460 _M_break_promise(_Ptr_type __res)
462 if (static_cast<bool>(__res))
465 make_exception_ptr(future_error(future_errc::broken_promise));
466 // This function is only called when the last asynchronous result
467 // provider is abandoning this shared state, so noone can be
468 // trying to make the shared state ready at the same time, and
469 // we can access _M_result directly instead of through call_once.
470 _M_result.swap(__res);
471 // Use release MO to synchronize with observers of the ready state.
472 _M_status._M_store_notify_all(_Status::__ready,
473 memory_order_release);
477 // Called when this object is first passed to a future.
479 _M_set_retrieved_flag()
481 if (_M_retrieved.test_and_set())
482 __throw_future_error(int(future_errc::future_already_retrieved));
485 template<typename _Res, typename _Arg>
489 template<typename _Res, typename _Arg>
490 struct _Setter<_Res, _Arg&>
492 // check this is only used by promise<R>::set_value(const R&)
493 // or promise<R&>::set_value(R&)
494 static_assert(is_same<_Res, _Arg&>::value // promise<R&>
495 || is_same<const _Res, _Arg>::value, // promise<R>
496 "Invalid specialisation");
498 // Used by std::promise to copy construct the result.
499 typename promise<_Res>::_Ptr_type operator()() const
501 _M_promise->_M_storage->_M_set(*_M_arg);
502 return std::move(_M_promise->_M_storage);
504 promise<_Res>* _M_promise;
509 template<typename _Res>
510 struct _Setter<_Res, _Res&&>
512 // Used by std::promise to move construct the result.
513 typename promise<_Res>::_Ptr_type operator()() const
515 _M_promise->_M_storage->_M_set(std::move(*_M_arg));
516 return std::move(_M_promise->_M_storage);
518 promise<_Res>* _M_promise;
523 template<typename _Res>
524 struct _Setter<_Res, void>
526 static_assert(is_void<_Res>::value, "Only used for promise<void>");
528 typename promise<_Res>::_Ptr_type operator()() const
529 { return std::move(_M_promise->_M_storage); }
531 promise<_Res>* _M_promise;
534 struct __exception_ptr_tag { };
537 template<typename _Res>
538 struct _Setter<_Res, __exception_ptr_tag>
540 // Used by std::promise to store an exception as the result.
541 typename promise<_Res>::_Ptr_type operator()() const
543 _M_promise->_M_storage->_M_error = *_M_ex;
544 return std::move(_M_promise->_M_storage);
547 promise<_Res>* _M_promise;
548 exception_ptr* _M_ex;
551 template<typename _Res, typename _Arg>
552 __attribute__((__always_inline__))
553 static _Setter<_Res, _Arg&&>
554 __setter(promise<_Res>* __prom, _Arg&& __arg) noexcept
556 return _Setter<_Res, _Arg&&>{ __prom, std::__addressof(__arg) };
559 template<typename _Res>
560 __attribute__((__always_inline__))
561 static _Setter<_Res, __exception_ptr_tag>
562 __setter(exception_ptr& __ex, promise<_Res>* __prom) noexcept
564 __glibcxx_assert(__ex != nullptr); // LWG 2276
565 return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex };
568 template<typename _Res>
569 __attribute__((__always_inline__))
570 static _Setter<_Res, void>
571 __setter(promise<_Res>* __prom) noexcept
573 return _Setter<_Res, void>{ __prom };
576 template<typename _Tp>
578 _S_check(const shared_ptr<_Tp>& __p)
580 if (!static_cast<bool>(__p))
581 __throw_future_error((int)future_errc::no_state);
585 // The function invoked with std::call_once(_M_once, ...).
587 _M_do_set(function<_Ptr_type()>* __f, bool* __did_set)
589 _Ptr_type __res = (*__f)();
590 // Notify the caller that we did try to set; if we do not throw an
591 // exception, the caller will be aware that it did set (e.g., see
594 _M_result.swap(__res); // nothrow
597 // Wait for completion of async function.
598 virtual void _M_complete_async() { }
600 // Return true if state corresponds to a deferred function.
601 virtual bool _M_is_deferred_future() const { return false; }
603 struct _Make_ready final : __at_thread_exit_elt
605 weak_ptr<_State_baseV2> _M_shared_state;
606 static void _S_run(void*);
611#ifdef _GLIBCXX_ASYNC_ABI_COMPAT
613 class _Async_state_common;
615 using _State_base = _State_baseV2;
616 class _Async_state_commonV2;
619 template<typename _BoundFn,
620 typename _Res = decltype(std::declval<_BoundFn&>()())>
621 class _Deferred_state;
623 template<typename _BoundFn,
624 typename _Res = decltype(std::declval<_BoundFn&>()())>
625 class _Async_state_impl;
627 template<typename _Signature>
628 class _Task_state_base;
630 template<typename _Fn, typename _Alloc, typename _Signature>
633 template<typename _Res_ptr, typename _Fn,
634 typename _Res = typename _Res_ptr::element_type::result_type>
637 template<typename _Res_ptr, typename _BoundFn>
638 static _Task_setter<_Res_ptr, _BoundFn>
639 _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call)
641 return { std::__addressof(__ptr), std::__addressof(__call) };
645 /// Partial specialization for reference types.
646 template<typename _Res>
647 struct __future_base::_Result<_Res&> : __future_base::_Result_base
649 typedef _Res& result_type;
651 _Result() noexcept : _M_value_ptr() { }
654 _M_set(_Res& __res) noexcept
655 { _M_value_ptr = std::addressof(__res); }
657 _Res& _M_get() noexcept { return *_M_value_ptr; }
662 void _M_destroy() { delete this; }
665 /// Explicit specialization for void.
667 struct __future_base::_Result<void> : __future_base::_Result_base
669 typedef void result_type;
672 void _M_destroy() { delete this; }
677#ifndef _GLIBCXX_ASYNC_ABI_COMPAT
679 /// @cond undocumented
680 // Allow _Setter objects to be stored locally in std::function
681 template<typename _Res, typename _Arg>
682 struct __is_location_invariant
683 <__future_base::_State_base::_Setter<_Res, _Arg>>
686 // Allow _Task_setter objects to be stored locally in std::function
687 template<typename _Res_ptr, typename _Fn, typename _Res>
688 struct __is_location_invariant
689 <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>>
693 /// Common implementation for future and shared_future.
694 template<typename _Res>
695 class __basic_future : public __future_base
698 typedef shared_ptr<_State_base> __state_type;
699 typedef __future_base::_Result<_Res>& __result_type;
702 __state_type _M_state;
706 __basic_future(const __basic_future&) = delete;
707 __basic_future& operator=(const __basic_future&) = delete;
710 valid() const noexcept { return static_cast<bool>(_M_state); }
715 _State_base::_S_check(_M_state);
719 template<typename _Rep, typename _Period>
721 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
723 _State_base::_S_check(_M_state);
724 return _M_state->wait_for(__rel);
727 template<typename _Clock, typename _Duration>
729 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
731 _State_base::_S_check(_M_state);
732 return _M_state->wait_until(__abs);
736 /// Wait for the state to be ready and rethrow any stored exception
738 _M_get_result() const
740 _State_base::_S_check(_M_state);
741 _Result_base& __res = _M_state->wait();
742 if (!(__res._M_error == nullptr))
743 rethrow_exception(__res._M_error);
744 return static_cast<__result_type>(__res);
747 void _M_swap(__basic_future& __that) noexcept
749 _M_state.swap(__that._M_state);
752 // Construction of a future by promise::get_future()
754 __basic_future(const __state_type& __state) : _M_state(__state)
756 _State_base::_S_check(_M_state);
757 _M_state->_M_set_retrieved_flag();
760 // Copy construction from a shared_future
762 __basic_future(const shared_future<_Res>&) noexcept;
764 // Move construction from a shared_future
766 __basic_future(shared_future<_Res>&&) noexcept;
768 // Move construction from a future
770 __basic_future(future<_Res>&&) noexcept;
772 constexpr __basic_future() noexcept : _M_state() { }
776 explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { }
777 ~_Reset() { _M_fut._M_state.reset(); }
778 __basic_future& _M_fut;
783 /// Primary template for future.
784 template<typename _Res>
785 class future : public __basic_future<_Res>
787 // _GLIBCXX_RESOLVE_LIB_DEFECTS
788 // 3458. Is shared_future intended to work with arrays or function types?
789 static_assert(!is_array<_Res>{}, "result type must not be an array");
790 static_assert(!is_function<_Res>{}, "result type must not be a function");
791 static_assert(is_destructible<_Res>{},
792 "result type must be destructible");
794 friend class promise<_Res>;
795 template<typename> friend class packaged_task;
796 template<typename _Fn, typename... _Args>
797 friend future<__async_result_of<_Fn, _Args...>>
798 async(launch, _Fn&&, _Args&&...);
800 typedef __basic_future<_Res> _Base_type;
801 typedef typename _Base_type::__state_type __state_type;
804 future(const __state_type& __state) : _Base_type(__state) { }
807 constexpr future() noexcept : _Base_type() { }
810 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
813 future(const future&) = delete;
814 future& operator=(const future&) = delete;
816 future& operator=(future&& __fut) noexcept
818 future(std::move(__fut))._M_swap(*this);
822 /// Retrieving the value
826 typename _Base_type::_Reset __reset(*this);
827 return std::move(this->_M_get_result()._M_value());
830 shared_future<_Res> share() noexcept;
833 /// Partial specialization for future<R&>
834 template<typename _Res>
835 class future<_Res&> : public __basic_future<_Res&>
837 friend class promise<_Res&>;
838 template<typename> friend class packaged_task;
839 template<typename _Fn, typename... _Args>
840 friend future<__async_result_of<_Fn, _Args...>>
841 async(launch, _Fn&&, _Args&&...);
843 typedef __basic_future<_Res&> _Base_type;
844 typedef typename _Base_type::__state_type __state_type;
847 future(const __state_type& __state) : _Base_type(__state) { }
850 constexpr future() noexcept : _Base_type() { }
853 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
856 future(const future&) = delete;
857 future& operator=(const future&) = delete;
859 future& operator=(future&& __fut) noexcept
861 future(std::move(__fut))._M_swap(*this);
865 /// Retrieving the value
869 typename _Base_type::_Reset __reset(*this);
870 return this->_M_get_result()._M_get();
873 shared_future<_Res&> share() noexcept;
876 /// Explicit specialization for future<void>
878 class future<void> : public __basic_future<void>
880 friend class promise<void>;
881 template<typename> friend class packaged_task;
882 template<typename _Fn, typename... _Args>
883 friend future<__async_result_of<_Fn, _Args...>>
884 async(launch, _Fn&&, _Args&&...);
886 typedef __basic_future<void> _Base_type;
887 typedef typename _Base_type::__state_type __state_type;
890 future(const __state_type& __state) : _Base_type(__state) { }
893 constexpr future() noexcept : _Base_type() { }
896 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
899 future(const future&) = delete;
900 future& operator=(const future&) = delete;
902 future& operator=(future&& __fut) noexcept
904 future(std::move(__fut))._M_swap(*this);
908 /// Retrieving the value
912 typename _Base_type::_Reset __reset(*this);
913 this->_M_get_result();
916 shared_future<void> share() noexcept;
920 /// Primary template for shared_future.
921 template<typename _Res>
922 class shared_future : public __basic_future<_Res>
924 // _GLIBCXX_RESOLVE_LIB_DEFECTS
925 // 3458. Is shared_future intended to work with arrays or function types?
926 static_assert(!is_array<_Res>{}, "result type must not be an array");
927 static_assert(!is_function<_Res>{}, "result type must not be a function");
928 static_assert(is_destructible<_Res>{},
929 "result type must be destructible");
931 typedef __basic_future<_Res> _Base_type;
934 constexpr shared_future() noexcept : _Base_type() { }
937 shared_future(const shared_future& __sf) noexcept : _Base_type(__sf) { }
939 /// Construct from a future rvalue
940 shared_future(future<_Res>&& __uf) noexcept
941 : _Base_type(std::move(__uf))
944 /// Construct from a shared_future rvalue
945 shared_future(shared_future&& __sf) noexcept
946 : _Base_type(std::move(__sf))
949 shared_future& operator=(const shared_future& __sf) noexcept
951 shared_future(__sf)._M_swap(*this);
955 shared_future& operator=(shared_future&& __sf) noexcept
957 shared_future(std::move(__sf))._M_swap(*this);
961 /// Retrieving the value
963 get() const { return this->_M_get_result()._M_value(); }
966 /// Partial specialization for shared_future<R&>
967 template<typename _Res>
968 class shared_future<_Res&> : public __basic_future<_Res&>
970 typedef __basic_future<_Res&> _Base_type;
973 constexpr shared_future() noexcept : _Base_type() { }
976 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
978 /// Construct from a future rvalue
979 shared_future(future<_Res&>&& __uf) noexcept
980 : _Base_type(std::move(__uf))
983 /// Construct from a shared_future rvalue
984 shared_future(shared_future&& __sf) noexcept
985 : _Base_type(std::move(__sf))
988 shared_future& operator=(const shared_future& __sf)
990 shared_future(__sf)._M_swap(*this);
994 shared_future& operator=(shared_future&& __sf) noexcept
996 shared_future(std::move(__sf))._M_swap(*this);
1000 /// Retrieving the value
1002 get() const { return this->_M_get_result()._M_get(); }
1005 /// Explicit specialization for shared_future<void>
1007 class shared_future<void> : public __basic_future<void>
1009 typedef __basic_future<void> _Base_type;
1012 constexpr shared_future() noexcept : _Base_type() { }
1014 /// Copy constructor
1015 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
1017 /// Construct from a future rvalue
1018 shared_future(future<void>&& __uf) noexcept
1019 : _Base_type(std::move(__uf))
1022 /// Construct from a shared_future rvalue
1023 shared_future(shared_future&& __sf) noexcept
1024 : _Base_type(std::move(__sf))
1027 shared_future& operator=(const shared_future& __sf)
1029 shared_future(__sf)._M_swap(*this);
1033 shared_future& operator=(shared_future&& __sf) noexcept
1035 shared_future(std::move(__sf))._M_swap(*this);
1039 // Retrieving the value
1041 get() const { this->_M_get_result(); }
1044 // Now we can define the protected __basic_future constructors.
1045 template<typename _Res>
1046 inline __basic_future<_Res>::
1047 __basic_future(const shared_future<_Res>& __sf) noexcept
1048 : _M_state(__sf._M_state)
1051 template<typename _Res>
1052 inline __basic_future<_Res>::
1053 __basic_future(shared_future<_Res>&& __sf) noexcept
1054 : _M_state(std::move(__sf._M_state))
1057 template<typename _Res>
1058 inline __basic_future<_Res>::
1059 __basic_future(future<_Res>&& __uf) noexcept
1060 : _M_state(std::move(__uf._M_state))
1063 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1064 // 2556. Wide contract for future::share()
1065 template<typename _Res>
1066 inline shared_future<_Res>
1067 future<_Res>::share() noexcept
1068 { return shared_future<_Res>(std::move(*this)); }
1070 template<typename _Res>
1071 inline shared_future<_Res&>
1072 future<_Res&>::share() noexcept
1073 { return shared_future<_Res&>(std::move(*this)); }
1075 inline shared_future<void>
1076 future<void>::share() noexcept
1077 { return shared_future<void>(std::move(*this)); }
1079 /// Primary template for promise
1080 template<typename _Res>
1083 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1084 // 3466: Specify the requirements for promise/future/[...] consistently
1085 static_assert(!is_array<_Res>{}, "result type must not be an array");
1086 static_assert(!is_function<_Res>{}, "result type must not be a function");
1087 static_assert(is_destructible<_Res>{},
1088 "result type must be destructible");
1090 typedef __future_base::_State_base _State;
1091 typedef __future_base::_Result<_Res> _Res_type;
1092 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1093 template<typename, typename> friend struct _State::_Setter;
1096 shared_ptr<_State> _M_future;
1097 _Ptr_type _M_storage;
1101 : _M_future(std::make_shared<_State>()),
1102 _M_storage(new _Res_type())
1105 promise(promise&& __rhs) noexcept
1106 : _M_future(std::move(__rhs._M_future)),
1107 _M_storage(std::move(__rhs._M_storage))
1110 template<typename _Allocator>
1111 promise(allocator_arg_t, const _Allocator& __a)
1112 : _M_future(std::allocate_shared<_State>(__a)),
1113 _M_storage(__future_base::_S_allocate_result<_Res>(__a))
1116 template<typename _Allocator>
1117 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1118 : _M_future(std::move(__rhs._M_future)),
1119 _M_storage(std::move(__rhs._M_storage))
1122 promise(const promise&) = delete;
1126 if (static_cast<bool>(_M_future) && !_M_future.unique())
1127 _M_future->_M_break_promise(std::move(_M_storage));
1132 operator=(promise&& __rhs) noexcept
1134 promise(std::move(__rhs)).swap(*this);
1138 promise& operator=(const promise&) = delete;
1141 swap(promise& __rhs) noexcept
1143 _M_future.swap(__rhs._M_future);
1144 _M_storage.swap(__rhs._M_storage);
1147 // Retrieving the result
1150 { return future<_Res>(_M_future); }
1152 // Setting the result
1154 set_value(const _Res& __r)
1155 { _M_state()._M_set_result(_State::__setter(this, __r)); }
1158 set_value(_Res&& __r)
1159 { _M_state()._M_set_result(_State::__setter(this, std::move(__r))); }
1162 set_exception(exception_ptr __p)
1163 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1166 set_value_at_thread_exit(const _Res& __r)
1168 _M_state()._M_set_delayed_result(_State::__setter(this, __r),
1173 set_value_at_thread_exit(_Res&& __r)
1175 _M_state()._M_set_delayed_result(
1176 _State::__setter(this, std::move(__r)), _M_future);
1180 set_exception_at_thread_exit(exception_ptr __p)
1182 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1190 __future_base::_State_base::_S_check(_M_future);
1195 template<typename _Res>
1197 swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
1200 template<typename _Res, typename _Alloc>
1201 struct uses_allocator<promise<_Res>, _Alloc>
1202 : public true_type { };
1205 /// Partial specialization for promise<R&>
1206 template<typename _Res>
1207 class promise<_Res&>
1209 typedef __future_base::_State_base _State;
1210 typedef __future_base::_Result<_Res&> _Res_type;
1211 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1212 template<typename, typename> friend struct _State::_Setter;
1215 shared_ptr<_State> _M_future;
1216 _Ptr_type _M_storage;
1220 : _M_future(std::make_shared<_State>()),
1221 _M_storage(new _Res_type())
1224 promise(promise&& __rhs) noexcept
1225 : _M_future(std::move(__rhs._M_future)),
1226 _M_storage(std::move(__rhs._M_storage))
1229 template<typename _Allocator>
1230 promise(allocator_arg_t, const _Allocator& __a)
1231 : _M_future(std::allocate_shared<_State>(__a)),
1232 _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
1235 template<typename _Allocator>
1236 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1237 : _M_future(std::move(__rhs._M_future)),
1238 _M_storage(std::move(__rhs._M_storage))
1241 promise(const promise&) = delete;
1245 if (static_cast<bool>(_M_future) && !_M_future.unique())
1246 _M_future->_M_break_promise(std::move(_M_storage));
1251 operator=(promise&& __rhs) noexcept
1253 promise(std::move(__rhs)).swap(*this);
1257 promise& operator=(const promise&) = delete;
1260 swap(promise& __rhs) noexcept
1262 _M_future.swap(__rhs._M_future);
1263 _M_storage.swap(__rhs._M_storage);
1266 // Retrieving the result
1269 { return future<_Res&>(_M_future); }
1271 // Setting the result
1273 set_value(_Res& __r)
1274 { _M_state()._M_set_result(_State::__setter(this, __r)); }
1277 set_exception(exception_ptr __p)
1278 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1281 set_value_at_thread_exit(_Res& __r)
1283 _M_state()._M_set_delayed_result(_State::__setter(this, __r),
1288 set_exception_at_thread_exit(exception_ptr __p)
1290 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1298 __future_base::_State_base::_S_check(_M_future);
1303 /// Explicit specialization for promise<void>
1307 typedef __future_base::_State_base _State;
1308 typedef __future_base::_Result<void> _Res_type;
1309 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1310 template<typename, typename> friend struct _State::_Setter;
1313 shared_ptr<_State> _M_future;
1314 _Ptr_type _M_storage;
1318 : _M_future(std::make_shared<_State>()),
1319 _M_storage(new _Res_type())
1322 promise(promise&& __rhs) noexcept
1323 : _M_future(std::move(__rhs._M_future)),
1324 _M_storage(std::move(__rhs._M_storage))
1327 template<typename _Allocator>
1328 promise(allocator_arg_t, const _Allocator& __a)
1329 : _M_future(std::allocate_shared<_State>(__a)),
1330 _M_storage(__future_base::_S_allocate_result<void>(__a))
1333 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1334 // 2095. missing constructors needed for uses-allocator construction
1335 template<typename _Allocator>
1336 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1337 : _M_future(std::move(__rhs._M_future)),
1338 _M_storage(std::move(__rhs._M_storage))
1341 promise(const promise&) = delete;
1345 if (static_cast<bool>(_M_future) && !_M_future.unique())
1346 _M_future->_M_break_promise(std::move(_M_storage));
1351 operator=(promise&& __rhs) noexcept
1353 promise(std::move(__rhs)).swap(*this);
1357 promise& operator=(const promise&) = delete;
1360 swap(promise& __rhs) noexcept
1362 _M_future.swap(__rhs._M_future);
1363 _M_storage.swap(__rhs._M_storage);
1366 // Retrieving the result
1369 { return future<void>(_M_future); }
1371 // Setting the result
1374 { _M_state()._M_set_result(_State::__setter(this)); }
1377 set_exception(exception_ptr __p)
1378 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1381 set_value_at_thread_exit()
1382 { _M_state()._M_set_delayed_result(_State::__setter(this), _M_future); }
1385 set_exception_at_thread_exit(exception_ptr __p)
1387 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1395 __future_base::_State_base::_S_check(_M_future);
1400 /// @cond undocumented
1401 template<typename _Ptr_type, typename _Fn, typename _Res>
1402 struct __future_base::_Task_setter
1404 // Invoke the function and provide the result to the caller.
1405 _Ptr_type operator()() const
1409 (*_M_result)->_M_set((*_M_fn)());
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 template<typename _Ptr_type, typename _Fn>
1426 struct __future_base::_Task_setter<_Ptr_type, _Fn, void>
1428 _Ptr_type operator()() const
1434 __catch(const __cxxabiv1::__forced_unwind&)
1436 __throw_exception_again; // will cause broken_promise
1440 (*_M_result)->_M_error = current_exception();
1442 return std::move(*_M_result);
1444 _Ptr_type* _M_result;
1448 // Holds storage for a packaged_task's result.
1449 template<typename _Res, typename... _Args>
1450 struct __future_base::_Task_state_base<_Res(_Args...)>
1451 : __future_base::_State_base
1453 typedef _Res _Res_type;
1455 template<typename _Alloc>
1456 _Task_state_base(const _Alloc& __a)
1457 : _M_result(_S_allocate_result<_Res>(__a))
1460 // Invoke the stored task and make the state ready.
1462 _M_run(_Args&&... __args) = 0;
1464 // Invoke the stored task and make the state ready at thread exit.
1466 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0;
1468 virtual shared_ptr<_Task_state_base>
1471 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1472 _Ptr_type _M_result;
1475 // Holds a packaged_task's stored task.
1476 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1477 struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final
1478 : __future_base::_Task_state_base<_Res(_Args...)>
1480 template<typename _Fn2>
1481 _Task_state(_Fn2&& __fn, const _Alloc& __a)
1482 : _Task_state_base<_Res(_Args...)>(__a),
1483 _M_impl(std::forward<_Fn2>(__fn), __a)
1488 _M_run(_Args&&... __args)
1490 auto __boundfn = [&] () -> _Res {
1491 return std::__invoke_r<_Res>(_M_impl._M_fn,
1492 std::forward<_Args>(__args)...);
1494 this->_M_set_result(_S_task_setter(this->_M_result, __boundfn));
1498 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self)
1500 auto __boundfn = [&] () -> _Res {
1501 return std::__invoke_r<_Res>(_M_impl._M_fn,
1502 std::forward<_Args>(__args)...);
1504 this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn),
1508 virtual shared_ptr<_Task_state_base<_Res(_Args...)>>
1511 struct _Impl : _Alloc
1513 template<typename _Fn2>
1514 _Impl(_Fn2&& __fn, const _Alloc& __a)
1515 : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { }
1520 template<typename _Signature, typename _Fn,
1521 typename _Alloc = std::allocator<int>>
1522 static shared_ptr<__future_base::_Task_state_base<_Signature>>
1523 __create_task_state(_Fn&& __fn, const _Alloc& __a = _Alloc())
1525 typedef typename decay<_Fn>::type _Fn2;
1526 typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State;
1527 return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a);
1530 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1531 shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>>
1532 __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset()
1534 return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn),
1535 static_cast<_Alloc&>(_M_impl));
1540 template<typename _Res, typename... _ArgTypes>
1541 class packaged_task<_Res(_ArgTypes...)>
1543 typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type;
1544 shared_ptr<_State_type> _M_state;
1546 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1547 // 3039. Unnecessary decay in thread and packaged_task
1548 template<typename _Fn, typename _Fn2 = __remove_cvref_t<_Fn>>
1550 = typename enable_if<!is_same<packaged_task, _Fn2>::value>::type;
1553 // Construction and destruction
1554 packaged_task() noexcept { }
1556 template<typename _Fn, typename = __not_same<_Fn>>
1558 packaged_task(_Fn&& __fn)
1560 __create_task_state<_Res(_ArgTypes...)>(std::forward<_Fn>(__fn)))
1563#if __cplusplus < 201703L
1564 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1565 // 2097. packaged_task constructors should be constrained
1566 // 2407. [this constructor should not be] explicit
1567 // 2921. packaged_task and type-erased allocators
1568 template<typename _Fn, typename _Alloc, typename = __not_same<_Fn>>
1569 packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn)
1570 : _M_state(__create_task_state<_Res(_ArgTypes...)>(
1571 std::forward<_Fn>(__fn), __a))
1574 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1575 // 2095. missing constructors needed for uses-allocator construction
1576 template<typename _Allocator>
1577 packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
1580 template<typename _Allocator>
1581 packaged_task(allocator_arg_t, const _Allocator&,
1582 const packaged_task&) = delete;
1584 template<typename _Allocator>
1585 packaged_task(allocator_arg_t, const _Allocator&,
1586 packaged_task&& __other) noexcept
1587 { this->swap(__other); }
1592 if (static_cast<bool>(_M_state) && !_M_state.unique())
1593 _M_state->_M_break_promise(std::move(_M_state->_M_result));
1597 packaged_task(const packaged_task&) = delete;
1598 packaged_task& operator=(const packaged_task&) = delete;
1601 packaged_task(packaged_task&& __other) noexcept
1602 { this->swap(__other); }
1604 packaged_task& operator=(packaged_task&& __other) noexcept
1606 packaged_task(std::move(__other)).swap(*this);
1611 swap(packaged_task& __other) noexcept
1612 { _M_state.swap(__other._M_state); }
1615 valid() const noexcept
1616 { return static_cast<bool>(_M_state); }
1621 { return future<_Res>(_M_state); }
1625 operator()(_ArgTypes... __args)
1627 __future_base::_State_base::_S_check(_M_state);
1628 _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
1632 make_ready_at_thread_exit(_ArgTypes... __args)
1634 __future_base::_State_base::_S_check(_M_state);
1635 _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state);
1641 __future_base::_State_base::_S_check(_M_state);
1642 packaged_task __tmp;
1643 __tmp._M_state = _M_state;
1644 _M_state = _M_state->_M_reset();
1648 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1649 // 3117. Missing packaged_task deduction guides
1650#if __cpp_deduction_guides >= 201606
1651 template<typename _Res, typename... _ArgTypes>
1652 packaged_task(_Res(*)(_ArgTypes...)) -> packaged_task<_Res(_ArgTypes...)>;
1654 template<typename _Fun, typename _Signature
1655 = __function_guide_t<_Fun, decltype(&_Fun::operator())>>
1656 packaged_task(_Fun) -> packaged_task<_Signature>;
1660 template<typename _Res, typename... _ArgTypes>
1662 swap(packaged_task<_Res(_ArgTypes...)>& __x,
1663 packaged_task<_Res(_ArgTypes...)>& __y) noexcept
1666#if __cplusplus < 201703L
1667 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1668 // 2976. Dangling uses_allocator specialization for packaged_task
1669 template<typename _Res, typename _Alloc>
1670 struct uses_allocator<packaged_task<_Res>, _Alloc>
1671 : public true_type { };
1674 /// @cond undocumented
1676 // Shared state created by std::async().
1677 // Holds a deferred function and storage for its result.
1678 template<typename _BoundFn, typename _Res>
1679 class __future_base::_Deferred_state final
1680 : public __future_base::_State_base
1683 template<typename... _Args>
1685 _Deferred_state(_Args&&... __args)
1686 : _M_result(new _Result<_Res>()),
1687 _M_fn(std::forward<_Args>(__args)...)
1691 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1692 _Ptr_type _M_result;
1695 // Run the deferred function.
1699 // Multiple threads can call a waiting function on the future and
1700 // reach this point at the same time. The call_once in _M_set_result
1701 // ensures only the first one run the deferred function, stores the
1702 // result in _M_result, swaps that with the base _M_result and makes
1703 // the state ready. Tell _M_set_result to ignore failure so all later
1704 // calls do nothing.
1705 _M_set_result(_S_task_setter(_M_result, _M_fn), true);
1708 // Caller should check whether the state is ready first, because this
1709 // function will return true even after the deferred function has run.
1710 virtual bool _M_is_deferred_future() const { return true; }
1713 // Common functionality hoisted out of the _Async_state_impl template.
1714 class __future_base::_Async_state_commonV2
1715 : public __future_base::_State_base
1718 ~_Async_state_commonV2() = default;
1720 // Make waiting functions block until the thread completes, as if joined.
1722 // This function is used by wait() to satisfy the first requirement below
1723 // and by wait_for() / wait_until() to satisfy the second.
1727 // - a call to a waiting function on an asynchronous return object that
1728 // shares the shared state created by this async call shall block until
1729 // the associated thread has completed, as if joined, or else time out.
1731 // - the associated thread completion synchronizes with the return from
1732 // the first function that successfully detects the ready status of the
1733 // shared state or with the return from the last function that releases
1734 // the shared state, whichever happens first.
1735 virtual void _M_complete_async() { _M_join(); }
1737 void _M_join() { std::call_once(_M_once, &thread::join, &_M_thread); }
1743 // Shared state created by std::async().
1744 // Starts a new thread that runs a function and makes the shared state ready.
1745 template<typename _BoundFn, typename _Res>
1746 class __future_base::_Async_state_impl final
1747 : public __future_base::_Async_state_commonV2
1750 template<typename... _Args>
1752 _Async_state_impl(_Args&&... __args)
1753 : _M_result(new _Result<_Res>()),
1754 _M_fn(std::forward<_Args>(__args)...)
1756 _M_thread = std::thread{&_Async_state_impl::_M_run, this};
1759 // Must not destroy _M_result and _M_fn until the thread finishes.
1760 // Call join() directly rather than through _M_join() because no other
1761 // thread can be referring to this state if it is being destroyed.
1762 ~_Async_state_impl()
1764 if (_M_thread.joinable())
1774 _M_set_result(_S_task_setter(_M_result, _M_fn));
1776 __catch (const __cxxabiv1::__forced_unwind&)
1778 // make the shared state ready on thread cancellation
1779 if (static_cast<bool>(_M_result))
1780 this->_M_break_promise(std::move(_M_result));
1781 __throw_exception_again;
1785 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1786 _Ptr_type _M_result;
1792 template<typename _Fn, typename... _Args>
1793 _GLIBCXX_NODISCARD future<__async_result_of<_Fn, _Args...>>
1794 async(launch __policy, _Fn&& __fn, _Args&&... __args)
1796 using _Wr = std::thread::_Call_wrapper<_Fn, _Args...>;
1797 using _As = __future_base::_Async_state_impl<_Wr>;
1798 using _Ds = __future_base::_Deferred_state<_Wr>;
1800 std::shared_ptr<__future_base::_State_base> __state;
1801 if ((__policy & launch::async) == launch::async)
1805 __state = std::make_shared<_As>(std::forward<_Fn>(__fn),
1806 std::forward<_Args>(__args)...);
1809 catch(const system_error& __e)
1811 if (__e.code() != errc::resource_unavailable_try_again
1812 || (__policy & launch::deferred) != launch::deferred)
1819 __state = std::make_shared<_Ds>(std::forward<_Fn>(__fn),
1820 std::forward<_Args>(__args)...);
1822 return future<__async_result_of<_Fn, _Args...>>(std::move(__state));
1825 /// async, potential overload
1826 template<typename _Fn, typename... _Args>
1827 _GLIBCXX_NODISCARD inline future<__async_result_of<_Fn, _Args...>>
1828 async(_Fn&& __fn, _Args&&... __args)
1830 return std::async(launch::async|launch::deferred,
1831 std::forward<_Fn>(__fn),
1832 std::forward<_Args>(__args)...);
1835#endif // _GLIBCXX_ASYNC_ABI_COMPAT
1836#endif // _GLIBCXX_HAS_GTHREADS
1838 /// @} group futures
1839_GLIBCXX_END_NAMESPACE_VERSION
1844#endif // _GLIBCXX_FUTURE