1 // <future> -*- C++ -*-
3 // Copyright (C) 2009-2020 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
100 future_error(future_errc __errc)
101 : future_error(std::make_error_code(__errc))
104 virtual ~future_error() noexcept;
107 what() const noexcept;
110 code() const noexcept { return _M_code; }
114 future_error(error_code __ec)
115 : logic_error("std::future_error: " + __ec.message()), _M_code(__ec)
118 friend void __throw_future_error(int);
123 // Forward declarations.
124 template<typename _Res>
127 template<typename _Res>
130 template<typename _Signature>
133 template<typename _Res>
136 /// Launch code for futures
143 constexpr launch operator&(launch __x, launch __y)
145 return static_cast<launch>(
146 static_cast<int>(__x) & static_cast<int>(__y));
149 constexpr launch operator|(launch __x, launch __y)
151 return static_cast<launch>(
152 static_cast<int>(__x) | static_cast<int>(__y));
155 constexpr launch operator^(launch __x, launch __y)
157 return static_cast<launch>(
158 static_cast<int>(__x) ^ static_cast<int>(__y));
161 constexpr launch operator~(launch __x)
162 { return static_cast<launch>(~static_cast<int>(__x)); }
164 inline launch& operator&=(launch& __x, launch __y)
165 { return __x = __x & __y; }
167 inline launch& operator|=(launch& __x, launch __y)
168 { return __x = __x | __y; }
170 inline launch& operator^=(launch& __x, launch __y)
171 { return __x = __x ^ __y; }
173 /// Status code for futures
174 enum class future_status
181 // _GLIBCXX_RESOLVE_LIB_DEFECTS
182 // 2021. Further incorrect usages of result_of
183 template<typename _Fn, typename... _Args>
184 using __async_result_of = typename __invoke_result<
185 typename decay<_Fn>::type, typename decay<_Args>::type...>::type;
187 template<typename _Fn, typename... _Args>
188 future<__async_result_of<_Fn, _Args...>>
189 async(launch __policy, _Fn&& __fn, _Args&&... __args);
191 template<typename _Fn, typename... _Args>
192 future<__async_result_of<_Fn, _Args...>>
193 async(_Fn&& __fn, _Args&&... __args);
195 #if defined(_GLIBCXX_HAS_GTHREADS)
197 /// Base class and enclosing scope.
200 /// Base class for results.
203 exception_ptr _M_error;
205 _Result_base(const _Result_base&) = delete;
206 _Result_base& operator=(const _Result_base&) = delete;
208 // _M_destroy() allows derived classes to control deallocation
209 virtual void _M_destroy() = 0;
213 void operator()(_Result_base* __fr) const { __fr->_M_destroy(); }
218 virtual ~_Result_base();
221 /// A unique_ptr for result objects.
222 template<typename _Res>
223 using _Ptr = unique_ptr<_Res, _Result_base::_Deleter>;
225 /// A result object that has storage for an object of type _Res.
226 template<typename _Res>
227 struct _Result : _Result_base
230 __gnu_cxx::__aligned_buffer<_Res> _M_storage;
234 typedef _Res result_type;
236 _Result() noexcept : _M_initialized() { }
244 // Return lvalue, future will add const or rvalue-reference
246 _M_value() noexcept { return *_M_storage._M_ptr(); }
249 _M_set(const _Res& __res)
251 ::new (_M_storage._M_addr()) _Res(__res);
252 _M_initialized = true;
258 ::new (_M_storage._M_addr()) _Res(std::move(__res));
259 _M_initialized = true;
263 void _M_destroy() { delete this; }
266 /// A result object that uses an allocator.
267 template<typename _Res, typename _Alloc>
268 struct _Result_alloc final : _Result<_Res>, _Alloc
270 using __allocator_type = __alloc_rebind<_Alloc, _Result_alloc>;
273 _Result_alloc(const _Alloc& __a) : _Result<_Res>(), _Alloc(__a)
279 __allocator_type __a(*this);
280 __allocated_ptr<__allocator_type> __guard_ptr{ __a, this };
281 this->~_Result_alloc();
285 // Create a result object that uses an allocator.
286 template<typename _Res, typename _Allocator>
287 static _Ptr<_Result_alloc<_Res, _Allocator>>
288 _S_allocate_result(const _Allocator& __a)
290 using __result_type = _Result_alloc<_Res, _Allocator>;
291 typename __result_type::__allocator_type __a2(__a);
292 auto __guard = std::__allocate_guarded(__a2);
293 __result_type* __p = ::new((void*)__guard.get()) __result_type{__a};
295 return _Ptr<__result_type>(__p);
298 // Keep it simple for std::allocator.
299 template<typename _Res, typename _Tp>
300 static _Ptr<_Result<_Res>>
301 _S_allocate_result(const std::allocator<_Tp>& __a)
303 return _Ptr<_Result<_Res>>(new _Result<_Res>);
306 // Base class for various types of shared state created by an
307 // asynchronous provider (such as a std::promise) and shared with one
308 // or more associated futures.
311 typedef _Ptr<_Result_base> _Ptr_type;
313 enum _Status : unsigned {
319 __atomic_futex_unsigned<> _M_status;
320 atomic_flag _M_retrieved = ATOMIC_FLAG_INIT;
324 _State_baseV2() noexcept : _M_result(), _M_status(_Status::__not_ready)
326 _State_baseV2(const _State_baseV2&) = delete;
327 _State_baseV2& operator=(const _State_baseV2&) = delete;
328 virtual ~_State_baseV2() = default;
333 // Run any deferred function or join any asynchronous thread:
335 // Acquire MO makes sure this synchronizes with the thread that made
337 _M_status._M_load_when_equal(_Status::__ready, memory_order_acquire);
341 template<typename _Rep, typename _Period>
343 wait_for(const chrono::duration<_Rep, _Period>& __rel)
345 // First, check if the future has been made ready. Use acquire MO
346 // to synchronize with the thread that made it ready.
347 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
348 return future_status::ready;
350 if (_M_is_deferred_future())
351 return future_status::deferred;
353 // Don't wait unless the relative time is greater than zero.
354 if (__rel > __rel.zero()
355 && _M_status._M_load_when_equal_for(_Status::__ready,
356 memory_order_acquire,
359 // _GLIBCXX_RESOLVE_LIB_DEFECTS
360 // 2100. timed waiting functions must also join
361 // This call is a no-op by default except on an async future,
362 // in which case the async thread is joined. It's also not a
363 // no-op for a deferred future, but such a future will never
364 // reach this point because it returns future_status::deferred
365 // instead of waiting for the future to become ready (see
366 // above). Async futures synchronize in this call, so we need
367 // no further synchronization here.
370 return future_status::ready;
372 return future_status::timeout;
375 template<typename _Clock, typename _Duration>
377 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
379 #if __cplusplus > 201703L
380 static_assert(chrono::is_clock_v<_Clock>);
382 // First, check if the future has been made ready. Use acquire MO
383 // to synchronize with the thread that made it ready.
384 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
385 return future_status::ready;
387 if (_M_is_deferred_future())
388 return future_status::deferred;
390 if (_M_status._M_load_when_equal_until(_Status::__ready,
391 memory_order_acquire,
394 // _GLIBCXX_RESOLVE_LIB_DEFECTS
395 // 2100. timed waiting functions must also join
396 // See wait_for(...) above.
399 return future_status::ready;
401 return future_status::timeout;
404 // Provide a result to the shared state and make it ready.
405 // Calls at most once: _M_result = __res();
407 _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
409 bool __did_set = false;
410 // all calls to this function are serialized,
411 // side-effects of invoking __res only happen once
412 call_once(_M_once, &_State_baseV2::_M_do_set, this,
413 std::__addressof(__res), std::__addressof(__did_set));
415 // Use release MO to synchronize with observers of the ready state.
416 _M_status._M_store_notify_all(_Status::__ready,
417 memory_order_release);
418 else if (!__ignore_failure)
419 __throw_future_error(int(future_errc::promise_already_satisfied));
422 // Provide a result to the shared state but delay making it ready
423 // until the calling thread exits.
424 // Calls at most once: _M_result = __res();
426 _M_set_delayed_result(function<_Ptr_type()> __res,
427 weak_ptr<_State_baseV2> __self)
429 bool __did_set = false;
430 unique_ptr<_Make_ready> __mr{new _Make_ready};
431 // all calls to this function are serialized,
432 // side-effects of invoking __res only happen once
433 call_once(_M_once, &_State_baseV2::_M_do_set, this,
434 std::__addressof(__res), std::__addressof(__did_set));
436 __throw_future_error(int(future_errc::promise_already_satisfied));
437 __mr->_M_shared_state = std::move(__self);
442 // Abandon this shared state.
444 _M_break_promise(_Ptr_type __res)
446 if (static_cast<bool>(__res))
449 make_exception_ptr(future_error(future_errc::broken_promise));
450 // This function is only called when the last asynchronous result
451 // provider is abandoning this shared state, so noone can be
452 // trying to make the shared state ready at the same time, and
453 // we can access _M_result directly instead of through call_once.
454 _M_result.swap(__res);
455 // Use release MO to synchronize with observers of the ready state.
456 _M_status._M_store_notify_all(_Status::__ready,
457 memory_order_release);
461 // Called when this object is first passed to a future.
463 _M_set_retrieved_flag()
465 if (_M_retrieved.test_and_set())
466 __throw_future_error(int(future_errc::future_already_retrieved));
469 template<typename _Res, typename _Arg>
473 template<typename _Res, typename _Arg>
474 struct _Setter<_Res, _Arg&>
476 // check this is only used by promise<R>::set_value(const R&)
477 // or promise<R&>::set_value(R&)
478 static_assert(is_same<_Res, _Arg&>::value // promise<R&>
479 || is_same<const _Res, _Arg>::value, // promise<R>
480 "Invalid specialisation");
482 // Used by std::promise to copy construct the result.
483 typename promise<_Res>::_Ptr_type operator()() const
485 _M_promise->_M_storage->_M_set(*_M_arg);
486 return std::move(_M_promise->_M_storage);
488 promise<_Res>* _M_promise;
493 template<typename _Res>
494 struct _Setter<_Res, _Res&&>
496 // Used by std::promise to move construct the result.
497 typename promise<_Res>::_Ptr_type operator()() const
499 _M_promise->_M_storage->_M_set(std::move(*_M_arg));
500 return std::move(_M_promise->_M_storage);
502 promise<_Res>* _M_promise;
507 template<typename _Res>
508 struct _Setter<_Res, void>
510 static_assert(is_void<_Res>::value, "Only used for promise<void>");
512 typename promise<_Res>::_Ptr_type operator()() const
513 { return std::move(_M_promise->_M_storage); }
515 promise<_Res>* _M_promise;
518 struct __exception_ptr_tag { };
521 template<typename _Res>
522 struct _Setter<_Res, __exception_ptr_tag>
524 // Used by std::promise to store an exception as the result.
525 typename promise<_Res>::_Ptr_type operator()() const
527 _M_promise->_M_storage->_M_error = *_M_ex;
528 return std::move(_M_promise->_M_storage);
531 promise<_Res>* _M_promise;
532 exception_ptr* _M_ex;
535 template<typename _Res, typename _Arg>
536 __attribute__((__always_inline__))
537 static _Setter<_Res, _Arg&&>
538 __setter(promise<_Res>* __prom, _Arg&& __arg) noexcept
540 return _Setter<_Res, _Arg&&>{ __prom, std::__addressof(__arg) };
543 template<typename _Res>
544 __attribute__((__always_inline__))
545 static _Setter<_Res, __exception_ptr_tag>
546 __setter(exception_ptr& __ex, promise<_Res>* __prom) noexcept
548 return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex };
551 template<typename _Res>
552 __attribute__((__always_inline__))
553 static _Setter<_Res, void>
554 __setter(promise<_Res>* __prom) noexcept
556 return _Setter<_Res, void>{ __prom };
559 template<typename _Tp>
561 _S_check(const shared_ptr<_Tp>& __p)
563 if (!static_cast<bool>(__p))
564 __throw_future_error((int)future_errc::no_state);
568 // The function invoked with std::call_once(_M_once, ...).
570 _M_do_set(function<_Ptr_type()>* __f, bool* __did_set)
572 _Ptr_type __res = (*__f)();
573 // Notify the caller that we did try to set; if we do not throw an
574 // exception, the caller will be aware that it did set (e.g., see
577 _M_result.swap(__res); // nothrow
580 // Wait for completion of async function.
581 virtual void _M_complete_async() { }
583 // Return true if state corresponds to a deferred function.
584 virtual bool _M_is_deferred_future() const { return false; }
586 struct _Make_ready final : __at_thread_exit_elt
588 weak_ptr<_State_baseV2> _M_shared_state;
589 static void _S_run(void*);
594 #ifdef _GLIBCXX_ASYNC_ABI_COMPAT
596 class _Async_state_common;
598 using _State_base = _State_baseV2;
599 class _Async_state_commonV2;
602 template<typename _BoundFn,
603 typename _Res = decltype(std::declval<_BoundFn&>()())>
604 class _Deferred_state;
606 template<typename _BoundFn,
607 typename _Res = decltype(std::declval<_BoundFn&>()())>
608 class _Async_state_impl;
610 template<typename _Signature>
611 class _Task_state_base;
613 template<typename _Fn, typename _Alloc, typename _Signature>
616 template<typename _BoundFn>
617 static std::shared_ptr<_State_base>
618 _S_make_deferred_state(_BoundFn&& __fn);
620 template<typename _BoundFn>
621 static std::shared_ptr<_State_base>
622 _S_make_async_state(_BoundFn&& __fn);
624 template<typename _Res_ptr, typename _Fn,
625 typename _Res = typename _Res_ptr::element_type::result_type>
628 template<typename _Res_ptr, typename _BoundFn>
629 static _Task_setter<_Res_ptr, _BoundFn>
630 _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call)
632 return { std::__addressof(__ptr), std::__addressof(__call) };
636 /// Partial specialization for reference types.
637 template<typename _Res>
638 struct __future_base::_Result<_Res&> : __future_base::_Result_base
640 typedef _Res& result_type;
642 _Result() noexcept : _M_value_ptr() { }
645 _M_set(_Res& __res) noexcept
646 { _M_value_ptr = std::addressof(__res); }
648 _Res& _M_get() noexcept { return *_M_value_ptr; }
653 void _M_destroy() { delete this; }
656 /// Explicit specialization for void.
658 struct __future_base::_Result<void> : __future_base::_Result_base
660 typedef void result_type;
663 void _M_destroy() { delete this; }
666 #ifndef _GLIBCXX_ASYNC_ABI_COMPAT
668 // Allow _Setter objects to be stored locally in std::function
669 template<typename _Res, typename _Arg>
670 struct __is_location_invariant
671 <__future_base::_State_base::_Setter<_Res, _Arg>>
674 // Allow _Task_setter objects to be stored locally in std::function
675 template<typename _Res_ptr, typename _Fn, typename _Res>
676 struct __is_location_invariant
677 <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>>
680 /// Common implementation for future and shared_future.
681 template<typename _Res>
682 class __basic_future : public __future_base
685 typedef shared_ptr<_State_base> __state_type;
686 typedef __future_base::_Result<_Res>& __result_type;
689 __state_type _M_state;
693 __basic_future(const __basic_future&) = delete;
694 __basic_future& operator=(const __basic_future&) = delete;
697 valid() const noexcept { return static_cast<bool>(_M_state); }
702 _State_base::_S_check(_M_state);
706 template<typename _Rep, typename _Period>
708 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
710 _State_base::_S_check(_M_state);
711 return _M_state->wait_for(__rel);
714 template<typename _Clock, typename _Duration>
716 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
718 _State_base::_S_check(_M_state);
719 return _M_state->wait_until(__abs);
723 /// Wait for the state to be ready and rethrow any stored exception
725 _M_get_result() const
727 _State_base::_S_check(_M_state);
728 _Result_base& __res = _M_state->wait();
729 if (!(__res._M_error == 0))
730 rethrow_exception(__res._M_error);
731 return static_cast<__result_type>(__res);
734 void _M_swap(__basic_future& __that) noexcept
736 _M_state.swap(__that._M_state);
739 // Construction of a future by promise::get_future()
741 __basic_future(const __state_type& __state) : _M_state(__state)
743 _State_base::_S_check(_M_state);
744 _M_state->_M_set_retrieved_flag();
747 // Copy construction from a shared_future
749 __basic_future(const shared_future<_Res>&) noexcept;
751 // Move construction from a shared_future
753 __basic_future(shared_future<_Res>&&) noexcept;
755 // Move construction from a future
757 __basic_future(future<_Res>&&) noexcept;
759 constexpr __basic_future() noexcept : _M_state() { }
763 explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { }
764 ~_Reset() { _M_fut._M_state.reset(); }
765 __basic_future& _M_fut;
770 /// Primary template for future.
771 template<typename _Res>
772 class future : public __basic_future<_Res>
774 friend class promise<_Res>;
775 template<typename> friend class packaged_task;
776 template<typename _Fn, typename... _Args>
777 friend future<__async_result_of<_Fn, _Args...>>
778 async(launch, _Fn&&, _Args&&...);
780 typedef __basic_future<_Res> _Base_type;
781 typedef typename _Base_type::__state_type __state_type;
784 future(const __state_type& __state) : _Base_type(__state) { }
787 constexpr future() noexcept : _Base_type() { }
790 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
793 future(const future&) = delete;
794 future& operator=(const future&) = delete;
796 future& operator=(future&& __fut) noexcept
798 future(std::move(__fut))._M_swap(*this);
802 /// Retrieving the value
806 typename _Base_type::_Reset __reset(*this);
807 return std::move(this->_M_get_result()._M_value());
810 shared_future<_Res> share() noexcept;
813 /// Partial specialization for future<R&>
814 template<typename _Res>
815 class future<_Res&> : public __basic_future<_Res&>
817 friend class promise<_Res&>;
818 template<typename> friend class packaged_task;
819 template<typename _Fn, typename... _Args>
820 friend future<__async_result_of<_Fn, _Args...>>
821 async(launch, _Fn&&, _Args&&...);
823 typedef __basic_future<_Res&> _Base_type;
824 typedef typename _Base_type::__state_type __state_type;
827 future(const __state_type& __state) : _Base_type(__state) { }
830 constexpr future() noexcept : _Base_type() { }
833 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
836 future(const future&) = delete;
837 future& operator=(const future&) = delete;
839 future& operator=(future&& __fut) noexcept
841 future(std::move(__fut))._M_swap(*this);
845 /// Retrieving the value
849 typename _Base_type::_Reset __reset(*this);
850 return this->_M_get_result()._M_get();
853 shared_future<_Res&> share() noexcept;
856 /// Explicit specialization for future<void>
858 class future<void> : public __basic_future<void>
860 friend class promise<void>;
861 template<typename> friend class packaged_task;
862 template<typename _Fn, typename... _Args>
863 friend future<__async_result_of<_Fn, _Args...>>
864 async(launch, _Fn&&, _Args&&...);
866 typedef __basic_future<void> _Base_type;
867 typedef typename _Base_type::__state_type __state_type;
870 future(const __state_type& __state) : _Base_type(__state) { }
873 constexpr future() noexcept : _Base_type() { }
876 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
879 future(const future&) = delete;
880 future& operator=(const future&) = delete;
882 future& operator=(future&& __fut) noexcept
884 future(std::move(__fut))._M_swap(*this);
888 /// Retrieving the value
892 typename _Base_type::_Reset __reset(*this);
893 this->_M_get_result();
896 shared_future<void> share() noexcept;
900 /// Primary template for shared_future.
901 template<typename _Res>
902 class shared_future : public __basic_future<_Res>
904 typedef __basic_future<_Res> _Base_type;
907 constexpr shared_future() noexcept : _Base_type() { }
910 shared_future(const shared_future& __sf) noexcept : _Base_type(__sf) { }
912 /// Construct from a future rvalue
913 shared_future(future<_Res>&& __uf) noexcept
914 : _Base_type(std::move(__uf))
917 /// Construct from a shared_future rvalue
918 shared_future(shared_future&& __sf) noexcept
919 : _Base_type(std::move(__sf))
922 shared_future& operator=(const shared_future& __sf) noexcept
924 shared_future(__sf)._M_swap(*this);
928 shared_future& operator=(shared_future&& __sf) noexcept
930 shared_future(std::move(__sf))._M_swap(*this);
934 /// Retrieving the value
936 get() const { return this->_M_get_result()._M_value(); }
939 /// Partial specialization for shared_future<R&>
940 template<typename _Res>
941 class shared_future<_Res&> : public __basic_future<_Res&>
943 typedef __basic_future<_Res&> _Base_type;
946 constexpr shared_future() noexcept : _Base_type() { }
949 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
951 /// Construct from a future rvalue
952 shared_future(future<_Res&>&& __uf) noexcept
953 : _Base_type(std::move(__uf))
956 /// Construct from a shared_future rvalue
957 shared_future(shared_future&& __sf) noexcept
958 : _Base_type(std::move(__sf))
961 shared_future& operator=(const shared_future& __sf)
963 shared_future(__sf)._M_swap(*this);
967 shared_future& operator=(shared_future&& __sf) noexcept
969 shared_future(std::move(__sf))._M_swap(*this);
973 /// Retrieving the value
975 get() const { return this->_M_get_result()._M_get(); }
978 /// Explicit specialization for shared_future<void>
980 class shared_future<void> : public __basic_future<void>
982 typedef __basic_future<void> _Base_type;
985 constexpr shared_future() noexcept : _Base_type() { }
988 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
990 /// Construct from a future rvalue
991 shared_future(future<void>&& __uf) noexcept
992 : _Base_type(std::move(__uf))
995 /// Construct from a shared_future rvalue
996 shared_future(shared_future&& __sf) noexcept
997 : _Base_type(std::move(__sf))
1000 shared_future& operator=(const shared_future& __sf)
1002 shared_future(__sf)._M_swap(*this);
1006 shared_future& operator=(shared_future&& __sf) noexcept
1008 shared_future(std::move(__sf))._M_swap(*this);
1012 // Retrieving the value
1014 get() const { this->_M_get_result(); }
1017 // Now we can define the protected __basic_future constructors.
1018 template<typename _Res>
1019 inline __basic_future<_Res>::
1020 __basic_future(const shared_future<_Res>& __sf) noexcept
1021 : _M_state(__sf._M_state)
1024 template<typename _Res>
1025 inline __basic_future<_Res>::
1026 __basic_future(shared_future<_Res>&& __sf) noexcept
1027 : _M_state(std::move(__sf._M_state))
1030 template<typename _Res>
1031 inline __basic_future<_Res>::
1032 __basic_future(future<_Res>&& __uf) noexcept
1033 : _M_state(std::move(__uf._M_state))
1036 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1037 // 2556. Wide contract for future::share()
1038 template<typename _Res>
1039 inline shared_future<_Res>
1040 future<_Res>::share() noexcept
1041 { return shared_future<_Res>(std::move(*this)); }
1043 template<typename _Res>
1044 inline shared_future<_Res&>
1045 future<_Res&>::share() noexcept
1046 { return shared_future<_Res&>(std::move(*this)); }
1048 inline shared_future<void>
1049 future<void>::share() noexcept
1050 { return shared_future<void>(std::move(*this)); }
1052 /// Primary template for promise
1053 template<typename _Res>
1056 typedef __future_base::_State_base _State;
1057 typedef __future_base::_Result<_Res> _Res_type;
1058 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1059 template<typename, typename> friend class _State::_Setter;
1062 shared_ptr<_State> _M_future;
1063 _Ptr_type _M_storage;
1067 : _M_future(std::make_shared<_State>()),
1068 _M_storage(new _Res_type())
1071 promise(promise&& __rhs) noexcept
1072 : _M_future(std::move(__rhs._M_future)),
1073 _M_storage(std::move(__rhs._M_storage))
1076 template<typename _Allocator>
1077 promise(allocator_arg_t, const _Allocator& __a)
1078 : _M_future(std::allocate_shared<_State>(__a)),
1079 _M_storage(__future_base::_S_allocate_result<_Res>(__a))
1082 template<typename _Allocator>
1083 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1084 : _M_future(std::move(__rhs._M_future)),
1085 _M_storage(std::move(__rhs._M_storage))
1088 promise(const promise&) = delete;
1092 if (static_cast<bool>(_M_future) && !_M_future.unique())
1093 _M_future->_M_break_promise(std::move(_M_storage));
1098 operator=(promise&& __rhs) noexcept
1100 promise(std::move(__rhs)).swap(*this);
1104 promise& operator=(const promise&) = delete;
1107 swap(promise& __rhs) noexcept
1109 _M_future.swap(__rhs._M_future);
1110 _M_storage.swap(__rhs._M_storage);
1113 // Retrieving the result
1116 { return future<_Res>(_M_future); }
1118 // Setting the result
1120 set_value(const _Res& __r)
1121 { _M_state()._M_set_result(_State::__setter(this, __r)); }
1124 set_value(_Res&& __r)
1125 { _M_state()._M_set_result(_State::__setter(this, std::move(__r))); }
1128 set_exception(exception_ptr __p)
1129 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1132 set_value_at_thread_exit(const _Res& __r)
1134 _M_state()._M_set_delayed_result(_State::__setter(this, __r),
1139 set_value_at_thread_exit(_Res&& __r)
1141 _M_state()._M_set_delayed_result(
1142 _State::__setter(this, std::move(__r)), _M_future);
1146 set_exception_at_thread_exit(exception_ptr __p)
1148 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1156 __future_base::_State_base::_S_check(_M_future);
1161 template<typename _Res>
1163 swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
1166 template<typename _Res, typename _Alloc>
1167 struct uses_allocator<promise<_Res>, _Alloc>
1168 : public true_type { };
1171 /// Partial specialization for promise<R&>
1172 template<typename _Res>
1173 class promise<_Res&>
1175 typedef __future_base::_State_base _State;
1176 typedef __future_base::_Result<_Res&> _Res_type;
1177 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1178 template<typename, typename> friend class _State::_Setter;
1181 shared_ptr<_State> _M_future;
1182 _Ptr_type _M_storage;
1186 : _M_future(std::make_shared<_State>()),
1187 _M_storage(new _Res_type())
1190 promise(promise&& __rhs) noexcept
1191 : _M_future(std::move(__rhs._M_future)),
1192 _M_storage(std::move(__rhs._M_storage))
1195 template<typename _Allocator>
1196 promise(allocator_arg_t, const _Allocator& __a)
1197 : _M_future(std::allocate_shared<_State>(__a)),
1198 _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
1201 template<typename _Allocator>
1202 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1203 : _M_future(std::move(__rhs._M_future)),
1204 _M_storage(std::move(__rhs._M_storage))
1207 promise(const promise&) = delete;
1211 if (static_cast<bool>(_M_future) && !_M_future.unique())
1212 _M_future->_M_break_promise(std::move(_M_storage));
1217 operator=(promise&& __rhs) noexcept
1219 promise(std::move(__rhs)).swap(*this);
1223 promise& operator=(const promise&) = delete;
1226 swap(promise& __rhs) noexcept
1228 _M_future.swap(__rhs._M_future);
1229 _M_storage.swap(__rhs._M_storage);
1232 // Retrieving the result
1235 { return future<_Res&>(_M_future); }
1237 // Setting the result
1239 set_value(_Res& __r)
1240 { _M_state()._M_set_result(_State::__setter(this, __r)); }
1243 set_exception(exception_ptr __p)
1244 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1247 set_value_at_thread_exit(_Res& __r)
1249 _M_state()._M_set_delayed_result(_State::__setter(this, __r),
1254 set_exception_at_thread_exit(exception_ptr __p)
1256 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1264 __future_base::_State_base::_S_check(_M_future);
1269 /// Explicit specialization for promise<void>
1273 typedef __future_base::_State_base _State;
1274 typedef __future_base::_Result<void> _Res_type;
1275 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1276 template<typename, typename> friend class _State::_Setter;
1279 shared_ptr<_State> _M_future;
1280 _Ptr_type _M_storage;
1284 : _M_future(std::make_shared<_State>()),
1285 _M_storage(new _Res_type())
1288 promise(promise&& __rhs) noexcept
1289 : _M_future(std::move(__rhs._M_future)),
1290 _M_storage(std::move(__rhs._M_storage))
1293 template<typename _Allocator>
1294 promise(allocator_arg_t, const _Allocator& __a)
1295 : _M_future(std::allocate_shared<_State>(__a)),
1296 _M_storage(__future_base::_S_allocate_result<void>(__a))
1299 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1300 // 2095. missing constructors needed for uses-allocator construction
1301 template<typename _Allocator>
1302 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1303 : _M_future(std::move(__rhs._M_future)),
1304 _M_storage(std::move(__rhs._M_storage))
1307 promise(const promise&) = delete;
1311 if (static_cast<bool>(_M_future) && !_M_future.unique())
1312 _M_future->_M_break_promise(std::move(_M_storage));
1317 operator=(promise&& __rhs) noexcept
1319 promise(std::move(__rhs)).swap(*this);
1323 promise& operator=(const promise&) = delete;
1326 swap(promise& __rhs) noexcept
1328 _M_future.swap(__rhs._M_future);
1329 _M_storage.swap(__rhs._M_storage);
1332 // Retrieving the result
1335 { return future<void>(_M_future); }
1337 // Setting the result
1340 { _M_state()._M_set_result(_State::__setter(this)); }
1343 set_exception(exception_ptr __p)
1344 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1347 set_value_at_thread_exit()
1348 { _M_state()._M_set_delayed_result(_State::__setter(this), _M_future); }
1351 set_exception_at_thread_exit(exception_ptr __p)
1353 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1361 __future_base::_State_base::_S_check(_M_future);
1366 template<typename _Ptr_type, typename _Fn, typename _Res>
1367 struct __future_base::_Task_setter
1369 // Invoke the function and provide the result to the caller.
1370 _Ptr_type operator()() const
1374 (*_M_result)->_M_set((*_M_fn)());
1376 __catch(const __cxxabiv1::__forced_unwind&)
1378 __throw_exception_again; // will cause broken_promise
1382 (*_M_result)->_M_error = current_exception();
1384 return std::move(*_M_result);
1386 _Ptr_type* _M_result;
1390 template<typename _Ptr_type, typename _Fn>
1391 struct __future_base::_Task_setter<_Ptr_type, _Fn, void>
1393 _Ptr_type operator()() const
1399 __catch(const __cxxabiv1::__forced_unwind&)
1401 __throw_exception_again; // will cause broken_promise
1405 (*_M_result)->_M_error = current_exception();
1407 return std::move(*_M_result);
1409 _Ptr_type* _M_result;
1413 // Holds storage for a packaged_task's result.
1414 template<typename _Res, typename... _Args>
1415 struct __future_base::_Task_state_base<_Res(_Args...)>
1416 : __future_base::_State_base
1418 typedef _Res _Res_type;
1420 template<typename _Alloc>
1421 _Task_state_base(const _Alloc& __a)
1422 : _M_result(_S_allocate_result<_Res>(__a))
1425 // Invoke the stored task and make the state ready.
1427 _M_run(_Args&&... __args) = 0;
1429 // Invoke the stored task and make the state ready at thread exit.
1431 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0;
1433 virtual shared_ptr<_Task_state_base>
1436 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1437 _Ptr_type _M_result;
1440 // Holds a packaged_task's stored task.
1441 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1442 struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final
1443 : __future_base::_Task_state_base<_Res(_Args...)>
1445 template<typename _Fn2>
1446 _Task_state(_Fn2&& __fn, const _Alloc& __a)
1447 : _Task_state_base<_Res(_Args...)>(__a),
1448 _M_impl(std::forward<_Fn2>(__fn), __a)
1453 _M_run(_Args&&... __args)
1455 auto __boundfn = [&] () -> _Res {
1456 return std::__invoke_r<_Res>(_M_impl._M_fn,
1457 std::forward<_Args>(__args)...);
1459 this->_M_set_result(_S_task_setter(this->_M_result, __boundfn));
1463 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self)
1465 auto __boundfn = [&] () -> _Res {
1466 return std::__invoke_r<_Res>(_M_impl._M_fn,
1467 std::forward<_Args>(__args)...);
1469 this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn),
1473 virtual shared_ptr<_Task_state_base<_Res(_Args...)>>
1476 struct _Impl : _Alloc
1478 template<typename _Fn2>
1479 _Impl(_Fn2&& __fn, const _Alloc& __a)
1480 : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { }
1485 template<typename _Signature, typename _Fn,
1486 typename _Alloc = std::allocator<int>>
1487 static shared_ptr<__future_base::_Task_state_base<_Signature>>
1488 __create_task_state(_Fn&& __fn, const _Alloc& __a = _Alloc())
1490 typedef typename decay<_Fn>::type _Fn2;
1491 typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State;
1492 return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a);
1495 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1496 shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>>
1497 __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset()
1499 return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn),
1500 static_cast<_Alloc&>(_M_impl));
1504 template<typename _Res, typename... _ArgTypes>
1505 class packaged_task<_Res(_ArgTypes...)>
1507 typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type;
1508 shared_ptr<_State_type> _M_state;
1510 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1511 // 3039. Unnecessary decay in thread and packaged_task
1512 template<typename _Fn, typename _Fn2 = __remove_cvref_t<_Fn>>
1514 = typename enable_if<!is_same<packaged_task, _Fn2>::value>::type;
1517 // Construction and destruction
1518 packaged_task() noexcept { }
1520 template<typename _Fn, typename = __not_same<_Fn>>
1522 packaged_task(_Fn&& __fn)
1524 __create_task_state<_Res(_ArgTypes...)>(std::forward<_Fn>(__fn)))
1527 #if __cplusplus < 201703L
1528 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1529 // 2097. packaged_task constructors should be constrained
1530 // 2407. [this constructor should not be] explicit
1531 // 2921. packaged_task and type-erased allocators
1532 template<typename _Fn, typename _Alloc, typename = __not_same<_Fn>>
1533 packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn)
1534 : _M_state(__create_task_state<_Res(_ArgTypes...)>(
1535 std::forward<_Fn>(__fn), __a))
1538 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1539 // 2095. missing constructors needed for uses-allocator construction
1540 template<typename _Allocator>
1541 packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
1544 template<typename _Allocator>
1545 packaged_task(allocator_arg_t, const _Allocator&,
1546 const packaged_task&) = delete;
1548 template<typename _Allocator>
1549 packaged_task(allocator_arg_t, const _Allocator&,
1550 packaged_task&& __other) noexcept
1551 { this->swap(__other); }
1556 if (static_cast<bool>(_M_state) && !_M_state.unique())
1557 _M_state->_M_break_promise(std::move(_M_state->_M_result));
1561 packaged_task(const packaged_task&) = delete;
1562 packaged_task& operator=(const packaged_task&) = delete;
1565 packaged_task(packaged_task&& __other) noexcept
1566 { this->swap(__other); }
1568 packaged_task& operator=(packaged_task&& __other) noexcept
1570 packaged_task(std::move(__other)).swap(*this);
1575 swap(packaged_task& __other) noexcept
1576 { _M_state.swap(__other._M_state); }
1579 valid() const noexcept
1580 { return static_cast<bool>(_M_state); }
1585 { return future<_Res>(_M_state); }
1589 operator()(_ArgTypes... __args)
1591 __future_base::_State_base::_S_check(_M_state);
1592 _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
1596 make_ready_at_thread_exit(_ArgTypes... __args)
1598 __future_base::_State_base::_S_check(_M_state);
1599 _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state);
1605 __future_base::_State_base::_S_check(_M_state);
1606 packaged_task __tmp;
1607 __tmp._M_state = _M_state;
1608 _M_state = _M_state->_M_reset();
1613 template<typename _Res, typename... _ArgTypes>
1615 swap(packaged_task<_Res(_ArgTypes...)>& __x,
1616 packaged_task<_Res(_ArgTypes...)>& __y) noexcept
1619 #if __cplusplus < 201703L
1620 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1621 // 2976. Dangling uses_allocator specialization for packaged_task
1622 template<typename _Res, typename _Alloc>
1623 struct uses_allocator<packaged_task<_Res>, _Alloc>
1624 : public true_type { };
1627 // Shared state created by std::async().
1628 // Holds a deferred function and storage for its result.
1629 template<typename _BoundFn, typename _Res>
1630 class __future_base::_Deferred_state final
1631 : public __future_base::_State_base
1635 _Deferred_state(_BoundFn&& __fn)
1636 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1640 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1641 _Ptr_type _M_result;
1644 // Run the deferred function.
1648 // Multiple threads can call a waiting function on the future and
1649 // reach this point at the same time. The call_once in _M_set_result
1650 // ensures only the first one run the deferred function, stores the
1651 // result in _M_result, swaps that with the base _M_result and makes
1652 // the state ready. Tell _M_set_result to ignore failure so all later
1653 // calls do nothing.
1654 _M_set_result(_S_task_setter(_M_result, _M_fn), true);
1657 // Caller should check whether the state is ready first, because this
1658 // function will return true even after the deferred function has run.
1659 virtual bool _M_is_deferred_future() const { return true; }
1662 // Common functionality hoisted out of the _Async_state_impl template.
1663 class __future_base::_Async_state_commonV2
1664 : public __future_base::_State_base
1667 ~_Async_state_commonV2() = default;
1669 // Make waiting functions block until the thread completes, as if joined.
1671 // This function is used by wait() to satisfy the first requirement below
1672 // and by wait_for() / wait_until() to satisfy the second.
1676 // - a call to a waiting function on an asynchronous return object that
1677 // shares the shared state created by this async call shall block until
1678 // the associated thread has completed, as if joined, or else time out.
1680 // - the associated thread completion synchronizes with the return from
1681 // the first function that successfully detects the ready status of the
1682 // shared state or with the return from the last function that releases
1683 // the shared state, whichever happens first.
1684 virtual void _M_complete_async() { _M_join(); }
1686 void _M_join() { std::call_once(_M_once, &thread::join, &_M_thread); }
1692 // Shared state created by std::async().
1693 // Starts a new thread that runs a function and makes the shared state ready.
1694 template<typename _BoundFn, typename _Res>
1695 class __future_base::_Async_state_impl final
1696 : public __future_base::_Async_state_commonV2
1700 _Async_state_impl(_BoundFn&& __fn)
1701 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1703 _M_thread = std::thread{ [this] {
1706 _M_set_result(_S_task_setter(_M_result, _M_fn));
1708 __catch (const __cxxabiv1::__forced_unwind&)
1710 // make the shared state ready on thread cancellation
1711 if (static_cast<bool>(_M_result))
1712 this->_M_break_promise(std::move(_M_result));
1713 __throw_exception_again;
1718 // Must not destroy _M_result and _M_fn until the thread finishes.
1719 // Call join() directly rather than through _M_join() because no other
1720 // thread can be referring to this state if it is being destroyed.
1721 ~_Async_state_impl() { if (_M_thread.joinable()) _M_thread.join(); }
1724 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1725 _Ptr_type _M_result;
1729 template<typename _BoundFn>
1730 inline std::shared_ptr<__future_base::_State_base>
1731 __future_base::_S_make_deferred_state(_BoundFn&& __fn)
1733 typedef typename remove_reference<_BoundFn>::type __fn_type;
1734 typedef _Deferred_state<__fn_type> __state_type;
1735 return std::make_shared<__state_type>(std::move(__fn));
1738 template<typename _BoundFn>
1739 inline std::shared_ptr<__future_base::_State_base>
1740 __future_base::_S_make_async_state(_BoundFn&& __fn)
1742 typedef typename remove_reference<_BoundFn>::type __fn_type;
1743 typedef _Async_state_impl<__fn_type> __state_type;
1744 return std::make_shared<__state_type>(std::move(__fn));
1749 template<typename _Fn, typename... _Args>
1750 _GLIBCXX_NODISCARD future<__async_result_of<_Fn, _Args...>>
1751 async(launch __policy, _Fn&& __fn, _Args&&... __args)
1753 std::shared_ptr<__future_base::_State_base> __state;
1754 if ((__policy & launch::async) == launch::async)
1758 __state = __future_base::_S_make_async_state(
1759 std::thread::__make_invoker(std::forward<_Fn>(__fn),
1760 std::forward<_Args>(__args)...)
1763 #if __cpp_exceptions
1764 catch(const system_error& __e)
1766 if (__e.code() != errc::resource_unavailable_try_again
1767 || (__policy & launch::deferred) != launch::deferred)
1774 __state = __future_base::_S_make_deferred_state(
1775 std::thread::__make_invoker(std::forward<_Fn>(__fn),
1776 std::forward<_Args>(__args)...));
1778 return future<__async_result_of<_Fn, _Args...>>(__state);
1781 /// async, potential overload
1782 template<typename _Fn, typename... _Args>
1783 _GLIBCXX_NODISCARD inline future<__async_result_of<_Fn, _Args...>>
1784 async(_Fn&& __fn, _Args&&... __args)
1786 return std::async(launch::async|launch::deferred,
1787 std::forward<_Fn>(__fn),
1788 std::forward<_Args>(__args)...);
1791 #endif // _GLIBCXX_ASYNC_ABI_COMPAT
1792 #endif // _GLIBCXX_HAS_GTHREADS
1794 /// @} group futures
1795 _GLIBCXX_END_NAMESPACE_VERSION
1800 #endif // _GLIBCXX_FUTURE