1 // <future> -*- C++ -*-
3 // Copyright (C) 2009-2014 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/functexcept.h>
45 #include <bits/unique_ptr.h>
46 #include <bits/shared_ptr.h>
47 #include <bits/uses_allocator.h>
48 #include <bits/allocated_ptr.h>
49 #include <ext/aligned_buffer.h>
51 namespace std _GLIBCXX_VISIBILITY(default)
53 _GLIBCXX_BEGIN_NAMESPACE_VERSION
56 * @defgroup futures Futures
57 * @ingroup concurrency
59 * Classes for futures support.
63 /// Error code for futures
64 enum class future_errc
66 future_already_retrieved = 1,
67 promise_already_satisfied,
74 struct is_error_code_enum<future_errc> : public true_type { };
76 /// Points to a statically-allocated object derived from error_category.
78 future_category() noexcept;
80 /// Overload for make_error_code.
82 make_error_code(future_errc __errc) noexcept
83 { return error_code(static_cast<int>(__errc), future_category()); }
85 /// Overload for make_error_condition.
86 inline error_condition
87 make_error_condition(future_errc __errc) noexcept
88 { return error_condition(static_cast<int>(__errc), future_category()); }
91 * @brief Exception type thrown by futures.
94 class future_error : public logic_error
99 explicit future_error(error_code __ec)
100 : logic_error("std::future_error"), _M_code(__ec)
103 virtual ~future_error() noexcept;
106 what() const noexcept;
109 code() const noexcept { return _M_code; }
112 // Forward declarations.
113 template<typename _Res>
116 template<typename _Res>
119 template<typename _Signature>
122 template<typename _Res>
125 /// Launch code for futures
132 constexpr launch operator&(launch __x, launch __y)
134 return static_cast<launch>(
135 static_cast<int>(__x) & static_cast<int>(__y));
138 constexpr launch operator|(launch __x, launch __y)
140 return static_cast<launch>(
141 static_cast<int>(__x) | static_cast<int>(__y));
144 constexpr launch operator^(launch __x, launch __y)
146 return static_cast<launch>(
147 static_cast<int>(__x) ^ static_cast<int>(__y));
150 constexpr launch operator~(launch __x)
151 { return static_cast<launch>(~static_cast<int>(__x)); }
153 inline launch& operator&=(launch& __x, launch __y)
154 { return __x = __x & __y; }
156 inline launch& operator|=(launch& __x, launch __y)
157 { return __x = __x | __y; }
159 inline launch& operator^=(launch& __x, launch __y)
160 { return __x = __x ^ __y; }
162 /// Status code for futures
163 enum class future_status
170 template<typename _Fn, typename... _Args>
171 future<typename result_of<_Fn(_Args...)>::type>
172 async(launch __policy, _Fn&& __fn, _Args&&... __args);
174 template<typename _Fn, typename... _Args>
175 future<typename result_of<_Fn(_Args...)>::type>
176 async(_Fn&& __fn, _Args&&... __args);
178 #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) \
179 && (ATOMIC_INT_LOCK_FREE > 1)
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;
299 condition_variable _M_cond;
300 atomic_flag _M_retrieved = ATOMIC_FLAG_INIT;
301 bool _M_ready = false;
305 _State_baseV2() noexcept = default;
306 _State_baseV2(const _State_baseV2&) = delete;
307 _State_baseV2& operator=(const _State_baseV2&) = delete;
308 virtual ~_State_baseV2() = default;
313 // Run any deferred function or join any asynchronous thread:
316 unique_lock<mutex> __lock(_M_mutex);
317 _M_cond.wait(__lock, [&] { return _M_ready; });
321 template<typename _Rep, typename _Period>
323 wait_for(const chrono::duration<_Rep, _Period>& __rel)
325 unique_lock<mutex> __lock(_M_mutex);
327 return future_status::ready;
328 if (_M_has_deferred())
329 return future_status::deferred;
330 if (_M_cond.wait_for(__lock, __rel, [&] { return _M_ready; }))
332 // _GLIBCXX_RESOLVE_LIB_DEFECTS
333 // 2100. timed waiting functions must also join
334 // This call is a no-op by default except on an async future,
335 // in which case the async thread is joined. It's also not a
336 // no-op for a deferred future, but such a future will never
337 // reach this point because it returns future_status::deferred
338 // instead of waiting for the future to become ready (see
339 // above). Async futures synchronize in this call, so we need
340 // no further synchronization here.
343 return future_status::ready;
345 return future_status::timeout;
348 template<typename _Clock, typename _Duration>
350 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
352 unique_lock<mutex> __lock(_M_mutex);
354 return future_status::ready;
355 if (_M_has_deferred())
356 return future_status::deferred;
357 if (_M_cond.wait_until(__lock, __abs, [&] { return _M_ready; }))
359 // _GLIBCXX_RESOLVE_LIB_DEFECTS
360 // 2100. timed waiting functions must also join
361 // See wait_for(...) above.
364 return future_status::ready;
366 return future_status::timeout;
369 // Provide a result to the shared state and make it ready.
370 // Atomically performs:
372 // _M_result = __res();
376 _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
378 unique_lock<mutex> __lock(_M_mutex, defer_lock);
379 // all calls to this function are serialized,
380 // side-effects of invoking __res only happen once
381 call_once(_M_once, &_State_baseV2::_M_do_set, this,
382 std::__addressof(__res), std::__addressof(__lock));
383 if (__lock.owns_lock())
386 _M_cond.notify_all();
388 else if (!__ignore_failure)
389 __throw_future_error(int(future_errc::promise_already_satisfied));
392 // Provide a result to the shared state but delay making it ready
393 // until the calling thread exits.
394 // Atomically performs:
396 // _M_result = __res();
399 _M_set_delayed_result(function<_Ptr_type()> __res,
400 weak_ptr<_State_baseV2> __self)
402 unique_ptr<_Make_ready> __mr{new _Make_ready};
403 unique_lock<mutex> __lock(_M_mutex, defer_lock);
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(__lock));
408 if (!__lock.owns_lock())
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.
428 lock_guard<mutex> __lock(_M_mutex);
429 _M_result.swap(__res);
432 _M_cond.notify_all();
436 // Called when this object is first passed to a future.
438 _M_set_retrieved_flag()
440 if (_M_retrieved.test_and_set())
441 __throw_future_error(int(future_errc::future_already_retrieved));
444 template<typename _Res, typename _Arg>
448 template<typename _Res, typename _Arg>
449 struct _Setter<_Res, _Arg&>
451 // check this is only used by promise<R>::set_value(const R&)
452 // or promise<R&>::set_value(R&)
453 static_assert(is_same<_Res, _Arg&>::value // promise<R&>
454 || is_same<const _Res, _Arg>::value, // promise<R>
455 "Invalid specialisation");
457 // Used by std::promise to copy construct the result.
458 typename promise<_Res>::_Ptr_type operator()()
460 _State_baseV2::_S_check(_M_promise->_M_future);
461 _M_promise->_M_storage->_M_set(*_M_arg);
462 return std::move(_M_promise->_M_storage);
464 promise<_Res>* _M_promise;
469 template<typename _Res>
470 struct _Setter<_Res, _Res&&>
472 // Used by std::promise to move construct the result.
473 typename promise<_Res>::_Ptr_type operator()()
475 _State_baseV2::_S_check(_M_promise->_M_future);
476 _M_promise->_M_storage->_M_set(std::move(*_M_arg));
477 return std::move(_M_promise->_M_storage);
479 promise<_Res>* _M_promise;
483 struct __exception_ptr_tag { };
486 template<typename _Res>
487 struct _Setter<_Res, __exception_ptr_tag>
489 // Used by std::promise to store an exception as the result.
490 typename promise<_Res>::_Ptr_type operator()()
492 _State_baseV2::_S_check(_M_promise->_M_future);
493 _M_promise->_M_storage->_M_error = *_M_ex;
494 return std::move(_M_promise->_M_storage);
497 promise<_Res>* _M_promise;
498 exception_ptr* _M_ex;
501 template<typename _Res, typename _Arg>
502 static _Setter<_Res, _Arg&&>
503 __setter(promise<_Res>* __prom, _Arg&& __arg)
505 return _Setter<_Res, _Arg&&>{ __prom, &__arg };
508 template<typename _Res>
509 static _Setter<_Res, __exception_ptr_tag>
510 __setter(exception_ptr& __ex, promise<_Res>* __prom)
512 return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex };
515 template<typename _Tp>
517 _S_check(const shared_ptr<_Tp>& __p)
519 if (!static_cast<bool>(__p))
520 __throw_future_error((int)future_errc::no_state);
524 // The function invoked with std::call_once(_M_once, ...).
526 _M_do_set(function<_Ptr_type()>* __f, unique_lock<mutex>* __lock)
528 _Ptr_type __res = (*__f)(); // do not hold lock while running setter
530 _M_result.swap(__res);
533 // Wait for completion of async function.
534 virtual void _M_complete_async() { }
536 // Return true if state corresponds to a deferred function.
537 virtual bool _M_has_deferred() const { return false; }
539 struct _Make_ready final : __at_thread_exit_elt
541 weak_ptr<_State_baseV2> _M_shared_state;
542 static void _S_run(void*);
547 #ifdef _GLIBCXX_ASYNC_ABI_COMPAT
549 class _Async_state_common;
551 using _State_base = _State_baseV2;
552 class _Async_state_commonV2;
555 template<typename _BoundFn, typename = typename _BoundFn::result_type>
556 class _Deferred_state;
558 template<typename _BoundFn, typename = typename _BoundFn::result_type>
559 class _Async_state_impl;
561 template<typename _Signature>
562 class _Task_state_base;
564 template<typename _Fn, typename _Alloc, typename _Signature>
567 template<typename _BoundFn>
568 static std::shared_ptr<_State_base>
569 _S_make_deferred_state(_BoundFn&& __fn);
571 template<typename _BoundFn>
572 static std::shared_ptr<_State_base>
573 _S_make_async_state(_BoundFn&& __fn);
575 template<typename _Res_ptr, typename _Fn,
576 typename _Res = typename _Res_ptr::element_type::result_type>
579 template<typename _Res_ptr, typename _BoundFn>
580 static _Task_setter<_Res_ptr, _BoundFn>
581 _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call)
583 return { std::__addressof(__ptr), std::__addressof(__call) };
587 /// Partial specialization for reference types.
588 template<typename _Res>
589 struct __future_base::_Result<_Res&> : __future_base::_Result_base
591 typedef _Res& result_type;
593 _Result() noexcept : _M_value_ptr() { }
596 _M_set(_Res& __res) noexcept
597 { _M_value_ptr = std::addressof(__res); }
599 _Res& _M_get() noexcept { return *_M_value_ptr; }
604 void _M_destroy() { delete this; }
607 /// Explicit specialization for void.
609 struct __future_base::_Result<void> : __future_base::_Result_base
611 typedef void result_type;
614 void _M_destroy() { delete this; }
617 #ifndef _GLIBCXX_ASYNC_ABI_COMPAT
619 // Allow _Setter objects to be stored locally in std::function
620 template<typename _Res, typename _Arg>
621 struct __is_location_invariant
622 <__future_base::_State_base::_Setter<_Res, _Arg>>
625 // Allow _Task_setter objects to be stored locally in std::function
626 template<typename _Res_ptr, typename _Fn, typename _Res>
627 struct __is_location_invariant
628 <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>>
631 /// Common implementation for future and shared_future.
632 template<typename _Res>
633 class __basic_future : public __future_base
636 typedef shared_ptr<_State_base> __state_type;
637 typedef __future_base::_Result<_Res>& __result_type;
640 __state_type _M_state;
644 __basic_future(const __basic_future&) = delete;
645 __basic_future& operator=(const __basic_future&) = delete;
648 valid() const noexcept { return static_cast<bool>(_M_state); }
653 _State_base::_S_check(_M_state);
657 template<typename _Rep, typename _Period>
659 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
661 _State_base::_S_check(_M_state);
662 return _M_state->wait_for(__rel);
665 template<typename _Clock, typename _Duration>
667 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
669 _State_base::_S_check(_M_state);
670 return _M_state->wait_until(__abs);
674 /// Wait for the state to be ready and rethrow any stored exception
676 _M_get_result() const
678 _State_base::_S_check(_M_state);
679 _Result_base& __res = _M_state->wait();
680 if (!(__res._M_error == 0))
681 rethrow_exception(__res._M_error);
682 return static_cast<__result_type>(__res);
685 void _M_swap(__basic_future& __that) noexcept
687 _M_state.swap(__that._M_state);
690 // Construction of a future by promise::get_future()
692 __basic_future(const __state_type& __state) : _M_state(__state)
694 _State_base::_S_check(_M_state);
695 _M_state->_M_set_retrieved_flag();
698 // Copy construction from a shared_future
700 __basic_future(const shared_future<_Res>&) noexcept;
702 // Move construction from a shared_future
704 __basic_future(shared_future<_Res>&&) noexcept;
706 // Move construction from a future
708 __basic_future(future<_Res>&&) noexcept;
710 constexpr __basic_future() noexcept : _M_state() { }
714 explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { }
715 ~_Reset() { _M_fut._M_state.reset(); }
716 __basic_future& _M_fut;
721 /// Primary template for future.
722 template<typename _Res>
723 class future : public __basic_future<_Res>
725 friend class promise<_Res>;
726 template<typename> friend class packaged_task;
727 template<typename _Fn, typename... _Args>
728 friend future<typename result_of<_Fn(_Args...)>::type>
729 async(launch, _Fn&&, _Args&&...);
731 typedef __basic_future<_Res> _Base_type;
732 typedef typename _Base_type::__state_type __state_type;
735 future(const __state_type& __state) : _Base_type(__state) { }
738 constexpr future() noexcept : _Base_type() { }
741 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
744 future(const future&) = delete;
745 future& operator=(const future&) = delete;
747 future& operator=(future&& __fut) noexcept
749 future(std::move(__fut))._M_swap(*this);
753 /// Retrieving the value
757 typename _Base_type::_Reset __reset(*this);
758 return std::move(this->_M_get_result()._M_value());
761 shared_future<_Res> share();
764 /// Partial specialization for future<R&>
765 template<typename _Res>
766 class future<_Res&> : public __basic_future<_Res&>
768 friend class promise<_Res&>;
769 template<typename> friend class packaged_task;
770 template<typename _Fn, typename... _Args>
771 friend future<typename result_of<_Fn(_Args...)>::type>
772 async(launch, _Fn&&, _Args&&...);
774 typedef __basic_future<_Res&> _Base_type;
775 typedef typename _Base_type::__state_type __state_type;
778 future(const __state_type& __state) : _Base_type(__state) { }
781 constexpr future() noexcept : _Base_type() { }
784 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
787 future(const future&) = delete;
788 future& operator=(const future&) = delete;
790 future& operator=(future&& __fut) noexcept
792 future(std::move(__fut))._M_swap(*this);
796 /// Retrieving the value
800 typename _Base_type::_Reset __reset(*this);
801 return this->_M_get_result()._M_get();
804 shared_future<_Res&> share();
807 /// Explicit specialization for future<void>
809 class future<void> : public __basic_future<void>
811 friend class promise<void>;
812 template<typename> friend class packaged_task;
813 template<typename _Fn, typename... _Args>
814 friend future<typename result_of<_Fn(_Args...)>::type>
815 async(launch, _Fn&&, _Args&&...);
817 typedef __basic_future<void> _Base_type;
818 typedef typename _Base_type::__state_type __state_type;
821 future(const __state_type& __state) : _Base_type(__state) { }
824 constexpr future() noexcept : _Base_type() { }
827 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
830 future(const future&) = delete;
831 future& operator=(const future&) = delete;
833 future& operator=(future&& __fut) noexcept
835 future(std::move(__fut))._M_swap(*this);
839 /// Retrieving the value
843 typename _Base_type::_Reset __reset(*this);
844 this->_M_get_result();
847 shared_future<void> share();
851 /// Primary template for shared_future.
852 template<typename _Res>
853 class shared_future : public __basic_future<_Res>
855 typedef __basic_future<_Res> _Base_type;
858 constexpr shared_future() noexcept : _Base_type() { }
861 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
863 /// Construct from a future rvalue
864 shared_future(future<_Res>&& __uf) noexcept
865 : _Base_type(std::move(__uf))
868 /// Construct from a shared_future rvalue
869 shared_future(shared_future&& __sf) noexcept
870 : _Base_type(std::move(__sf))
873 shared_future& operator=(const shared_future& __sf)
875 shared_future(__sf)._M_swap(*this);
879 shared_future& operator=(shared_future&& __sf) noexcept
881 shared_future(std::move(__sf))._M_swap(*this);
885 /// Retrieving the value
887 get() const { return this->_M_get_result()._M_value(); }
890 /// Partial specialization for shared_future<R&>
891 template<typename _Res>
892 class shared_future<_Res&> : public __basic_future<_Res&>
894 typedef __basic_future<_Res&> _Base_type;
897 constexpr shared_future() noexcept : _Base_type() { }
900 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
902 /// Construct from a future rvalue
903 shared_future(future<_Res&>&& __uf) noexcept
904 : _Base_type(std::move(__uf))
907 /// Construct from a shared_future rvalue
908 shared_future(shared_future&& __sf) noexcept
909 : _Base_type(std::move(__sf))
912 shared_future& operator=(const shared_future& __sf)
914 shared_future(__sf)._M_swap(*this);
918 shared_future& operator=(shared_future&& __sf) noexcept
920 shared_future(std::move(__sf))._M_swap(*this);
924 /// Retrieving the value
926 get() const { return this->_M_get_result()._M_get(); }
929 /// Explicit specialization for shared_future<void>
931 class shared_future<void> : public __basic_future<void>
933 typedef __basic_future<void> _Base_type;
936 constexpr shared_future() noexcept : _Base_type() { }
939 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
941 /// Construct from a future rvalue
942 shared_future(future<void>&& __uf) noexcept
943 : _Base_type(std::move(__uf))
946 /// Construct from a shared_future rvalue
947 shared_future(shared_future&& __sf) noexcept
948 : _Base_type(std::move(__sf))
951 shared_future& operator=(const shared_future& __sf)
953 shared_future(__sf)._M_swap(*this);
957 shared_future& operator=(shared_future&& __sf) noexcept
959 shared_future(std::move(__sf))._M_swap(*this);
963 // Retrieving the value
965 get() const { this->_M_get_result(); }
968 // Now we can define the protected __basic_future constructors.
969 template<typename _Res>
970 inline __basic_future<_Res>::
971 __basic_future(const shared_future<_Res>& __sf) noexcept
972 : _M_state(__sf._M_state)
975 template<typename _Res>
976 inline __basic_future<_Res>::
977 __basic_future(shared_future<_Res>&& __sf) noexcept
978 : _M_state(std::move(__sf._M_state))
981 template<typename _Res>
982 inline __basic_future<_Res>::
983 __basic_future(future<_Res>&& __uf) noexcept
984 : _M_state(std::move(__uf._M_state))
987 template<typename _Res>
988 inline shared_future<_Res>
989 future<_Res>::share()
990 { return shared_future<_Res>(std::move(*this)); }
992 template<typename _Res>
993 inline shared_future<_Res&>
994 future<_Res&>::share()
995 { return shared_future<_Res&>(std::move(*this)); }
997 inline shared_future<void>
998 future<void>::share()
999 { return shared_future<void>(std::move(*this)); }
1001 /// Primary template for promise
1002 template<typename _Res>
1005 typedef __future_base::_State_base _State;
1006 typedef __future_base::_Result<_Res> _Res_type;
1007 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1008 template<typename, typename> friend class _State::_Setter;
1010 shared_ptr<_State> _M_future;
1011 _Ptr_type _M_storage;
1015 : _M_future(std::make_shared<_State>()),
1016 _M_storage(new _Res_type())
1019 promise(promise&& __rhs) noexcept
1020 : _M_future(std::move(__rhs._M_future)),
1021 _M_storage(std::move(__rhs._M_storage))
1024 template<typename _Allocator>
1025 promise(allocator_arg_t, const _Allocator& __a)
1026 : _M_future(std::allocate_shared<_State>(__a)),
1027 _M_storage(__future_base::_S_allocate_result<_Res>(__a))
1030 template<typename _Allocator>
1031 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1032 : _M_future(std::move(__rhs._M_future)),
1033 _M_storage(std::move(__rhs._M_storage))
1036 promise(const promise&) = delete;
1040 if (static_cast<bool>(_M_future) && !_M_future.unique())
1041 _M_future->_M_break_promise(std::move(_M_storage));
1046 operator=(promise&& __rhs) noexcept
1048 promise(std::move(__rhs)).swap(*this);
1052 promise& operator=(const promise&) = delete;
1055 swap(promise& __rhs) noexcept
1057 _M_future.swap(__rhs._M_future);
1058 _M_storage.swap(__rhs._M_storage);
1061 // Retrieving the result
1064 { return future<_Res>(_M_future); }
1066 // Setting the result
1068 set_value(const _Res& __r)
1069 { _M_future->_M_set_result(_State::__setter(this, __r)); }
1072 set_value(_Res&& __r)
1073 { _M_future->_M_set_result(_State::__setter(this, std::move(__r))); }
1076 set_exception(exception_ptr __p)
1077 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1080 set_value_at_thread_exit(const _Res& __r)
1082 _M_future->_M_set_delayed_result(_State::__setter(this, __r),
1087 set_value_at_thread_exit(_Res&& __r)
1089 _M_future->_M_set_delayed_result(
1090 _State::__setter(this, std::move(__r)), _M_future);
1094 set_exception_at_thread_exit(exception_ptr __p)
1096 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1101 template<typename _Res>
1103 swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
1106 template<typename _Res, typename _Alloc>
1107 struct uses_allocator<promise<_Res>, _Alloc>
1108 : public true_type { };
1111 /// Partial specialization for promise<R&>
1112 template<typename _Res>
1113 class promise<_Res&>
1115 typedef __future_base::_State_base _State;
1116 typedef __future_base::_Result<_Res&> _Res_type;
1117 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1118 template<typename, typename> friend class _State::_Setter;
1120 shared_ptr<_State> _M_future;
1121 _Ptr_type _M_storage;
1125 : _M_future(std::make_shared<_State>()),
1126 _M_storage(new _Res_type())
1129 promise(promise&& __rhs) noexcept
1130 : _M_future(std::move(__rhs._M_future)),
1131 _M_storage(std::move(__rhs._M_storage))
1134 template<typename _Allocator>
1135 promise(allocator_arg_t, const _Allocator& __a)
1136 : _M_future(std::allocate_shared<_State>(__a)),
1137 _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
1140 template<typename _Allocator>
1141 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1142 : _M_future(std::move(__rhs._M_future)),
1143 _M_storage(std::move(__rhs._M_storage))
1146 promise(const promise&) = delete;
1150 if (static_cast<bool>(_M_future) && !_M_future.unique())
1151 _M_future->_M_break_promise(std::move(_M_storage));
1156 operator=(promise&& __rhs) noexcept
1158 promise(std::move(__rhs)).swap(*this);
1162 promise& operator=(const promise&) = delete;
1165 swap(promise& __rhs) noexcept
1167 _M_future.swap(__rhs._M_future);
1168 _M_storage.swap(__rhs._M_storage);
1171 // Retrieving the result
1174 { return future<_Res&>(_M_future); }
1176 // Setting the result
1178 set_value(_Res& __r)
1179 { _M_future->_M_set_result(_State::__setter(this, __r)); }
1182 set_exception(exception_ptr __p)
1183 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1186 set_value_at_thread_exit(_Res& __r)
1188 _M_future->_M_set_delayed_result(_State::__setter(this, __r),
1193 set_exception_at_thread_exit(exception_ptr __p)
1195 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1200 /// Explicit specialization for promise<void>
1204 typedef __future_base::_State_base _State;
1205 typedef __future_base::_Result<void> _Res_type;
1206 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1207 template<typename, typename> friend class _State::_Setter;
1209 shared_ptr<_State> _M_future;
1210 _Ptr_type _M_storage;
1214 : _M_future(std::make_shared<_State>()),
1215 _M_storage(new _Res_type())
1218 promise(promise&& __rhs) noexcept
1219 : _M_future(std::move(__rhs._M_future)),
1220 _M_storage(std::move(__rhs._M_storage))
1223 template<typename _Allocator>
1224 promise(allocator_arg_t, const _Allocator& __a)
1225 : _M_future(std::allocate_shared<_State>(__a)),
1226 _M_storage(__future_base::_S_allocate_result<void>(__a))
1229 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1230 // 2095. missing constructors needed for uses-allocator construction
1231 template<typename _Allocator>
1232 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1233 : _M_future(std::move(__rhs._M_future)),
1234 _M_storage(std::move(__rhs._M_storage))
1237 promise(const promise&) = delete;
1241 if (static_cast<bool>(_M_future) && !_M_future.unique())
1242 _M_future->_M_break_promise(std::move(_M_storage));
1247 operator=(promise&& __rhs) noexcept
1249 promise(std::move(__rhs)).swap(*this);
1253 promise& operator=(const promise&) = delete;
1256 swap(promise& __rhs) noexcept
1258 _M_future.swap(__rhs._M_future);
1259 _M_storage.swap(__rhs._M_storage);
1262 // Retrieving the result
1265 { return future<void>(_M_future); }
1267 // Setting the result
1271 set_exception(exception_ptr __p)
1272 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1275 set_value_at_thread_exit();
1278 set_exception_at_thread_exit(exception_ptr __p)
1280 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1287 struct __future_base::_State_base::_Setter<void, void>
1289 promise<void>::_Ptr_type operator()()
1291 _State_base::_S_check(_M_promise->_M_future);
1292 return std::move(_M_promise->_M_storage);
1295 promise<void>* _M_promise;
1299 promise<void>::set_value()
1300 { _M_future->_M_set_result(_State::_Setter<void, void>{ this }); }
1303 promise<void>::set_value_at_thread_exit()
1305 _M_future->_M_set_delayed_result(_State::_Setter<void, void>{this},
1309 template<typename _Ptr_type, typename _Fn, typename _Res>
1310 struct __future_base::_Task_setter
1312 // Invoke the function and provide the result to the caller.
1313 _Ptr_type operator()()
1317 (*_M_result)->_M_set((*_M_fn)());
1319 __catch(const __cxxabiv1::__forced_unwind&)
1321 __throw_exception_again; // will cause broken_promise
1325 (*_M_result)->_M_error = current_exception();
1327 return std::move(*_M_result);
1329 _Ptr_type* _M_result;
1333 template<typename _Ptr_type, typename _Fn>
1334 struct __future_base::_Task_setter<_Ptr_type, _Fn, void>
1336 _Ptr_type operator()()
1342 __catch(const __cxxabiv1::__forced_unwind&)
1344 __throw_exception_again; // will cause broken_promise
1348 (*_M_result)->_M_error = current_exception();
1350 return std::move(*_M_result);
1352 _Ptr_type* _M_result;
1356 // Holds storage for a packaged_task's result.
1357 template<typename _Res, typename... _Args>
1358 struct __future_base::_Task_state_base<_Res(_Args...)>
1359 : __future_base::_State_base
1361 typedef _Res _Res_type;
1363 template<typename _Alloc>
1364 _Task_state_base(const _Alloc& __a)
1365 : _M_result(_S_allocate_result<_Res>(__a))
1368 // Invoke the stored task and make the state ready.
1370 _M_run(_Args&&... __args) = 0;
1372 // Invoke the stored task and make the state ready at thread exit.
1374 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0;
1376 virtual shared_ptr<_Task_state_base>
1379 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1380 _Ptr_type _M_result;
1383 // Holds a packaged_task's stored task.
1384 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1385 struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final
1386 : __future_base::_Task_state_base<_Res(_Args...)>
1388 template<typename _Fn2>
1389 _Task_state(_Fn2&& __fn, const _Alloc& __a)
1390 : _Task_state_base<_Res(_Args...)>(__a),
1391 _M_impl(std::forward<_Fn2>(__fn), __a)
1396 _M_run(_Args&&... __args)
1398 // bound arguments decay so wrap lvalue references
1399 auto __boundfn = std::__bind_simple(std::ref(_M_impl._M_fn),
1400 _S_maybe_wrap_ref(std::forward<_Args>(__args))...);
1401 this->_M_set_result(_S_task_setter(this->_M_result, __boundfn));
1405 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self)
1407 // bound arguments decay so wrap lvalue references
1408 auto __boundfn = std::__bind_simple(std::ref(_M_impl._M_fn),
1409 _S_maybe_wrap_ref(std::forward<_Args>(__args))...);
1410 this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn),
1414 virtual shared_ptr<_Task_state_base<_Res(_Args...)>>
1417 template<typename _Tp>
1418 static reference_wrapper<_Tp>
1419 _S_maybe_wrap_ref(_Tp& __t)
1420 { return std::ref(__t); }
1422 template<typename _Tp>
1424 typename enable_if<!is_lvalue_reference<_Tp>::value, _Tp>::type&&
1425 _S_maybe_wrap_ref(_Tp&& __t)
1426 { return std::forward<_Tp>(__t); }
1428 struct _Impl : _Alloc
1430 template<typename _Fn2>
1431 _Impl(_Fn2&& __fn, const _Alloc& __a)
1432 : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { }
1437 template<typename _Signature, typename _Fn, typename _Alloc>
1438 static shared_ptr<__future_base::_Task_state_base<_Signature>>
1439 __create_task_state(_Fn&& __fn, const _Alloc& __a)
1441 typedef typename decay<_Fn>::type _Fn2;
1442 typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State;
1443 return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a);
1446 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1447 shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>>
1448 __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset()
1450 return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn),
1451 static_cast<_Alloc&>(_M_impl));
1454 template<typename _Task, typename _Fn, bool
1455 = is_same<_Task, typename decay<_Fn>::type>::value>
1456 struct __constrain_pkgdtask
1457 { typedef void __type; };
1459 template<typename _Task, typename _Fn>
1460 struct __constrain_pkgdtask<_Task, _Fn, true>
1464 template<typename _Res, typename... _ArgTypes>
1465 class packaged_task<_Res(_ArgTypes...)>
1467 typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type;
1468 shared_ptr<_State_type> _M_state;
1471 // Construction and destruction
1472 packaged_task() noexcept { }
1474 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1475 // 2095. missing constructors needed for uses-allocator construction
1476 template<typename _Allocator>
1477 packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
1480 template<typename _Fn, typename = typename
1481 __constrain_pkgdtask<packaged_task, _Fn>::__type>
1483 packaged_task(_Fn&& __fn)
1484 : packaged_task(allocator_arg, std::allocator<int>(),
1485 std::forward<_Fn>(__fn))
1488 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1489 // 2097. packaged_task constructors should be constrained
1490 template<typename _Fn, typename _Alloc, typename = typename
1491 __constrain_pkgdtask<packaged_task, _Fn>::__type>
1493 packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn)
1494 : _M_state(__create_task_state<_Res(_ArgTypes...)>(
1495 std::forward<_Fn>(__fn), __a))
1500 if (static_cast<bool>(_M_state) && !_M_state.unique())
1501 _M_state->_M_break_promise(std::move(_M_state->_M_result));
1505 packaged_task(const packaged_task&) = delete;
1506 packaged_task& operator=(const packaged_task&) = delete;
1508 template<typename _Allocator>
1509 packaged_task(allocator_arg_t, const _Allocator&,
1510 const packaged_task&) = delete;
1513 packaged_task(packaged_task&& __other) noexcept
1514 { this->swap(__other); }
1516 template<typename _Allocator>
1517 packaged_task(allocator_arg_t, const _Allocator&,
1518 packaged_task&& __other) noexcept
1519 { this->swap(__other); }
1521 packaged_task& operator=(packaged_task&& __other) noexcept
1523 packaged_task(std::move(__other)).swap(*this);
1528 swap(packaged_task& __other) noexcept
1529 { _M_state.swap(__other._M_state); }
1532 valid() const noexcept
1533 { return static_cast<bool>(_M_state); }
1538 { return future<_Res>(_M_state); }
1542 operator()(_ArgTypes... __args)
1544 __future_base::_State_base::_S_check(_M_state);
1545 _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
1549 make_ready_at_thread_exit(_ArgTypes... __args)
1551 __future_base::_State_base::_S_check(_M_state);
1552 _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state);
1558 __future_base::_State_base::_S_check(_M_state);
1559 packaged_task __tmp;
1560 __tmp._M_state = _M_state;
1561 _M_state = _M_state->_M_reset();
1566 template<typename _Res, typename... _ArgTypes>
1568 swap(packaged_task<_Res(_ArgTypes...)>& __x,
1569 packaged_task<_Res(_ArgTypes...)>& __y) noexcept
1572 template<typename _Res, typename _Alloc>
1573 struct uses_allocator<packaged_task<_Res>, _Alloc>
1574 : public true_type { };
1577 // Shared state created by std::async().
1578 // Holds a deferred function and storage for its result.
1579 template<typename _BoundFn, typename _Res>
1580 class __future_base::_Deferred_state final
1581 : public __future_base::_State_base
1585 _Deferred_state(_BoundFn&& __fn)
1586 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1590 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1591 _Ptr_type _M_result;
1594 // Run the deferred function.
1598 // Multiple threads can call a waiting function on the future and
1599 // reach this point at the same time. The call_once in _M_set_result
1600 // ensures only the first one run the deferred function, stores the
1601 // result in _M_result, swaps that with the base _M_result and makes
1602 // the state ready. Tell _M_set_result to ignore failure so all later
1603 // calls do nothing.
1604 _M_set_result(_S_task_setter(_M_result, _M_fn), true);
1607 // Caller should check whether the state is ready first, because this
1608 // function will return true even after the deferred function has run.
1609 virtual bool _M_has_deferred() const { return true; }
1612 // Common functionality hoisted out of the _Async_state_impl template.
1613 class __future_base::_Async_state_commonV2
1614 : public __future_base::_State_base
1617 ~_Async_state_commonV2() = default;
1619 // Make waiting functions block until the thread completes, as if joined.
1621 // This function is used by wait() to satisfy the first requirement below
1622 // and by wait_for() / wait_until() to satisfy the second.
1626 // — a call to a waiting function on an asynchronous return object that
1627 // shares the shared state created by this async call shall block until
1628 // the associated thread has completed, as if joined, or else time out.
1630 // — the associated thread completion synchronizes with the return from
1631 // the first function that successfully detects the ready status of the
1632 // shared state or with the return from the last function that releases
1633 // the shared state, whichever happens first.
1634 virtual void _M_complete_async() { _M_join(); }
1636 void _M_join() { std::call_once(_M_once, &thread::join, ref(_M_thread)); }
1642 // Shared state created by std::async().
1643 // Starts a new thread that runs a function and makes the shared state ready.
1644 template<typename _BoundFn, typename _Res>
1645 class __future_base::_Async_state_impl final
1646 : public __future_base::_Async_state_commonV2
1650 _Async_state_impl(_BoundFn&& __fn)
1651 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1653 _M_thread = std::thread{ [this] {
1656 _M_set_result(_S_task_setter(_M_result, _M_fn));
1658 __catch (const __cxxabiv1::__forced_unwind&)
1660 // make the shared state ready on thread cancellation
1661 if (static_cast<bool>(_M_result))
1662 this->_M_break_promise(std::move(_M_result));
1663 __throw_exception_again;
1668 // Must not destroy _M_result and _M_fn until the thread finishes.
1669 // Call join() directly rather than through _M_join() because no other
1670 // thread can be referring to this state if it is being destroyed.
1671 ~_Async_state_impl() { if (_M_thread.joinable()) _M_thread.join(); }
1674 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1675 _Ptr_type _M_result;
1679 template<typename _BoundFn>
1680 inline std::shared_ptr<__future_base::_State_base>
1681 __future_base::_S_make_deferred_state(_BoundFn&& __fn)
1683 typedef typename remove_reference<_BoundFn>::type __fn_type;
1684 typedef _Deferred_state<__fn_type> __state_type;
1685 return std::make_shared<__state_type>(std::move(__fn));
1688 template<typename _BoundFn>
1689 inline std::shared_ptr<__future_base::_State_base>
1690 __future_base::_S_make_async_state(_BoundFn&& __fn)
1692 typedef typename remove_reference<_BoundFn>::type __fn_type;
1693 typedef _Async_state_impl<__fn_type> __state_type;
1694 return std::make_shared<__state_type>(std::move(__fn));
1699 template<typename _Fn, typename... _Args>
1700 future<typename result_of<_Fn(_Args...)>::type>
1701 async(launch __policy, _Fn&& __fn, _Args&&... __args)
1703 typedef typename result_of<_Fn(_Args...)>::type result_type;
1704 std::shared_ptr<__future_base::_State_base> __state;
1705 if ((__policy & (launch::async|launch::deferred)) == launch::async)
1707 __state = __future_base::_S_make_async_state(std::__bind_simple(
1708 std::forward<_Fn>(__fn), std::forward<_Args>(__args)...));
1712 __state = __future_base::_S_make_deferred_state(std::__bind_simple(
1713 std::forward<_Fn>(__fn), std::forward<_Args>(__args)...));
1715 return future<result_type>(__state);
1718 /// async, potential overload
1719 template<typename _Fn, typename... _Args>
1720 inline future<typename result_of<_Fn(_Args...)>::type>
1721 async(_Fn&& __fn, _Args&&... __args)
1723 return async(launch::async|launch::deferred, std::forward<_Fn>(__fn),
1724 std::forward<_Args>(__args)...);
1727 #endif // _GLIBCXX_ASYNC_ABI_COMPAT
1728 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
1729 // && ATOMIC_INT_LOCK_FREE
1732 _GLIBCXX_END_NAMESPACE_VERSION
1737 #endif // _GLIBCXX_FUTURE