1 // <future> -*- C++ -*-
3 // Copyright (C) 2009-2015 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>
41 #include <condition_variable>
42 #include <system_error>
44 #include <bits/atomic_futex.h>
45 #include <bits/functexcept.h>
46 #include <bits/unique_ptr.h>
47 #include <bits/shared_ptr.h>
48 #include <bits/uses_allocator.h>
49 #include <bits/allocated_ptr.h>
50 #include <ext/aligned_buffer.h>
52 namespace std _GLIBCXX_VISIBILITY(default)
54 _GLIBCXX_BEGIN_NAMESPACE_VERSION
57 * @defgroup futures Futures
58 * @ingroup concurrency
60 * Classes for futures support.
64 /// Error code for futures
65 enum class future_errc
67 future_already_retrieved = 1,
68 promise_already_satisfied,
75 struct is_error_code_enum<future_errc> : public true_type { };
77 /// Points to a statically-allocated object derived from error_category.
79 future_category() noexcept;
81 /// Overload for make_error_code.
83 make_error_code(future_errc __errc) noexcept
84 { return error_code(static_cast<int>(__errc), future_category()); }
86 /// Overload for make_error_condition.
87 inline error_condition
88 make_error_condition(future_errc __errc) noexcept
89 { return error_condition(static_cast<int>(__errc), future_category()); }
92 * @brief Exception type thrown by futures.
95 class future_error : public logic_error
100 explicit future_error(error_code __ec)
101 : logic_error("std::future_error: " + __ec.message()), _M_code(__ec)
104 virtual ~future_error() noexcept;
107 what() const noexcept;
110 code() const noexcept { return _M_code; }
113 // Forward declarations.
114 template<typename _Res>
117 template<typename _Res>
120 template<typename _Signature>
123 template<typename _Res>
126 /// Launch code for futures
133 constexpr launch operator&(launch __x, launch __y)
135 return static_cast<launch>(
136 static_cast<int>(__x) & static_cast<int>(__y));
139 constexpr launch operator|(launch __x, launch __y)
141 return static_cast<launch>(
142 static_cast<int>(__x) | static_cast<int>(__y));
145 constexpr launch operator^(launch __x, launch __y)
147 return static_cast<launch>(
148 static_cast<int>(__x) ^ static_cast<int>(__y));
151 constexpr launch operator~(launch __x)
152 { return static_cast<launch>(~static_cast<int>(__x)); }
154 inline launch& operator&=(launch& __x, launch __y)
155 { return __x = __x & __y; }
157 inline launch& operator|=(launch& __x, launch __y)
158 { return __x = __x | __y; }
160 inline launch& operator^=(launch& __x, launch __y)
161 { return __x = __x ^ __y; }
163 /// Status code for futures
164 enum class future_status
171 template<typename _Fn, typename... _Args>
172 future<typename result_of<_Fn(_Args...)>::type>
173 async(launch __policy, _Fn&& __fn, _Args&&... __args);
175 template<typename _Fn, typename... _Args>
176 future<typename result_of<_Fn(_Args...)>::type>
177 async(_Fn&& __fn, _Args&&... __args);
179 #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1)
181 /// Base class and enclosing scope.
184 /// Base class for results.
187 exception_ptr _M_error;
189 _Result_base(const _Result_base&) = delete;
190 _Result_base& operator=(const _Result_base&) = delete;
192 // _M_destroy() allows derived classes to control deallocation
193 virtual void _M_destroy() = 0;
197 void operator()(_Result_base* __fr) const { __fr->_M_destroy(); }
202 virtual ~_Result_base();
205 /// A unique_ptr for result objects.
206 template<typename _Res>
207 using _Ptr = unique_ptr<_Res, _Result_base::_Deleter>;
209 /// A result object that has storage for an object of type _Res.
210 template<typename _Res>
211 struct _Result : _Result_base
214 __gnu_cxx::__aligned_buffer<_Res> _M_storage;
218 typedef _Res result_type;
220 _Result() noexcept : _M_initialized() { }
228 // Return lvalue, future will add const or rvalue-reference
230 _M_value() noexcept { return *_M_storage._M_ptr(); }
233 _M_set(const _Res& __res)
235 ::new (_M_storage._M_addr()) _Res(__res);
236 _M_initialized = true;
242 ::new (_M_storage._M_addr()) _Res(std::move(__res));
243 _M_initialized = true;
247 void _M_destroy() { delete this; }
250 /// A result object that uses an allocator.
251 template<typename _Res, typename _Alloc>
252 struct _Result_alloc final : _Result<_Res>, _Alloc
254 using __allocator_type = __alloc_rebind<_Alloc, _Result_alloc>;
257 _Result_alloc(const _Alloc& __a) : _Result<_Res>(), _Alloc(__a)
263 __allocator_type __a(*this);
264 __allocated_ptr<__allocator_type> __guard_ptr{ __a, this };
265 this->~_Result_alloc();
269 // Create a result object that uses an allocator.
270 template<typename _Res, typename _Allocator>
271 static _Ptr<_Result_alloc<_Res, _Allocator>>
272 _S_allocate_result(const _Allocator& __a)
274 using __result_type = _Result_alloc<_Res, _Allocator>;
275 typename __result_type::__allocator_type __a2(__a);
276 auto __guard = std::__allocate_guarded(__a2);
277 __result_type* __p = ::new((void*)__guard.get()) __result_type{__a};
279 return _Ptr<__result_type>(__p);
282 // Keep it simple for std::allocator.
283 template<typename _Res, typename _Tp>
284 static _Ptr<_Result<_Res>>
285 _S_allocate_result(const std::allocator<_Tp>& __a)
287 return _Ptr<_Result<_Res>>(new _Result<_Res>);
290 // Base class for various types of shared state created by an
291 // asynchronous provider (such as a std::promise) and shared with one
292 // or more associated futures.
295 typedef _Ptr<_Result_base> _Ptr_type;
297 enum _Status : unsigned {
303 __atomic_futex_unsigned<> _M_status;
304 atomic_flag _M_retrieved = ATOMIC_FLAG_INIT;
308 _State_baseV2() noexcept : _M_result(), _M_status(_Status::__not_ready)
310 _State_baseV2(const _State_baseV2&) = delete;
311 _State_baseV2& operator=(const _State_baseV2&) = delete;
312 virtual ~_State_baseV2() = default;
317 // Run any deferred function or join any asynchronous thread:
319 // Acquire MO makes sure this synchronizes with the thread that made
321 _M_status._M_load_when_equal(_Status::__ready, memory_order_acquire);
325 template<typename _Rep, typename _Period>
327 wait_for(const chrono::duration<_Rep, _Period>& __rel)
329 // First, check if the future has been made ready. Use acquire MO
330 // to synchronize with the thread that made it ready.
331 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
332 return future_status::ready;
333 if (_M_is_deferred_future())
334 return future_status::deferred;
335 if (_M_status._M_load_when_equal_for(_Status::__ready,
336 memory_order_acquire, __rel))
338 // _GLIBCXX_RESOLVE_LIB_DEFECTS
339 // 2100. timed waiting functions must also join
340 // This call is a no-op by default except on an async future,
341 // in which case the async thread is joined. It's also not a
342 // no-op for a deferred future, but such a future will never
343 // reach this point because it returns future_status::deferred
344 // instead of waiting for the future to become ready (see
345 // above). Async futures synchronize in this call, so we need
346 // no further synchronization here.
349 return future_status::ready;
351 return future_status::timeout;
354 template<typename _Clock, typename _Duration>
356 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
358 // First, check if the future has been made ready. Use acquire MO
359 // to synchronize with the thread that made it ready.
360 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
361 return future_status::ready;
362 if (_M_is_deferred_future())
363 return future_status::deferred;
364 if (_M_status._M_load_when_equal_until(_Status::__ready,
365 memory_order_acquire, __abs))
367 // _GLIBCXX_RESOLVE_LIB_DEFECTS
368 // 2100. timed waiting functions must also join
369 // See wait_for(...) above.
372 return future_status::ready;
374 return future_status::timeout;
377 // Provide a result to the shared state and make it ready.
378 // Calls at most once: _M_result = __res();
380 _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
382 bool __did_set = false;
383 // all calls to this function are serialized,
384 // side-effects of invoking __res only happen once
385 call_once(_M_once, &_State_baseV2::_M_do_set, this,
386 std::__addressof(__res), std::__addressof(__did_set));
388 // Use release MO to synchronize with observers of the ready state.
389 _M_status._M_store_notify_all(_Status::__ready,
390 memory_order_release);
391 else if (!__ignore_failure)
392 __throw_future_error(int(future_errc::promise_already_satisfied));
395 // Provide a result to the shared state but delay making it ready
396 // until the calling thread exits.
397 // Calls at most once: _M_result = __res();
399 _M_set_delayed_result(function<_Ptr_type()> __res,
400 weak_ptr<_State_baseV2> __self)
402 bool __did_set = false;
403 unique_ptr<_Make_ready> __mr{new _Make_ready};
404 // all calls to this function are serialized,
405 // side-effects of invoking __res only happen once
406 call_once(_M_once, &_State_baseV2::_M_do_set, this,
407 std::__addressof(__res), std::__addressof(__did_set));
409 __throw_future_error(int(future_errc::promise_already_satisfied));
410 __mr->_M_shared_state = std::move(__self);
415 // Abandon this shared state.
417 _M_break_promise(_Ptr_type __res)
419 if (static_cast<bool>(__res))
421 error_code __ec(make_error_code(future_errc::broken_promise));
422 __res->_M_error = make_exception_ptr(future_error(__ec));
423 // This function is only called when the last asynchronous result
424 // provider is abandoning this shared state, so noone can be
425 // trying to make the shared state ready at the same time, and
426 // we can access _M_result directly instead of through call_once.
427 _M_result.swap(__res);
428 // Use release MO to synchronize with observers of the ready state.
429 _M_status._M_store_notify_all(_Status::__ready,
430 memory_order_release);
434 // Called when this object is first passed to a future.
436 _M_set_retrieved_flag()
438 if (_M_retrieved.test_and_set())
439 __throw_future_error(int(future_errc::future_already_retrieved));
442 template<typename _Res, typename _Arg>
446 template<typename _Res, typename _Arg>
447 struct _Setter<_Res, _Arg&>
449 // check this is only used by promise<R>::set_value(const R&)
450 // or promise<R&>::set_value(R&)
451 static_assert(is_same<_Res, _Arg&>::value // promise<R&>
452 || is_same<const _Res, _Arg>::value, // promise<R>
453 "Invalid specialisation");
455 // Used by std::promise to copy construct the result.
456 typename promise<_Res>::_Ptr_type operator()() const
458 _State_baseV2::_S_check(_M_promise->_M_future);
459 _M_promise->_M_storage->_M_set(*_M_arg);
460 return std::move(_M_promise->_M_storage);
462 promise<_Res>* _M_promise;
467 template<typename _Res>
468 struct _Setter<_Res, _Res&&>
470 // Used by std::promise to move construct the result.
471 typename promise<_Res>::_Ptr_type operator()() const
473 _State_baseV2::_S_check(_M_promise->_M_future);
474 _M_promise->_M_storage->_M_set(std::move(*_M_arg));
475 return std::move(_M_promise->_M_storage);
477 promise<_Res>* _M_promise;
481 struct __exception_ptr_tag { };
484 template<typename _Res>
485 struct _Setter<_Res, __exception_ptr_tag>
487 // Used by std::promise to store an exception as the result.
488 typename promise<_Res>::_Ptr_type operator()() const
490 _State_baseV2::_S_check(_M_promise->_M_future);
491 _M_promise->_M_storage->_M_error = *_M_ex;
492 return std::move(_M_promise->_M_storage);
495 promise<_Res>* _M_promise;
496 exception_ptr* _M_ex;
499 template<typename _Res, typename _Arg>
500 static _Setter<_Res, _Arg&&>
501 __setter(promise<_Res>* __prom, _Arg&& __arg)
503 return _Setter<_Res, _Arg&&>{ __prom, &__arg };
506 template<typename _Res>
507 static _Setter<_Res, __exception_ptr_tag>
508 __setter(exception_ptr& __ex, promise<_Res>* __prom)
510 return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex };
513 template<typename _Tp>
515 _S_check(const shared_ptr<_Tp>& __p)
517 if (!static_cast<bool>(__p))
518 __throw_future_error((int)future_errc::no_state);
522 // The function invoked with std::call_once(_M_once, ...).
524 _M_do_set(function<_Ptr_type()>* __f, bool* __did_set)
526 _Ptr_type __res = (*__f)();
527 // Notify the caller that we did try to set; if we do not throw an
528 // exception, the caller will be aware that it did set (e.g., see
531 _M_result.swap(__res); // nothrow
534 // Wait for completion of async function.
535 virtual void _M_complete_async() { }
537 // Return true if state corresponds to a deferred function.
538 virtual bool _M_is_deferred_future() const { return false; }
540 struct _Make_ready final : __at_thread_exit_elt
542 weak_ptr<_State_baseV2> _M_shared_state;
543 static void _S_run(void*);
548 #ifdef _GLIBCXX_ASYNC_ABI_COMPAT
550 class _Async_state_common;
552 using _State_base = _State_baseV2;
553 class _Async_state_commonV2;
556 template<typename _BoundFn, typename = typename _BoundFn::result_type>
557 class _Deferred_state;
559 template<typename _BoundFn, typename = typename _BoundFn::result_type>
560 class _Async_state_impl;
562 template<typename _Signature>
563 class _Task_state_base;
565 template<typename _Fn, typename _Alloc, typename _Signature>
568 template<typename _BoundFn>
569 static std::shared_ptr<_State_base>
570 _S_make_deferred_state(_BoundFn&& __fn);
572 template<typename _BoundFn>
573 static std::shared_ptr<_State_base>
574 _S_make_async_state(_BoundFn&& __fn);
576 template<typename _Res_ptr, typename _Fn,
577 typename _Res = typename _Res_ptr::element_type::result_type>
580 template<typename _Res_ptr, typename _BoundFn>
581 static _Task_setter<_Res_ptr, _BoundFn>
582 _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call)
584 return { std::__addressof(__ptr), std::__addressof(__call) };
588 /// Partial specialization for reference types.
589 template<typename _Res>
590 struct __future_base::_Result<_Res&> : __future_base::_Result_base
592 typedef _Res& result_type;
594 _Result() noexcept : _M_value_ptr() { }
597 _M_set(_Res& __res) noexcept
598 { _M_value_ptr = std::addressof(__res); }
600 _Res& _M_get() noexcept { return *_M_value_ptr; }
605 void _M_destroy() { delete this; }
608 /// Explicit specialization for void.
610 struct __future_base::_Result<void> : __future_base::_Result_base
612 typedef void result_type;
615 void _M_destroy() { delete this; }
618 #ifndef _GLIBCXX_ASYNC_ABI_COMPAT
620 // Allow _Setter objects to be stored locally in std::function
621 template<typename _Res, typename _Arg>
622 struct __is_location_invariant
623 <__future_base::_State_base::_Setter<_Res, _Arg>>
626 // Allow _Task_setter objects to be stored locally in std::function
627 template<typename _Res_ptr, typename _Fn, typename _Res>
628 struct __is_location_invariant
629 <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>>
632 /// Common implementation for future and shared_future.
633 template<typename _Res>
634 class __basic_future : public __future_base
637 typedef shared_ptr<_State_base> __state_type;
638 typedef __future_base::_Result<_Res>& __result_type;
641 __state_type _M_state;
645 __basic_future(const __basic_future&) = delete;
646 __basic_future& operator=(const __basic_future&) = delete;
649 valid() const noexcept { return static_cast<bool>(_M_state); }
654 _State_base::_S_check(_M_state);
658 template<typename _Rep, typename _Period>
660 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
662 _State_base::_S_check(_M_state);
663 return _M_state->wait_for(__rel);
666 template<typename _Clock, typename _Duration>
668 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
670 _State_base::_S_check(_M_state);
671 return _M_state->wait_until(__abs);
675 /// Wait for the state to be ready and rethrow any stored exception
677 _M_get_result() const
679 _State_base::_S_check(_M_state);
680 _Result_base& __res = _M_state->wait();
681 if (!(__res._M_error == 0))
682 rethrow_exception(__res._M_error);
683 return static_cast<__result_type>(__res);
686 void _M_swap(__basic_future& __that) noexcept
688 _M_state.swap(__that._M_state);
691 // Construction of a future by promise::get_future()
693 __basic_future(const __state_type& __state) : _M_state(__state)
695 _State_base::_S_check(_M_state);
696 _M_state->_M_set_retrieved_flag();
699 // Copy construction from a shared_future
701 __basic_future(const shared_future<_Res>&) noexcept;
703 // Move construction from a shared_future
705 __basic_future(shared_future<_Res>&&) noexcept;
707 // Move construction from a future
709 __basic_future(future<_Res>&&) noexcept;
711 constexpr __basic_future() noexcept : _M_state() { }
715 explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { }
716 ~_Reset() { _M_fut._M_state.reset(); }
717 __basic_future& _M_fut;
722 /// Primary template for future.
723 template<typename _Res>
724 class future : public __basic_future<_Res>
726 friend class promise<_Res>;
727 template<typename> friend class packaged_task;
728 template<typename _Fn, typename... _Args>
729 friend future<typename result_of<_Fn(_Args...)>::type>
730 async(launch, _Fn&&, _Args&&...);
732 typedef __basic_future<_Res> _Base_type;
733 typedef typename _Base_type::__state_type __state_type;
736 future(const __state_type& __state) : _Base_type(__state) { }
739 constexpr future() noexcept : _Base_type() { }
742 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
745 future(const future&) = delete;
746 future& operator=(const future&) = delete;
748 future& operator=(future&& __fut) noexcept
750 future(std::move(__fut))._M_swap(*this);
754 /// Retrieving the value
758 typename _Base_type::_Reset __reset(*this);
759 return std::move(this->_M_get_result()._M_value());
762 shared_future<_Res> share();
765 /// Partial specialization for future<R&>
766 template<typename _Res>
767 class future<_Res&> : public __basic_future<_Res&>
769 friend class promise<_Res&>;
770 template<typename> friend class packaged_task;
771 template<typename _Fn, typename... _Args>
772 friend future<typename result_of<_Fn(_Args...)>::type>
773 async(launch, _Fn&&, _Args&&...);
775 typedef __basic_future<_Res&> _Base_type;
776 typedef typename _Base_type::__state_type __state_type;
779 future(const __state_type& __state) : _Base_type(__state) { }
782 constexpr future() noexcept : _Base_type() { }
785 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
788 future(const future&) = delete;
789 future& operator=(const future&) = delete;
791 future& operator=(future&& __fut) noexcept
793 future(std::move(__fut))._M_swap(*this);
797 /// Retrieving the value
801 typename _Base_type::_Reset __reset(*this);
802 return this->_M_get_result()._M_get();
805 shared_future<_Res&> share();
808 /// Explicit specialization for future<void>
810 class future<void> : public __basic_future<void>
812 friend class promise<void>;
813 template<typename> friend class packaged_task;
814 template<typename _Fn, typename... _Args>
815 friend future<typename result_of<_Fn(_Args...)>::type>
816 async(launch, _Fn&&, _Args&&...);
818 typedef __basic_future<void> _Base_type;
819 typedef typename _Base_type::__state_type __state_type;
822 future(const __state_type& __state) : _Base_type(__state) { }
825 constexpr future() noexcept : _Base_type() { }
828 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
831 future(const future&) = delete;
832 future& operator=(const future&) = delete;
834 future& operator=(future&& __fut) noexcept
836 future(std::move(__fut))._M_swap(*this);
840 /// Retrieving the value
844 typename _Base_type::_Reset __reset(*this);
845 this->_M_get_result();
848 shared_future<void> share();
852 /// Primary template for shared_future.
853 template<typename _Res>
854 class shared_future : public __basic_future<_Res>
856 typedef __basic_future<_Res> _Base_type;
859 constexpr shared_future() noexcept : _Base_type() { }
862 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
864 /// Construct from a future rvalue
865 shared_future(future<_Res>&& __uf) noexcept
866 : _Base_type(std::move(__uf))
869 /// Construct from a shared_future rvalue
870 shared_future(shared_future&& __sf) noexcept
871 : _Base_type(std::move(__sf))
874 shared_future& operator=(const shared_future& __sf)
876 shared_future(__sf)._M_swap(*this);
880 shared_future& operator=(shared_future&& __sf) noexcept
882 shared_future(std::move(__sf))._M_swap(*this);
886 /// Retrieving the value
888 get() const { return this->_M_get_result()._M_value(); }
891 /// Partial specialization for shared_future<R&>
892 template<typename _Res>
893 class shared_future<_Res&> : public __basic_future<_Res&>
895 typedef __basic_future<_Res&> _Base_type;
898 constexpr shared_future() noexcept : _Base_type() { }
901 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
903 /// Construct from a future rvalue
904 shared_future(future<_Res&>&& __uf) noexcept
905 : _Base_type(std::move(__uf))
908 /// Construct from a shared_future rvalue
909 shared_future(shared_future&& __sf) noexcept
910 : _Base_type(std::move(__sf))
913 shared_future& operator=(const shared_future& __sf)
915 shared_future(__sf)._M_swap(*this);
919 shared_future& operator=(shared_future&& __sf) noexcept
921 shared_future(std::move(__sf))._M_swap(*this);
925 /// Retrieving the value
927 get() const { return this->_M_get_result()._M_get(); }
930 /// Explicit specialization for shared_future<void>
932 class shared_future<void> : public __basic_future<void>
934 typedef __basic_future<void> _Base_type;
937 constexpr shared_future() noexcept : _Base_type() { }
940 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
942 /// Construct from a future rvalue
943 shared_future(future<void>&& __uf) noexcept
944 : _Base_type(std::move(__uf))
947 /// Construct from a shared_future rvalue
948 shared_future(shared_future&& __sf) noexcept
949 : _Base_type(std::move(__sf))
952 shared_future& operator=(const shared_future& __sf)
954 shared_future(__sf)._M_swap(*this);
958 shared_future& operator=(shared_future&& __sf) noexcept
960 shared_future(std::move(__sf))._M_swap(*this);
964 // Retrieving the value
966 get() const { this->_M_get_result(); }
969 // Now we can define the protected __basic_future constructors.
970 template<typename _Res>
971 inline __basic_future<_Res>::
972 __basic_future(const shared_future<_Res>& __sf) noexcept
973 : _M_state(__sf._M_state)
976 template<typename _Res>
977 inline __basic_future<_Res>::
978 __basic_future(shared_future<_Res>&& __sf) noexcept
979 : _M_state(std::move(__sf._M_state))
982 template<typename _Res>
983 inline __basic_future<_Res>::
984 __basic_future(future<_Res>&& __uf) noexcept
985 : _M_state(std::move(__uf._M_state))
988 template<typename _Res>
989 inline shared_future<_Res>
990 future<_Res>::share()
991 { return shared_future<_Res>(std::move(*this)); }
993 template<typename _Res>
994 inline shared_future<_Res&>
995 future<_Res&>::share()
996 { return shared_future<_Res&>(std::move(*this)); }
998 inline shared_future<void>
999 future<void>::share()
1000 { return shared_future<void>(std::move(*this)); }
1002 /// Primary template for promise
1003 template<typename _Res>
1006 typedef __future_base::_State_base _State;
1007 typedef __future_base::_Result<_Res> _Res_type;
1008 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1009 template<typename, typename> friend class _State::_Setter;
1011 shared_ptr<_State> _M_future;
1012 _Ptr_type _M_storage;
1016 : _M_future(std::make_shared<_State>()),
1017 _M_storage(new _Res_type())
1020 promise(promise&& __rhs) noexcept
1021 : _M_future(std::move(__rhs._M_future)),
1022 _M_storage(std::move(__rhs._M_storage))
1025 template<typename _Allocator>
1026 promise(allocator_arg_t, const _Allocator& __a)
1027 : _M_future(std::allocate_shared<_State>(__a)),
1028 _M_storage(__future_base::_S_allocate_result<_Res>(__a))
1031 template<typename _Allocator>
1032 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1033 : _M_future(std::move(__rhs._M_future)),
1034 _M_storage(std::move(__rhs._M_storage))
1037 promise(const promise&) = delete;
1041 if (static_cast<bool>(_M_future) && !_M_future.unique())
1042 _M_future->_M_break_promise(std::move(_M_storage));
1047 operator=(promise&& __rhs) noexcept
1049 promise(std::move(__rhs)).swap(*this);
1053 promise& operator=(const promise&) = delete;
1056 swap(promise& __rhs) noexcept
1058 _M_future.swap(__rhs._M_future);
1059 _M_storage.swap(__rhs._M_storage);
1062 // Retrieving the result
1065 { return future<_Res>(_M_future); }
1067 // Setting the result
1069 set_value(const _Res& __r)
1070 { _M_future->_M_set_result(_State::__setter(this, __r)); }
1073 set_value(_Res&& __r)
1074 { _M_future->_M_set_result(_State::__setter(this, std::move(__r))); }
1077 set_exception(exception_ptr __p)
1078 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1081 set_value_at_thread_exit(const _Res& __r)
1083 _M_future->_M_set_delayed_result(_State::__setter(this, __r),
1088 set_value_at_thread_exit(_Res&& __r)
1090 _M_future->_M_set_delayed_result(
1091 _State::__setter(this, std::move(__r)), _M_future);
1095 set_exception_at_thread_exit(exception_ptr __p)
1097 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1102 template<typename _Res>
1104 swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
1107 template<typename _Res, typename _Alloc>
1108 struct uses_allocator<promise<_Res>, _Alloc>
1109 : public true_type { };
1112 /// Partial specialization for promise<R&>
1113 template<typename _Res>
1114 class promise<_Res&>
1116 typedef __future_base::_State_base _State;
1117 typedef __future_base::_Result<_Res&> _Res_type;
1118 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1119 template<typename, typename> friend class _State::_Setter;
1121 shared_ptr<_State> _M_future;
1122 _Ptr_type _M_storage;
1126 : _M_future(std::make_shared<_State>()),
1127 _M_storage(new _Res_type())
1130 promise(promise&& __rhs) noexcept
1131 : _M_future(std::move(__rhs._M_future)),
1132 _M_storage(std::move(__rhs._M_storage))
1135 template<typename _Allocator>
1136 promise(allocator_arg_t, const _Allocator& __a)
1137 : _M_future(std::allocate_shared<_State>(__a)),
1138 _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
1141 template<typename _Allocator>
1142 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1143 : _M_future(std::move(__rhs._M_future)),
1144 _M_storage(std::move(__rhs._M_storage))
1147 promise(const promise&) = delete;
1151 if (static_cast<bool>(_M_future) && !_M_future.unique())
1152 _M_future->_M_break_promise(std::move(_M_storage));
1157 operator=(promise&& __rhs) noexcept
1159 promise(std::move(__rhs)).swap(*this);
1163 promise& operator=(const promise&) = delete;
1166 swap(promise& __rhs) noexcept
1168 _M_future.swap(__rhs._M_future);
1169 _M_storage.swap(__rhs._M_storage);
1172 // Retrieving the result
1175 { return future<_Res&>(_M_future); }
1177 // Setting the result
1179 set_value(_Res& __r)
1180 { _M_future->_M_set_result(_State::__setter(this, __r)); }
1183 set_exception(exception_ptr __p)
1184 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1187 set_value_at_thread_exit(_Res& __r)
1189 _M_future->_M_set_delayed_result(_State::__setter(this, __r),
1194 set_exception_at_thread_exit(exception_ptr __p)
1196 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1201 /// Explicit specialization for promise<void>
1205 typedef __future_base::_State_base _State;
1206 typedef __future_base::_Result<void> _Res_type;
1207 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1208 template<typename, typename> friend class _State::_Setter;
1210 shared_ptr<_State> _M_future;
1211 _Ptr_type _M_storage;
1215 : _M_future(std::make_shared<_State>()),
1216 _M_storage(new _Res_type())
1219 promise(promise&& __rhs) noexcept
1220 : _M_future(std::move(__rhs._M_future)),
1221 _M_storage(std::move(__rhs._M_storage))
1224 template<typename _Allocator>
1225 promise(allocator_arg_t, const _Allocator& __a)
1226 : _M_future(std::allocate_shared<_State>(__a)),
1227 _M_storage(__future_base::_S_allocate_result<void>(__a))
1230 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1231 // 2095. missing constructors needed for uses-allocator construction
1232 template<typename _Allocator>
1233 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1234 : _M_future(std::move(__rhs._M_future)),
1235 _M_storage(std::move(__rhs._M_storage))
1238 promise(const promise&) = delete;
1242 if (static_cast<bool>(_M_future) && !_M_future.unique())
1243 _M_future->_M_break_promise(std::move(_M_storage));
1248 operator=(promise&& __rhs) noexcept
1250 promise(std::move(__rhs)).swap(*this);
1254 promise& operator=(const promise&) = delete;
1257 swap(promise& __rhs) noexcept
1259 _M_future.swap(__rhs._M_future);
1260 _M_storage.swap(__rhs._M_storage);
1263 // Retrieving the result
1266 { return future<void>(_M_future); }
1268 // Setting the result
1272 set_exception(exception_ptr __p)
1273 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1276 set_value_at_thread_exit();
1279 set_exception_at_thread_exit(exception_ptr __p)
1281 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1288 struct __future_base::_State_base::_Setter<void, void>
1290 promise<void>::_Ptr_type operator()() const
1292 _State_base::_S_check(_M_promise->_M_future);
1293 return std::move(_M_promise->_M_storage);
1296 promise<void>* _M_promise;
1300 promise<void>::set_value()
1301 { _M_future->_M_set_result(_State::_Setter<void, void>{ this }); }
1304 promise<void>::set_value_at_thread_exit()
1306 _M_future->_M_set_delayed_result(_State::_Setter<void, void>{this},
1310 template<typename _Ptr_type, typename _Fn, typename _Res>
1311 struct __future_base::_Task_setter
1313 // Invoke the function and provide the result to the caller.
1314 _Ptr_type operator()() const
1318 (*_M_result)->_M_set((*_M_fn)());
1320 __catch(const __cxxabiv1::__forced_unwind&)
1322 __throw_exception_again; // will cause broken_promise
1326 (*_M_result)->_M_error = current_exception();
1328 return std::move(*_M_result);
1330 _Ptr_type* _M_result;
1334 template<typename _Ptr_type, typename _Fn>
1335 struct __future_base::_Task_setter<_Ptr_type, _Fn, void>
1337 _Ptr_type operator()() const
1343 __catch(const __cxxabiv1::__forced_unwind&)
1345 __throw_exception_again; // will cause broken_promise
1349 (*_M_result)->_M_error = current_exception();
1351 return std::move(*_M_result);
1353 _Ptr_type* _M_result;
1357 // Holds storage for a packaged_task's result.
1358 template<typename _Res, typename... _Args>
1359 struct __future_base::_Task_state_base<_Res(_Args...)>
1360 : __future_base::_State_base
1362 typedef _Res _Res_type;
1364 template<typename _Alloc>
1365 _Task_state_base(const _Alloc& __a)
1366 : _M_result(_S_allocate_result<_Res>(__a))
1369 // Invoke the stored task and make the state ready.
1371 _M_run(_Args&&... __args) = 0;
1373 // Invoke the stored task and make the state ready at thread exit.
1375 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0;
1377 virtual shared_ptr<_Task_state_base>
1380 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1381 _Ptr_type _M_result;
1384 // Holds a packaged_task's stored task.
1385 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1386 struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final
1387 : __future_base::_Task_state_base<_Res(_Args...)>
1389 template<typename _Fn2>
1390 _Task_state(_Fn2&& __fn, const _Alloc& __a)
1391 : _Task_state_base<_Res(_Args...)>(__a),
1392 _M_impl(std::forward<_Fn2>(__fn), __a)
1397 _M_run(_Args&&... __args)
1399 // bound arguments decay so wrap lvalue references
1400 auto __boundfn = std::__bind_simple(std::ref(_M_impl._M_fn),
1401 _S_maybe_wrap_ref(std::forward<_Args>(__args))...);
1402 this->_M_set_result(_S_task_setter(this->_M_result, __boundfn));
1406 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self)
1408 // bound arguments decay so wrap lvalue references
1409 auto __boundfn = std::__bind_simple(std::ref(_M_impl._M_fn),
1410 _S_maybe_wrap_ref(std::forward<_Args>(__args))...);
1411 this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn),
1415 virtual shared_ptr<_Task_state_base<_Res(_Args...)>>
1418 template<typename _Tp>
1419 static reference_wrapper<_Tp>
1420 _S_maybe_wrap_ref(_Tp& __t)
1421 { return std::ref(__t); }
1423 template<typename _Tp>
1425 typename enable_if<!is_lvalue_reference<_Tp>::value, _Tp>::type&&
1426 _S_maybe_wrap_ref(_Tp&& __t)
1427 { return std::forward<_Tp>(__t); }
1429 struct _Impl : _Alloc
1431 template<typename _Fn2>
1432 _Impl(_Fn2&& __fn, const _Alloc& __a)
1433 : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { }
1438 template<typename _Signature, typename _Fn, typename _Alloc>
1439 static shared_ptr<__future_base::_Task_state_base<_Signature>>
1440 __create_task_state(_Fn&& __fn, const _Alloc& __a)
1442 typedef typename decay<_Fn>::type _Fn2;
1443 typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State;
1444 return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a);
1447 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1448 shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>>
1449 __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset()
1451 return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn),
1452 static_cast<_Alloc&>(_M_impl));
1455 template<typename _Task, typename _Fn, bool
1456 = is_same<_Task, typename decay<_Fn>::type>::value>
1457 struct __constrain_pkgdtask
1458 { typedef void __type; };
1460 template<typename _Task, typename _Fn>
1461 struct __constrain_pkgdtask<_Task, _Fn, true>
1465 template<typename _Res, typename... _ArgTypes>
1466 class packaged_task<_Res(_ArgTypes...)>
1468 typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type;
1469 shared_ptr<_State_type> _M_state;
1472 // Construction and destruction
1473 packaged_task() noexcept { }
1475 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1476 // 2095. missing constructors needed for uses-allocator construction
1477 template<typename _Allocator>
1478 packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
1481 template<typename _Fn, typename = typename
1482 __constrain_pkgdtask<packaged_task, _Fn>::__type>
1484 packaged_task(_Fn&& __fn)
1485 : packaged_task(allocator_arg, std::allocator<int>(),
1486 std::forward<_Fn>(__fn))
1489 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1490 // 2097. packaged_task constructors should be constrained
1491 template<typename _Fn, typename _Alloc, typename = typename
1492 __constrain_pkgdtask<packaged_task, _Fn>::__type>
1494 packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn)
1495 : _M_state(__create_task_state<_Res(_ArgTypes...)>(
1496 std::forward<_Fn>(__fn), __a))
1501 if (static_cast<bool>(_M_state) && !_M_state.unique())
1502 _M_state->_M_break_promise(std::move(_M_state->_M_result));
1506 packaged_task(const packaged_task&) = delete;
1507 packaged_task& operator=(const packaged_task&) = delete;
1509 template<typename _Allocator>
1510 packaged_task(allocator_arg_t, const _Allocator&,
1511 const packaged_task&) = delete;
1514 packaged_task(packaged_task&& __other) noexcept
1515 { this->swap(__other); }
1517 template<typename _Allocator>
1518 packaged_task(allocator_arg_t, const _Allocator&,
1519 packaged_task&& __other) noexcept
1520 { this->swap(__other); }
1522 packaged_task& operator=(packaged_task&& __other) noexcept
1524 packaged_task(std::move(__other)).swap(*this);
1529 swap(packaged_task& __other) noexcept
1530 { _M_state.swap(__other._M_state); }
1533 valid() const noexcept
1534 { return static_cast<bool>(_M_state); }
1539 { return future<_Res>(_M_state); }
1543 operator()(_ArgTypes... __args)
1545 __future_base::_State_base::_S_check(_M_state);
1546 _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
1550 make_ready_at_thread_exit(_ArgTypes... __args)
1552 __future_base::_State_base::_S_check(_M_state);
1553 _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state);
1559 __future_base::_State_base::_S_check(_M_state);
1560 packaged_task __tmp;
1561 __tmp._M_state = _M_state;
1562 _M_state = _M_state->_M_reset();
1567 template<typename _Res, typename... _ArgTypes>
1569 swap(packaged_task<_Res(_ArgTypes...)>& __x,
1570 packaged_task<_Res(_ArgTypes...)>& __y) noexcept
1573 template<typename _Res, typename _Alloc>
1574 struct uses_allocator<packaged_task<_Res>, _Alloc>
1575 : public true_type { };
1578 // Shared state created by std::async().
1579 // Holds a deferred function and storage for its result.
1580 template<typename _BoundFn, typename _Res>
1581 class __future_base::_Deferred_state final
1582 : public __future_base::_State_base
1586 _Deferred_state(_BoundFn&& __fn)
1587 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1591 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1592 _Ptr_type _M_result;
1595 // Run the deferred function.
1599 // Multiple threads can call a waiting function on the future and
1600 // reach this point at the same time. The call_once in _M_set_result
1601 // ensures only the first one run the deferred function, stores the
1602 // result in _M_result, swaps that with the base _M_result and makes
1603 // the state ready. Tell _M_set_result to ignore failure so all later
1604 // calls do nothing.
1605 _M_set_result(_S_task_setter(_M_result, _M_fn), true);
1608 // Caller should check whether the state is ready first, because this
1609 // function will return true even after the deferred function has run.
1610 virtual bool _M_is_deferred_future() const { return true; }
1613 // Common functionality hoisted out of the _Async_state_impl template.
1614 class __future_base::_Async_state_commonV2
1615 : public __future_base::_State_base
1618 ~_Async_state_commonV2() = default;
1620 // Make waiting functions block until the thread completes, as if joined.
1622 // This function is used by wait() to satisfy the first requirement below
1623 // and by wait_for() / wait_until() to satisfy the second.
1627 // — a call to a waiting function on an asynchronous return object that
1628 // shares the shared state created by this async call shall block until
1629 // the associated thread has completed, as if joined, or else time out.
1631 // — the associated thread completion synchronizes with the return from
1632 // the first function that successfully detects the ready status of the
1633 // shared state or with the return from the last function that releases
1634 // the shared state, whichever happens first.
1635 virtual void _M_complete_async() { _M_join(); }
1637 void _M_join() { std::call_once(_M_once, &thread::join, ref(_M_thread)); }
1643 // Shared state created by std::async().
1644 // Starts a new thread that runs a function and makes the shared state ready.
1645 template<typename _BoundFn, typename _Res>
1646 class __future_base::_Async_state_impl final
1647 : public __future_base::_Async_state_commonV2
1651 _Async_state_impl(_BoundFn&& __fn)
1652 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1654 _M_thread = std::thread{ [this] {
1657 _M_set_result(_S_task_setter(_M_result, _M_fn));
1659 __catch (const __cxxabiv1::__forced_unwind&)
1661 // make the shared state ready on thread cancellation
1662 if (static_cast<bool>(_M_result))
1663 this->_M_break_promise(std::move(_M_result));
1664 __throw_exception_again;
1669 // Must not destroy _M_result and _M_fn until the thread finishes.
1670 // Call join() directly rather than through _M_join() because no other
1671 // thread can be referring to this state if it is being destroyed.
1672 ~_Async_state_impl() { if (_M_thread.joinable()) _M_thread.join(); }
1675 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1676 _Ptr_type _M_result;
1680 template<typename _BoundFn>
1681 inline std::shared_ptr<__future_base::_State_base>
1682 __future_base::_S_make_deferred_state(_BoundFn&& __fn)
1684 typedef typename remove_reference<_BoundFn>::type __fn_type;
1685 typedef _Deferred_state<__fn_type> __state_type;
1686 return std::make_shared<__state_type>(std::move(__fn));
1689 template<typename _BoundFn>
1690 inline std::shared_ptr<__future_base::_State_base>
1691 __future_base::_S_make_async_state(_BoundFn&& __fn)
1693 typedef typename remove_reference<_BoundFn>::type __fn_type;
1694 typedef _Async_state_impl<__fn_type> __state_type;
1695 return std::make_shared<__state_type>(std::move(__fn));
1700 template<typename _Fn, typename... _Args>
1701 future<typename result_of<_Fn(_Args...)>::type>
1702 async(launch __policy, _Fn&& __fn, _Args&&... __args)
1704 typedef typename result_of<_Fn(_Args...)>::type result_type;
1705 std::shared_ptr<__future_base::_State_base> __state;
1706 if ((__policy & (launch::async|launch::deferred)) == launch::async)
1708 __state = __future_base::_S_make_async_state(std::__bind_simple(
1709 std::forward<_Fn>(__fn), std::forward<_Args>(__args)...));
1713 __state = __future_base::_S_make_deferred_state(std::__bind_simple(
1714 std::forward<_Fn>(__fn), std::forward<_Args>(__args)...));
1716 return future<result_type>(__state);
1719 /// async, potential overload
1720 template<typename _Fn, typename... _Args>
1721 inline future<typename result_of<_Fn(_Args...)>::type>
1722 async(_Fn&& __fn, _Args&&... __args)
1724 return async(launch::async|launch::deferred, std::forward<_Fn>(__fn),
1725 std::forward<_Args>(__args)...);
1728 #endif // _GLIBCXX_ASYNC_ABI_COMPAT
1729 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
1732 _GLIBCXX_END_NAMESPACE_VERSION
1737 #endif // _GLIBCXX_FUTURE