1 // <future> -*- C++ -*-
3 // Copyright (C) 2009-2019 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;
349 if (_M_is_deferred_future())
350 return future_status::deferred;
351 if (_M_status._M_load_when_equal_for(_Status::__ready,
352 memory_order_acquire, __rel))
354 // _GLIBCXX_RESOLVE_LIB_DEFECTS
355 // 2100. timed waiting functions must also join
356 // This call is a no-op by default except on an async future,
357 // in which case the async thread is joined. It's also not a
358 // no-op for a deferred future, but such a future will never
359 // reach this point because it returns future_status::deferred
360 // instead of waiting for the future to become ready (see
361 // above). Async futures synchronize in this call, so we need
362 // no further synchronization here.
365 return future_status::ready;
367 return future_status::timeout;
370 template<typename _Clock, typename _Duration>
372 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
374 // First, check if the future has been made ready. Use acquire MO
375 // to synchronize with the thread that made it ready.
376 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
377 return future_status::ready;
378 if (_M_is_deferred_future())
379 return future_status::deferred;
380 if (_M_status._M_load_when_equal_until(_Status::__ready,
381 memory_order_acquire, __abs))
383 // _GLIBCXX_RESOLVE_LIB_DEFECTS
384 // 2100. timed waiting functions must also join
385 // See wait_for(...) above.
388 return future_status::ready;
390 return future_status::timeout;
393 // Provide a result to the shared state and make it ready.
394 // Calls at most once: _M_result = __res();
396 _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
398 bool __did_set = false;
399 // all calls to this function are serialized,
400 // side-effects of invoking __res only happen once
401 call_once(_M_once, &_State_baseV2::_M_do_set, this,
402 std::__addressof(__res), std::__addressof(__did_set));
404 // Use release MO to synchronize with observers of the ready state.
405 _M_status._M_store_notify_all(_Status::__ready,
406 memory_order_release);
407 else if (!__ignore_failure)
408 __throw_future_error(int(future_errc::promise_already_satisfied));
411 // Provide a result to the shared state but delay making it ready
412 // until the calling thread exits.
413 // Calls at most once: _M_result = __res();
415 _M_set_delayed_result(function<_Ptr_type()> __res,
416 weak_ptr<_State_baseV2> __self)
418 bool __did_set = false;
419 unique_ptr<_Make_ready> __mr{new _Make_ready};
420 // all calls to this function are serialized,
421 // side-effects of invoking __res only happen once
422 call_once(_M_once, &_State_baseV2::_M_do_set, this,
423 std::__addressof(__res), std::__addressof(__did_set));
425 __throw_future_error(int(future_errc::promise_already_satisfied));
426 __mr->_M_shared_state = std::move(__self);
431 // Abandon this shared state.
433 _M_break_promise(_Ptr_type __res)
435 if (static_cast<bool>(__res))
438 make_exception_ptr(future_error(future_errc::broken_promise));
439 // This function is only called when the last asynchronous result
440 // provider is abandoning this shared state, so noone can be
441 // trying to make the shared state ready at the same time, and
442 // we can access _M_result directly instead of through call_once.
443 _M_result.swap(__res);
444 // Use release MO to synchronize with observers of the ready state.
445 _M_status._M_store_notify_all(_Status::__ready,
446 memory_order_release);
450 // Called when this object is first passed to a future.
452 _M_set_retrieved_flag()
454 if (_M_retrieved.test_and_set())
455 __throw_future_error(int(future_errc::future_already_retrieved));
458 template<typename _Res, typename _Arg>
462 template<typename _Res, typename _Arg>
463 struct _Setter<_Res, _Arg&>
465 // check this is only used by promise<R>::set_value(const R&)
466 // or promise<R&>::set_value(R&)
467 static_assert(is_same<_Res, _Arg&>::value // promise<R&>
468 || is_same<const _Res, _Arg>::value, // promise<R>
469 "Invalid specialisation");
471 // Used by std::promise to copy construct the result.
472 typename promise<_Res>::_Ptr_type operator()() const
474 _M_promise->_M_storage->_M_set(*_M_arg);
475 return std::move(_M_promise->_M_storage);
477 promise<_Res>* _M_promise;
482 template<typename _Res>
483 struct _Setter<_Res, _Res&&>
485 // Used by std::promise to move construct the result.
486 typename promise<_Res>::_Ptr_type operator()() const
488 _M_promise->_M_storage->_M_set(std::move(*_M_arg));
489 return std::move(_M_promise->_M_storage);
491 promise<_Res>* _M_promise;
496 template<typename _Res>
497 struct _Setter<_Res, void>
499 static_assert(is_void<_Res>::value, "Only used for promise<void>");
501 typename promise<_Res>::_Ptr_type operator()() const
502 { return std::move(_M_promise->_M_storage); }
504 promise<_Res>* _M_promise;
507 struct __exception_ptr_tag { };
510 template<typename _Res>
511 struct _Setter<_Res, __exception_ptr_tag>
513 // Used by std::promise to store an exception as the result.
514 typename promise<_Res>::_Ptr_type operator()() const
516 _M_promise->_M_storage->_M_error = *_M_ex;
517 return std::move(_M_promise->_M_storage);
520 promise<_Res>* _M_promise;
521 exception_ptr* _M_ex;
524 template<typename _Res, typename _Arg>
525 static _Setter<_Res, _Arg&&>
526 __setter(promise<_Res>* __prom, _Arg&& __arg)
528 _S_check(__prom->_M_future);
529 return _Setter<_Res, _Arg&&>{ __prom, std::__addressof(__arg) };
532 template<typename _Res>
533 static _Setter<_Res, __exception_ptr_tag>
534 __setter(exception_ptr& __ex, promise<_Res>* __prom)
536 _S_check(__prom->_M_future);
537 return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex };
540 template<typename _Res>
541 static _Setter<_Res, void>
542 __setter(promise<_Res>* __prom)
544 _S_check(__prom->_M_future);
545 return _Setter<_Res, void>{ __prom };
548 template<typename _Tp>
550 _S_check(const shared_ptr<_Tp>& __p)
552 if (!static_cast<bool>(__p))
553 __throw_future_error((int)future_errc::no_state);
557 // The function invoked with std::call_once(_M_once, ...).
559 _M_do_set(function<_Ptr_type()>* __f, bool* __did_set)
561 _Ptr_type __res = (*__f)();
562 // Notify the caller that we did try to set; if we do not throw an
563 // exception, the caller will be aware that it did set (e.g., see
566 _M_result.swap(__res); // nothrow
569 // Wait for completion of async function.
570 virtual void _M_complete_async() { }
572 // Return true if state corresponds to a deferred function.
573 virtual bool _M_is_deferred_future() const { return false; }
575 struct _Make_ready final : __at_thread_exit_elt
577 weak_ptr<_State_baseV2> _M_shared_state;
578 static void _S_run(void*);
583 #ifdef _GLIBCXX_ASYNC_ABI_COMPAT
585 class _Async_state_common;
587 using _State_base = _State_baseV2;
588 class _Async_state_commonV2;
591 template<typename _BoundFn,
592 typename _Res = decltype(std::declval<_BoundFn&>()())>
593 class _Deferred_state;
595 template<typename _BoundFn,
596 typename _Res = decltype(std::declval<_BoundFn&>()())>
597 class _Async_state_impl;
599 template<typename _Signature>
600 class _Task_state_base;
602 template<typename _Fn, typename _Alloc, typename _Signature>
605 template<typename _BoundFn>
606 static std::shared_ptr<_State_base>
607 _S_make_deferred_state(_BoundFn&& __fn);
609 template<typename _BoundFn>
610 static std::shared_ptr<_State_base>
611 _S_make_async_state(_BoundFn&& __fn);
613 template<typename _Res_ptr, typename _Fn,
614 typename _Res = typename _Res_ptr::element_type::result_type>
617 template<typename _Res_ptr, typename _BoundFn>
618 static _Task_setter<_Res_ptr, _BoundFn>
619 _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call)
621 return { std::__addressof(__ptr), std::__addressof(__call) };
625 /// Partial specialization for reference types.
626 template<typename _Res>
627 struct __future_base::_Result<_Res&> : __future_base::_Result_base
629 typedef _Res& result_type;
631 _Result() noexcept : _M_value_ptr() { }
634 _M_set(_Res& __res) noexcept
635 { _M_value_ptr = std::addressof(__res); }
637 _Res& _M_get() noexcept { return *_M_value_ptr; }
642 void _M_destroy() { delete this; }
645 /// Explicit specialization for void.
647 struct __future_base::_Result<void> : __future_base::_Result_base
649 typedef void result_type;
652 void _M_destroy() { delete this; }
655 #ifndef _GLIBCXX_ASYNC_ABI_COMPAT
657 // Allow _Setter objects to be stored locally in std::function
658 template<typename _Res, typename _Arg>
659 struct __is_location_invariant
660 <__future_base::_State_base::_Setter<_Res, _Arg>>
663 // Allow _Task_setter objects to be stored locally in std::function
664 template<typename _Res_ptr, typename _Fn, typename _Res>
665 struct __is_location_invariant
666 <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>>
669 /// Common implementation for future and shared_future.
670 template<typename _Res>
671 class __basic_future : public __future_base
674 typedef shared_ptr<_State_base> __state_type;
675 typedef __future_base::_Result<_Res>& __result_type;
678 __state_type _M_state;
682 __basic_future(const __basic_future&) = delete;
683 __basic_future& operator=(const __basic_future&) = delete;
686 valid() const noexcept { return static_cast<bool>(_M_state); }
691 _State_base::_S_check(_M_state);
695 template<typename _Rep, typename _Period>
697 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
699 _State_base::_S_check(_M_state);
700 return _M_state->wait_for(__rel);
703 template<typename _Clock, typename _Duration>
705 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
707 _State_base::_S_check(_M_state);
708 return _M_state->wait_until(__abs);
712 /// Wait for the state to be ready and rethrow any stored exception
714 _M_get_result() const
716 _State_base::_S_check(_M_state);
717 _Result_base& __res = _M_state->wait();
718 if (!(__res._M_error == 0))
719 rethrow_exception(__res._M_error);
720 return static_cast<__result_type>(__res);
723 void _M_swap(__basic_future& __that) noexcept
725 _M_state.swap(__that._M_state);
728 // Construction of a future by promise::get_future()
730 __basic_future(const __state_type& __state) : _M_state(__state)
732 _State_base::_S_check(_M_state);
733 _M_state->_M_set_retrieved_flag();
736 // Copy construction from a shared_future
738 __basic_future(const shared_future<_Res>&) noexcept;
740 // Move construction from a shared_future
742 __basic_future(shared_future<_Res>&&) noexcept;
744 // Move construction from a future
746 __basic_future(future<_Res>&&) noexcept;
748 constexpr __basic_future() noexcept : _M_state() { }
752 explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { }
753 ~_Reset() { _M_fut._M_state.reset(); }
754 __basic_future& _M_fut;
759 /// Primary template for future.
760 template<typename _Res>
761 class future : public __basic_future<_Res>
763 friend class promise<_Res>;
764 template<typename> friend class packaged_task;
765 template<typename _Fn, typename... _Args>
766 friend future<__async_result_of<_Fn, _Args...>>
767 async(launch, _Fn&&, _Args&&...);
769 typedef __basic_future<_Res> _Base_type;
770 typedef typename _Base_type::__state_type __state_type;
773 future(const __state_type& __state) : _Base_type(__state) { }
776 constexpr future() noexcept : _Base_type() { }
779 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
782 future(const future&) = delete;
783 future& operator=(const future&) = delete;
785 future& operator=(future&& __fut) noexcept
787 future(std::move(__fut))._M_swap(*this);
791 /// Retrieving the value
795 typename _Base_type::_Reset __reset(*this);
796 return std::move(this->_M_get_result()._M_value());
799 shared_future<_Res> share() noexcept;
802 /// Partial specialization for future<R&>
803 template<typename _Res>
804 class future<_Res&> : public __basic_future<_Res&>
806 friend class promise<_Res&>;
807 template<typename> friend class packaged_task;
808 template<typename _Fn, typename... _Args>
809 friend future<__async_result_of<_Fn, _Args...>>
810 async(launch, _Fn&&, _Args&&...);
812 typedef __basic_future<_Res&> _Base_type;
813 typedef typename _Base_type::__state_type __state_type;
816 future(const __state_type& __state) : _Base_type(__state) { }
819 constexpr future() noexcept : _Base_type() { }
822 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
825 future(const future&) = delete;
826 future& operator=(const future&) = delete;
828 future& operator=(future&& __fut) noexcept
830 future(std::move(__fut))._M_swap(*this);
834 /// Retrieving the value
838 typename _Base_type::_Reset __reset(*this);
839 return this->_M_get_result()._M_get();
842 shared_future<_Res&> share() noexcept;
845 /// Explicit specialization for future<void>
847 class future<void> : public __basic_future<void>
849 friend class promise<void>;
850 template<typename> friend class packaged_task;
851 template<typename _Fn, typename... _Args>
852 friend future<__async_result_of<_Fn, _Args...>>
853 async(launch, _Fn&&, _Args&&...);
855 typedef __basic_future<void> _Base_type;
856 typedef typename _Base_type::__state_type __state_type;
859 future(const __state_type& __state) : _Base_type(__state) { }
862 constexpr future() noexcept : _Base_type() { }
865 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
868 future(const future&) = delete;
869 future& operator=(const future&) = delete;
871 future& operator=(future&& __fut) noexcept
873 future(std::move(__fut))._M_swap(*this);
877 /// Retrieving the value
881 typename _Base_type::_Reset __reset(*this);
882 this->_M_get_result();
885 shared_future<void> share() noexcept;
889 /// Primary template for shared_future.
890 template<typename _Res>
891 class shared_future : public __basic_future<_Res>
893 typedef __basic_future<_Res> _Base_type;
896 constexpr shared_future() noexcept : _Base_type() { }
899 shared_future(const shared_future& __sf) noexcept : _Base_type(__sf) { }
901 /// Construct from a future rvalue
902 shared_future(future<_Res>&& __uf) noexcept
903 : _Base_type(std::move(__uf))
906 /// Construct from a shared_future rvalue
907 shared_future(shared_future&& __sf) noexcept
908 : _Base_type(std::move(__sf))
911 shared_future& operator=(const shared_future& __sf) noexcept
913 shared_future(__sf)._M_swap(*this);
917 shared_future& operator=(shared_future&& __sf) noexcept
919 shared_future(std::move(__sf))._M_swap(*this);
923 /// Retrieving the value
925 get() const { return this->_M_get_result()._M_value(); }
928 /// Partial specialization for shared_future<R&>
929 template<typename _Res>
930 class shared_future<_Res&> : public __basic_future<_Res&>
932 typedef __basic_future<_Res&> _Base_type;
935 constexpr shared_future() noexcept : _Base_type() { }
938 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
940 /// Construct from a future rvalue
941 shared_future(future<_Res&>&& __uf) noexcept
942 : _Base_type(std::move(__uf))
945 /// Construct from a shared_future rvalue
946 shared_future(shared_future&& __sf) noexcept
947 : _Base_type(std::move(__sf))
950 shared_future& operator=(const shared_future& __sf)
952 shared_future(__sf)._M_swap(*this);
956 shared_future& operator=(shared_future&& __sf) noexcept
958 shared_future(std::move(__sf))._M_swap(*this);
962 /// Retrieving the value
964 get() const { return this->_M_get_result()._M_get(); }
967 /// Explicit specialization for shared_future<void>
969 class shared_future<void> : public __basic_future<void>
971 typedef __basic_future<void> _Base_type;
974 constexpr shared_future() noexcept : _Base_type() { }
977 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
979 /// Construct from a future rvalue
980 shared_future(future<void>&& __uf) noexcept
981 : _Base_type(std::move(__uf))
984 /// Construct from a shared_future rvalue
985 shared_future(shared_future&& __sf) noexcept
986 : _Base_type(std::move(__sf))
989 shared_future& operator=(const shared_future& __sf)
991 shared_future(__sf)._M_swap(*this);
995 shared_future& operator=(shared_future&& __sf) noexcept
997 shared_future(std::move(__sf))._M_swap(*this);
1001 // Retrieving the value
1003 get() const { this->_M_get_result(); }
1006 // Now we can define the protected __basic_future constructors.
1007 template<typename _Res>
1008 inline __basic_future<_Res>::
1009 __basic_future(const shared_future<_Res>& __sf) noexcept
1010 : _M_state(__sf._M_state)
1013 template<typename _Res>
1014 inline __basic_future<_Res>::
1015 __basic_future(shared_future<_Res>&& __sf) noexcept
1016 : _M_state(std::move(__sf._M_state))
1019 template<typename _Res>
1020 inline __basic_future<_Res>::
1021 __basic_future(future<_Res>&& __uf) noexcept
1022 : _M_state(std::move(__uf._M_state))
1025 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1026 // 2556. Wide contract for future::share()
1027 template<typename _Res>
1028 inline shared_future<_Res>
1029 future<_Res>::share() noexcept
1030 { return shared_future<_Res>(std::move(*this)); }
1032 template<typename _Res>
1033 inline shared_future<_Res&>
1034 future<_Res&>::share() noexcept
1035 { return shared_future<_Res&>(std::move(*this)); }
1037 inline shared_future<void>
1038 future<void>::share() noexcept
1039 { return shared_future<void>(std::move(*this)); }
1041 /// Primary template for promise
1042 template<typename _Res>
1045 typedef __future_base::_State_base _State;
1046 typedef __future_base::_Result<_Res> _Res_type;
1047 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1048 template<typename, typename> friend class _State::_Setter;
1051 shared_ptr<_State> _M_future;
1052 _Ptr_type _M_storage;
1056 : _M_future(std::make_shared<_State>()),
1057 _M_storage(new _Res_type())
1060 promise(promise&& __rhs) noexcept
1061 : _M_future(std::move(__rhs._M_future)),
1062 _M_storage(std::move(__rhs._M_storage))
1065 template<typename _Allocator>
1066 promise(allocator_arg_t, const _Allocator& __a)
1067 : _M_future(std::allocate_shared<_State>(__a)),
1068 _M_storage(__future_base::_S_allocate_result<_Res>(__a))
1071 template<typename _Allocator>
1072 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1073 : _M_future(std::move(__rhs._M_future)),
1074 _M_storage(std::move(__rhs._M_storage))
1077 promise(const promise&) = delete;
1081 if (static_cast<bool>(_M_future) && !_M_future.unique())
1082 _M_future->_M_break_promise(std::move(_M_storage));
1087 operator=(promise&& __rhs) noexcept
1089 promise(std::move(__rhs)).swap(*this);
1093 promise& operator=(const promise&) = delete;
1096 swap(promise& __rhs) noexcept
1098 _M_future.swap(__rhs._M_future);
1099 _M_storage.swap(__rhs._M_storage);
1102 // Retrieving the result
1105 { return future<_Res>(_M_future); }
1107 // Setting the result
1109 set_value(const _Res& __r)
1110 { _M_future->_M_set_result(_State::__setter(this, __r)); }
1113 set_value(_Res&& __r)
1114 { _M_future->_M_set_result(_State::__setter(this, std::move(__r))); }
1117 set_exception(exception_ptr __p)
1118 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1121 set_value_at_thread_exit(const _Res& __r)
1123 _M_future->_M_set_delayed_result(_State::__setter(this, __r),
1128 set_value_at_thread_exit(_Res&& __r)
1130 _M_future->_M_set_delayed_result(
1131 _State::__setter(this, std::move(__r)), _M_future);
1135 set_exception_at_thread_exit(exception_ptr __p)
1137 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1142 template<typename _Res>
1144 swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
1147 template<typename _Res, typename _Alloc>
1148 struct uses_allocator<promise<_Res>, _Alloc>
1149 : public true_type { };
1152 /// Partial specialization for promise<R&>
1153 template<typename _Res>
1154 class promise<_Res&>
1156 typedef __future_base::_State_base _State;
1157 typedef __future_base::_Result<_Res&> _Res_type;
1158 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1159 template<typename, typename> friend class _State::_Setter;
1162 shared_ptr<_State> _M_future;
1163 _Ptr_type _M_storage;
1167 : _M_future(std::make_shared<_State>()),
1168 _M_storage(new _Res_type())
1171 promise(promise&& __rhs) noexcept
1172 : _M_future(std::move(__rhs._M_future)),
1173 _M_storage(std::move(__rhs._M_storage))
1176 template<typename _Allocator>
1177 promise(allocator_arg_t, const _Allocator& __a)
1178 : _M_future(std::allocate_shared<_State>(__a)),
1179 _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
1182 template<typename _Allocator>
1183 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1184 : _M_future(std::move(__rhs._M_future)),
1185 _M_storage(std::move(__rhs._M_storage))
1188 promise(const promise&) = delete;
1192 if (static_cast<bool>(_M_future) && !_M_future.unique())
1193 _M_future->_M_break_promise(std::move(_M_storage));
1198 operator=(promise&& __rhs) noexcept
1200 promise(std::move(__rhs)).swap(*this);
1204 promise& operator=(const promise&) = delete;
1207 swap(promise& __rhs) noexcept
1209 _M_future.swap(__rhs._M_future);
1210 _M_storage.swap(__rhs._M_storage);
1213 // Retrieving the result
1216 { return future<_Res&>(_M_future); }
1218 // Setting the result
1220 set_value(_Res& __r)
1221 { _M_future->_M_set_result(_State::__setter(this, __r)); }
1224 set_exception(exception_ptr __p)
1225 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1228 set_value_at_thread_exit(_Res& __r)
1230 _M_future->_M_set_delayed_result(_State::__setter(this, __r),
1235 set_exception_at_thread_exit(exception_ptr __p)
1237 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1242 /// Explicit specialization for promise<void>
1246 typedef __future_base::_State_base _State;
1247 typedef __future_base::_Result<void> _Res_type;
1248 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1249 template<typename, typename> friend class _State::_Setter;
1252 shared_ptr<_State> _M_future;
1253 _Ptr_type _M_storage;
1257 : _M_future(std::make_shared<_State>()),
1258 _M_storage(new _Res_type())
1261 promise(promise&& __rhs) noexcept
1262 : _M_future(std::move(__rhs._M_future)),
1263 _M_storage(std::move(__rhs._M_storage))
1266 template<typename _Allocator>
1267 promise(allocator_arg_t, const _Allocator& __a)
1268 : _M_future(std::allocate_shared<_State>(__a)),
1269 _M_storage(__future_base::_S_allocate_result<void>(__a))
1272 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1273 // 2095. missing constructors needed for uses-allocator construction
1274 template<typename _Allocator>
1275 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1276 : _M_future(std::move(__rhs._M_future)),
1277 _M_storage(std::move(__rhs._M_storage))
1280 promise(const promise&) = delete;
1284 if (static_cast<bool>(_M_future) && !_M_future.unique())
1285 _M_future->_M_break_promise(std::move(_M_storage));
1290 operator=(promise&& __rhs) noexcept
1292 promise(std::move(__rhs)).swap(*this);
1296 promise& operator=(const promise&) = delete;
1299 swap(promise& __rhs) noexcept
1301 _M_future.swap(__rhs._M_future);
1302 _M_storage.swap(__rhs._M_storage);
1305 // Retrieving the result
1308 { return future<void>(_M_future); }
1310 // Setting the result
1313 { _M_future->_M_set_result(_State::__setter(this)); }
1316 set_exception(exception_ptr __p)
1317 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1320 set_value_at_thread_exit()
1321 { _M_future->_M_set_delayed_result(_State::__setter(this), _M_future); }
1324 set_exception_at_thread_exit(exception_ptr __p)
1326 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1331 template<typename _Ptr_type, typename _Fn, typename _Res>
1332 struct __future_base::_Task_setter
1334 // Invoke the function and provide the result to the caller.
1335 _Ptr_type operator()() const
1339 (*_M_result)->_M_set((*_M_fn)());
1341 __catch(const __cxxabiv1::__forced_unwind&)
1343 __throw_exception_again; // will cause broken_promise
1347 (*_M_result)->_M_error = current_exception();
1349 return std::move(*_M_result);
1351 _Ptr_type* _M_result;
1355 template<typename _Ptr_type, typename _Fn>
1356 struct __future_base::_Task_setter<_Ptr_type, _Fn, void>
1358 _Ptr_type operator()() const
1364 __catch(const __cxxabiv1::__forced_unwind&)
1366 __throw_exception_again; // will cause broken_promise
1370 (*_M_result)->_M_error = current_exception();
1372 return std::move(*_M_result);
1374 _Ptr_type* _M_result;
1378 // Holds storage for a packaged_task's result.
1379 template<typename _Res, typename... _Args>
1380 struct __future_base::_Task_state_base<_Res(_Args...)>
1381 : __future_base::_State_base
1383 typedef _Res _Res_type;
1385 template<typename _Alloc>
1386 _Task_state_base(const _Alloc& __a)
1387 : _M_result(_S_allocate_result<_Res>(__a))
1390 // Invoke the stored task and make the state ready.
1392 _M_run(_Args&&... __args) = 0;
1394 // Invoke the stored task and make the state ready at thread exit.
1396 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0;
1398 virtual shared_ptr<_Task_state_base>
1401 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1402 _Ptr_type _M_result;
1405 // Holds a packaged_task's stored task.
1406 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1407 struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final
1408 : __future_base::_Task_state_base<_Res(_Args...)>
1410 template<typename _Fn2>
1411 _Task_state(_Fn2&& __fn, const _Alloc& __a)
1412 : _Task_state_base<_Res(_Args...)>(__a),
1413 _M_impl(std::forward<_Fn2>(__fn), __a)
1418 _M_run(_Args&&... __args)
1420 auto __boundfn = [&] () -> typename result_of<_Fn&(_Args&&...)>::type {
1421 return std::__invoke(_M_impl._M_fn, std::forward<_Args>(__args)...);
1423 this->_M_set_result(_S_task_setter(this->_M_result, __boundfn));
1427 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self)
1429 auto __boundfn = [&] () -> typename result_of<_Fn&(_Args&&...)>::type {
1430 return std::__invoke(_M_impl._M_fn, std::forward<_Args>(__args)...);
1432 this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn),
1436 virtual shared_ptr<_Task_state_base<_Res(_Args...)>>
1439 struct _Impl : _Alloc
1441 template<typename _Fn2>
1442 _Impl(_Fn2&& __fn, const _Alloc& __a)
1443 : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { }
1448 template<typename _Signature, typename _Fn, typename _Alloc>
1449 static shared_ptr<__future_base::_Task_state_base<_Signature>>
1450 __create_task_state(_Fn&& __fn, const _Alloc& __a)
1452 typedef typename decay<_Fn>::type _Fn2;
1453 typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State;
1454 return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a);
1457 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1458 shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>>
1459 __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset()
1461 return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn),
1462 static_cast<_Alloc&>(_M_impl));
1466 template<typename _Res, typename... _ArgTypes>
1467 class packaged_task<_Res(_ArgTypes...)>
1469 typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type;
1470 shared_ptr<_State_type> _M_state;
1472 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1473 // 3039. Unnecessary decay in thread and packaged_task
1474 template<typename _Fn, typename _Fn2 = __remove_cvref_t<_Fn>>
1476 = typename enable_if<!is_same<packaged_task, _Fn2>::value>::type;
1479 // Construction and destruction
1480 packaged_task() noexcept { }
1482 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1483 // 2095. missing constructors needed for uses-allocator construction
1484 template<typename _Allocator>
1485 packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
1488 template<typename _Fn, typename = __not_same<_Fn>>
1490 packaged_task(_Fn&& __fn)
1491 : packaged_task(allocator_arg, std::allocator<int>(),
1492 std::forward<_Fn>(__fn))
1495 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1496 // 2097. packaged_task constructors should be constrained
1497 // 2407. [this constructor should not be] explicit
1498 template<typename _Fn, typename _Alloc, typename = __not_same<_Fn>>
1499 packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn)
1500 : _M_state(__create_task_state<_Res(_ArgTypes...)>(
1501 std::forward<_Fn>(__fn), __a))
1506 if (static_cast<bool>(_M_state) && !_M_state.unique())
1507 _M_state->_M_break_promise(std::move(_M_state->_M_result));
1511 packaged_task(const packaged_task&) = delete;
1512 packaged_task& operator=(const packaged_task&) = delete;
1514 template<typename _Allocator>
1515 packaged_task(allocator_arg_t, const _Allocator&,
1516 const packaged_task&) = delete;
1519 packaged_task(packaged_task&& __other) noexcept
1520 { this->swap(__other); }
1522 template<typename _Allocator>
1523 packaged_task(allocator_arg_t, const _Allocator&,
1524 packaged_task&& __other) noexcept
1525 { this->swap(__other); }
1527 packaged_task& operator=(packaged_task&& __other) noexcept
1529 packaged_task(std::move(__other)).swap(*this);
1534 swap(packaged_task& __other) noexcept
1535 { _M_state.swap(__other._M_state); }
1538 valid() const noexcept
1539 { return static_cast<bool>(_M_state); }
1544 { return future<_Res>(_M_state); }
1548 operator()(_ArgTypes... __args)
1550 __future_base::_State_base::_S_check(_M_state);
1551 _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
1555 make_ready_at_thread_exit(_ArgTypes... __args)
1557 __future_base::_State_base::_S_check(_M_state);
1558 _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state);
1564 __future_base::_State_base::_S_check(_M_state);
1565 packaged_task __tmp;
1566 __tmp._M_state = _M_state;
1567 _M_state = _M_state->_M_reset();
1572 template<typename _Res, typename... _ArgTypes>
1574 swap(packaged_task<_Res(_ArgTypes...)>& __x,
1575 packaged_task<_Res(_ArgTypes...)>& __y) noexcept
1578 template<typename _Res, typename _Alloc>
1579 struct uses_allocator<packaged_task<_Res>, _Alloc>
1580 : public true_type { };
1583 // Shared state created by std::async().
1584 // Holds a deferred function and storage for its result.
1585 template<typename _BoundFn, typename _Res>
1586 class __future_base::_Deferred_state final
1587 : public __future_base::_State_base
1591 _Deferred_state(_BoundFn&& __fn)
1592 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1596 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1597 _Ptr_type _M_result;
1600 // Run the deferred function.
1604 // Multiple threads can call a waiting function on the future and
1605 // reach this point at the same time. The call_once in _M_set_result
1606 // ensures only the first one run the deferred function, stores the
1607 // result in _M_result, swaps that with the base _M_result and makes
1608 // the state ready. Tell _M_set_result to ignore failure so all later
1609 // calls do nothing.
1610 _M_set_result(_S_task_setter(_M_result, _M_fn), true);
1613 // Caller should check whether the state is ready first, because this
1614 // function will return true even after the deferred function has run.
1615 virtual bool _M_is_deferred_future() const { return true; }
1618 // Common functionality hoisted out of the _Async_state_impl template.
1619 class __future_base::_Async_state_commonV2
1620 : public __future_base::_State_base
1623 ~_Async_state_commonV2() = default;
1625 // Make waiting functions block until the thread completes, as if joined.
1627 // This function is used by wait() to satisfy the first requirement below
1628 // and by wait_for() / wait_until() to satisfy the second.
1632 // - a call to a waiting function on an asynchronous return object that
1633 // shares the shared state created by this async call shall block until
1634 // the associated thread has completed, as if joined, or else time out.
1636 // - the associated thread completion synchronizes with the return from
1637 // the first function that successfully detects the ready status of the
1638 // shared state or with the return from the last function that releases
1639 // the shared state, whichever happens first.
1640 virtual void _M_complete_async() { _M_join(); }
1642 void _M_join() { std::call_once(_M_once, &thread::join, &_M_thread); }
1648 // Shared state created by std::async().
1649 // Starts a new thread that runs a function and makes the shared state ready.
1650 template<typename _BoundFn, typename _Res>
1651 class __future_base::_Async_state_impl final
1652 : public __future_base::_Async_state_commonV2
1656 _Async_state_impl(_BoundFn&& __fn)
1657 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1659 _M_thread = std::thread{ [this] {
1662 _M_set_result(_S_task_setter(_M_result, _M_fn));
1664 __catch (const __cxxabiv1::__forced_unwind&)
1666 // make the shared state ready on thread cancellation
1667 if (static_cast<bool>(_M_result))
1668 this->_M_break_promise(std::move(_M_result));
1669 __throw_exception_again;
1674 // Must not destroy _M_result and _M_fn until the thread finishes.
1675 // Call join() directly rather than through _M_join() because no other
1676 // thread can be referring to this state if it is being destroyed.
1677 ~_Async_state_impl() { if (_M_thread.joinable()) _M_thread.join(); }
1680 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1681 _Ptr_type _M_result;
1685 template<typename _BoundFn>
1686 inline std::shared_ptr<__future_base::_State_base>
1687 __future_base::_S_make_deferred_state(_BoundFn&& __fn)
1689 typedef typename remove_reference<_BoundFn>::type __fn_type;
1690 typedef _Deferred_state<__fn_type> __state_type;
1691 return std::make_shared<__state_type>(std::move(__fn));
1694 template<typename _BoundFn>
1695 inline std::shared_ptr<__future_base::_State_base>
1696 __future_base::_S_make_async_state(_BoundFn&& __fn)
1698 typedef typename remove_reference<_BoundFn>::type __fn_type;
1699 typedef _Async_state_impl<__fn_type> __state_type;
1700 return std::make_shared<__state_type>(std::move(__fn));
1705 template<typename _Fn, typename... _Args>
1706 _GLIBCXX_NODISCARD future<__async_result_of<_Fn, _Args...>>
1707 async(launch __policy, _Fn&& __fn, _Args&&... __args)
1709 std::shared_ptr<__future_base::_State_base> __state;
1710 if ((__policy & launch::async) == launch::async)
1714 __state = __future_base::_S_make_async_state(
1715 std::thread::__make_invoker(std::forward<_Fn>(__fn),
1716 std::forward<_Args>(__args)...)
1719 #if __cpp_exceptions
1720 catch(const system_error& __e)
1722 if (__e.code() != errc::resource_unavailable_try_again
1723 || (__policy & launch::deferred) != launch::deferred)
1730 __state = __future_base::_S_make_deferred_state(
1731 std::thread::__make_invoker(std::forward<_Fn>(__fn),
1732 std::forward<_Args>(__args)...));
1734 return future<__async_result_of<_Fn, _Args...>>(__state);
1737 /// async, potential overload
1738 template<typename _Fn, typename... _Args>
1739 _GLIBCXX_NODISCARD inline future<__async_result_of<_Fn, _Args...>>
1740 async(_Fn&& __fn, _Args&&... __args)
1742 return std::async(launch::async|launch::deferred,
1743 std::forward<_Fn>(__fn),
1744 std::forward<_Args>(__args)...);
1747 #endif // _GLIBCXX_ASYNC_ABI_COMPAT
1748 #endif // _GLIBCXX_HAS_GTHREADS
1751 _GLIBCXX_END_NAMESPACE_VERSION
1756 #endif // _GLIBCXX_FUTURE