libstdc++
future
Go to the documentation of this file.
1// <future> -*- C++ -*-
2
3// Copyright (C) 2009-2020 Free Software Foundation, Inc.
4//
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)
9// any later version.
10
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.
15
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.
19
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/>.
24
25/** @file include/future
26 * This is a Standard C++ Library header.
27 */
28
29#ifndef _GLIBCXX_FUTURE
30#define _GLIBCXX_FUTURE 1
31
32#pragma GCC system_header
33
34#if __cplusplus < 201103L
35# include <bits/c++0x_warning.h>
36#else
37
38#include <mutex>
39#include <thread>
40#include <condition_variable>
41#include <system_error>
42#include <atomic>
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>
52
53namespace std _GLIBCXX_VISIBILITY(default)
54{
55_GLIBCXX_BEGIN_NAMESPACE_VERSION
56
57 /**
58 * @defgroup futures Futures
59 * @ingroup concurrency
60 *
61 * Classes for futures support.
62 * @{
63 */
64
65 /// Error code for futures
66 enum class future_errc
67 {
68 future_already_retrieved = 1,
69 promise_already_satisfied,
70 no_state,
71 broken_promise
72 };
73
74 /// Specialization.
75 template<>
77
78 /// Points to a statically-allocated object derived from error_category.
79 const error_category&
80 future_category() noexcept;
81
82 /// Overload for make_error_code.
83 inline error_code
84 make_error_code(future_errc __errc) noexcept
85 { return error_code(static_cast<int>(__errc), future_category()); }
86
87 /// Overload for make_error_condition.
88 inline error_condition
90 { return error_condition(static_cast<int>(__errc), future_category()); }
91
92 /**
93 * @brief Exception type thrown by futures.
94 * @ingroup exceptions
95 */
97 {
98 public:
99 explicit
101 : future_error(std::make_error_code(__errc))
102 { }
103
104 virtual ~future_error() noexcept;
105
106 virtual const char*
107 what() const noexcept;
108
109 const error_code&
110 code() const noexcept { return _M_code; }
111
112 private:
113 explicit
115 : logic_error("std::future_error: " + __ec.message()), _M_code(__ec)
116 { }
117
118 friend void __throw_future_error(int);
119
120 error_code _M_code;
121 };
122
123 // Forward declarations.
124 template<typename _Res>
125 class future;
126
127 template<typename _Res>
128 class shared_future;
129
130 template<typename _Signature>
131 class packaged_task;
132
133 template<typename _Res>
134 class promise;
135
136 /// Launch code for futures
137 enum class launch
138 {
139 async = 1,
140 deferred = 2
141 };
142
143 constexpr launch operator&(launch __x, launch __y)
144 {
145 return static_cast<launch>(
146 static_cast<int>(__x) & static_cast<int>(__y));
147 }
148
149 constexpr launch operator|(launch __x, launch __y)
150 {
151 return static_cast<launch>(
152 static_cast<int>(__x) | static_cast<int>(__y));
153 }
154
155 constexpr launch operator^(launch __x, launch __y)
156 {
157 return static_cast<launch>(
158 static_cast<int>(__x) ^ static_cast<int>(__y));
159 }
160
161 constexpr launch operator~(launch __x)
162 { return static_cast<launch>(~static_cast<int>(__x)); }
163
164 inline launch& operator&=(launch& __x, launch __y)
165 { return __x = __x & __y; }
166
167 inline launch& operator|=(launch& __x, launch __y)
168 { return __x = __x | __y; }
169
170 inline launch& operator^=(launch& __x, launch __y)
171 { return __x = __x ^ __y; }
172
173 /// Status code for futures
174 enum class future_status
175 {
176 ready,
177 timeout,
178 deferred
179 };
180
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;
186
187 template<typename _Fn, typename... _Args>
188 future<__async_result_of<_Fn, _Args...>>
189 async(launch __policy, _Fn&& __fn, _Args&&... __args);
190
191 template<typename _Fn, typename... _Args>
192 future<__async_result_of<_Fn, _Args...>>
193 async(_Fn&& __fn, _Args&&... __args);
194
195#if defined(_GLIBCXX_HAS_GTHREADS)
196
197 /// Base class and enclosing scope.
199 {
200 /// Base class for results.
202 {
203 exception_ptr _M_error;
204
205 _Result_base(const _Result_base&) = delete;
206 _Result_base& operator=(const _Result_base&) = delete;
207
208 // _M_destroy() allows derived classes to control deallocation
209 virtual void _M_destroy() = 0;
210
211 struct _Deleter
212 {
213 void operator()(_Result_base* __fr) const { __fr->_M_destroy(); }
214 };
215
216 protected:
217 _Result_base();
218 virtual ~_Result_base();
219 };
220
221 /// A unique_ptr for result objects.
222 template<typename _Res>
224
225 /// A result object that has storage for an object of type _Res.
226 template<typename _Res>
228 {
229 private:
230 __gnu_cxx::__aligned_buffer<_Res> _M_storage;
231 bool _M_initialized;
232
233 public:
234 typedef _Res result_type;
235
236 _Result() noexcept : _M_initialized() { }
237
238 ~_Result()
239 {
240 if (_M_initialized)
241 _M_value().~_Res();
242 }
243
244 // Return lvalue, future will add const or rvalue-reference
245 _Res&
246 _M_value() noexcept { return *_M_storage._M_ptr(); }
247
248 void
249 _M_set(const _Res& __res)
250 {
251 ::new (_M_storage._M_addr()) _Res(__res);
252 _M_initialized = true;
253 }
254
255 void
256 _M_set(_Res&& __res)
257 {
258 ::new (_M_storage._M_addr()) _Res(std::move(__res));
259 _M_initialized = true;
260 }
261
262 private:
263 void _M_destroy() { delete this; }
264 };
265
266 /// A result object that uses an allocator.
267 template<typename _Res, typename _Alloc>
268 struct _Result_alloc final : _Result<_Res>, _Alloc
269 {
270 using __allocator_type = __alloc_rebind<_Alloc, _Result_alloc>;
271
272 explicit
273 _Result_alloc(const _Alloc& __a) : _Result<_Res>(), _Alloc(__a)
274 { }
275
276 private:
277 void _M_destroy()
278 {
279 __allocator_type __a(*this);
280 __allocated_ptr<__allocator_type> __guard_ptr{ __a, this };
281 this->~_Result_alloc();
282 }
283 };
284
285 // Create a result object that uses an allocator.
286 template<typename _Res, typename _Allocator>
288 _S_allocate_result(const _Allocator& __a)
289 {
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};
294 __guard = nullptr;
295 return _Ptr<__result_type>(__p);
296 }
297
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)
302 {
303 return _Ptr<_Result<_Res>>(new _Result<_Res>);
304 }
305
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.
309 class _State_baseV2
310 {
311 typedef _Ptr<_Result_base> _Ptr_type;
312
313 enum _Status : unsigned {
314 __not_ready,
315 __ready
316 };
317
318 _Ptr_type _M_result;
319 __atomic_futex_unsigned<> _M_status;
320 atomic_flag _M_retrieved = ATOMIC_FLAG_INIT;
321 once_flag _M_once;
322
323 public:
324 _State_baseV2() noexcept : _M_result(), _M_status(_Status::__not_ready)
325 { }
326 _State_baseV2(const _State_baseV2&) = delete;
327 _State_baseV2& operator=(const _State_baseV2&) = delete;
328 virtual ~_State_baseV2() = default;
329
330 _Result_base&
331 wait()
332 {
333 // Run any deferred function or join any asynchronous thread:
334 _M_complete_async();
335 // Acquire MO makes sure this synchronizes with the thread that made
336 // the future ready.
337 _M_status._M_load_when_equal(_Status::__ready, memory_order_acquire);
338 return *_M_result;
339 }
340
341 template<typename _Rep, typename _Period>
343 wait_for(const chrono::duration<_Rep, _Period>& __rel)
344 {
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))
353 {
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.
363 _M_complete_async();
364
365 return future_status::ready;
366 }
367 return future_status::timeout;
368 }
369
370 template<typename _Clock, typename _Duration>
372 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
373 {
374#if __cplusplus > 201703L
375 static_assert(chrono::is_clock_v<_Clock>);
376#endif
377 // First, check if the future has been made ready. Use acquire MO
378 // to synchronize with the thread that made it ready.
379 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
380 return future_status::ready;
381 if (_M_is_deferred_future())
382 return future_status::deferred;
383 if (_M_status._M_load_when_equal_until(_Status::__ready,
384 memory_order_acquire, __abs))
385 {
386 // _GLIBCXX_RESOLVE_LIB_DEFECTS
387 // 2100. timed waiting functions must also join
388 // See wait_for(...) above.
389 _M_complete_async();
390
391 return future_status::ready;
392 }
393 return future_status::timeout;
394 }
395
396 // Provide a result to the shared state and make it ready.
397 // Calls at most once: _M_result = __res();
398 void
399 _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
400 {
401 bool __did_set = false;
402 // all calls to this function are serialized,
403 // side-effects of invoking __res only happen once
404 call_once(_M_once, &_State_baseV2::_M_do_set, this,
405 std::__addressof(__res), std::__addressof(__did_set));
406 if (__did_set)
407 // Use release MO to synchronize with observers of the ready state.
408 _M_status._M_store_notify_all(_Status::__ready,
409 memory_order_release);
410 else if (!__ignore_failure)
411 __throw_future_error(int(future_errc::promise_already_satisfied));
412 }
413
414 // Provide a result to the shared state but delay making it ready
415 // until the calling thread exits.
416 // Calls at most once: _M_result = __res();
417 void
418 _M_set_delayed_result(function<_Ptr_type()> __res,
419 weak_ptr<_State_baseV2> __self)
420 {
421 bool __did_set = false;
422 unique_ptr<_Make_ready> __mr{new _Make_ready};
423 // all calls to this function are serialized,
424 // side-effects of invoking __res only happen once
425 call_once(_M_once, &_State_baseV2::_M_do_set, this,
426 std::__addressof(__res), std::__addressof(__did_set));
427 if (!__did_set)
428 __throw_future_error(int(future_errc::promise_already_satisfied));
429 __mr->_M_shared_state = std::move(__self);
430 __mr->_M_set();
431 __mr.release();
432 }
433
434 // Abandon this shared state.
435 void
436 _M_break_promise(_Ptr_type __res)
437 {
438 if (static_cast<bool>(__res))
439 {
440 __res->_M_error =
441 make_exception_ptr(future_error(future_errc::broken_promise));
442 // This function is only called when the last asynchronous result
443 // provider is abandoning this shared state, so noone can be
444 // trying to make the shared state ready at the same time, and
445 // we can access _M_result directly instead of through call_once.
446 _M_result.swap(__res);
447 // Use release MO to synchronize with observers of the ready state.
448 _M_status._M_store_notify_all(_Status::__ready,
449 memory_order_release);
450 }
451 }
452
453 // Called when this object is first passed to a future.
454 void
455 _M_set_retrieved_flag()
456 {
457 if (_M_retrieved.test_and_set())
458 __throw_future_error(int(future_errc::future_already_retrieved));
459 }
460
461 template<typename _Res, typename _Arg>
462 struct _Setter;
463
464 // set lvalues
465 template<typename _Res, typename _Arg>
466 struct _Setter<_Res, _Arg&>
467 {
468 // check this is only used by promise<R>::set_value(const R&)
469 // or promise<R&>::set_value(R&)
470 static_assert(is_same<_Res, _Arg&>::value // promise<R&>
471 || is_same<const _Res, _Arg>::value, // promise<R>
472 "Invalid specialisation");
473
474 // Used by std::promise to copy construct the result.
475 typename promise<_Res>::_Ptr_type operator()() const
476 {
477 _M_promise->_M_storage->_M_set(*_M_arg);
478 return std::move(_M_promise->_M_storage);
479 }
480 promise<_Res>* _M_promise;
481 _Arg* _M_arg;
482 };
483
484 // set rvalues
485 template<typename _Res>
486 struct _Setter<_Res, _Res&&>
487 {
488 // Used by std::promise to move construct the result.
489 typename promise<_Res>::_Ptr_type operator()() const
490 {
491 _M_promise->_M_storage->_M_set(std::move(*_M_arg));
492 return std::move(_M_promise->_M_storage);
493 }
494 promise<_Res>* _M_promise;
495 _Res* _M_arg;
496 };
497
498 // set void
499 template<typename _Res>
500 struct _Setter<_Res, void>
501 {
502 static_assert(is_void<_Res>::value, "Only used for promise<void>");
503
504 typename promise<_Res>::_Ptr_type operator()() const
505 { return std::move(_M_promise->_M_storage); }
506
507 promise<_Res>* _M_promise;
508 };
509
510 struct __exception_ptr_tag { };
511
512 // set exceptions
513 template<typename _Res>
514 struct _Setter<_Res, __exception_ptr_tag>
515 {
516 // Used by std::promise to store an exception as the result.
517 typename promise<_Res>::_Ptr_type operator()() const
518 {
519 _M_promise->_M_storage->_M_error = *_M_ex;
520 return std::move(_M_promise->_M_storage);
521 }
522
523 promise<_Res>* _M_promise;
524 exception_ptr* _M_ex;
525 };
526
527 template<typename _Res, typename _Arg>
528 static _Setter<_Res, _Arg&&>
529 __setter(promise<_Res>* __prom, _Arg&& __arg)
530 {
531 _S_check(__prom->_M_future);
532 return _Setter<_Res, _Arg&&>{ __prom, std::__addressof(__arg) };
533 }
534
535 template<typename _Res>
536 static _Setter<_Res, __exception_ptr_tag>
537 __setter(exception_ptr& __ex, promise<_Res>* __prom)
538 {
539 _S_check(__prom->_M_future);
540 return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex };
541 }
542
543 template<typename _Res>
544 static _Setter<_Res, void>
545 __setter(promise<_Res>* __prom)
546 {
547 _S_check(__prom->_M_future);
548 return _Setter<_Res, void>{ __prom };
549 }
550
551 template<typename _Tp>
552 static void
553 _S_check(const shared_ptr<_Tp>& __p)
554 {
555 if (!static_cast<bool>(__p))
556 __throw_future_error((int)future_errc::no_state);
557 }
558
559 private:
560 // The function invoked with std::call_once(_M_once, ...).
561 void
562 _M_do_set(function<_Ptr_type()>* __f, bool* __did_set)
563 {
564 _Ptr_type __res = (*__f)();
565 // Notify the caller that we did try to set; if we do not throw an
566 // exception, the caller will be aware that it did set (e.g., see
567 // _M_set_result).
568 *__did_set = true;
569 _M_result.swap(__res); // nothrow
570 }
571
572 // Wait for completion of async function.
573 virtual void _M_complete_async() { }
574
575 // Return true if state corresponds to a deferred function.
576 virtual bool _M_is_deferred_future() const { return false; }
577
578 struct _Make_ready final : __at_thread_exit_elt
579 {
580 weak_ptr<_State_baseV2> _M_shared_state;
581 static void _S_run(void*);
582 void _M_set();
583 };
584 };
585
586#ifdef _GLIBCXX_ASYNC_ABI_COMPAT
587 class _State_base;
588 class _Async_state_common;
589#else
590 using _State_base = _State_baseV2;
591 class _Async_state_commonV2;
592#endif
593
594 template<typename _BoundFn,
595 typename _Res = decltype(std::declval<_BoundFn&>()())>
596 class _Deferred_state;
597
598 template<typename _BoundFn,
599 typename _Res = decltype(std::declval<_BoundFn&>()())>
600 class _Async_state_impl;
601
602 template<typename _Signature>
603 class _Task_state_base;
604
605 template<typename _Fn, typename _Alloc, typename _Signature>
606 class _Task_state;
607
608 template<typename _BoundFn>
610 _S_make_deferred_state(_BoundFn&& __fn);
611
612 template<typename _BoundFn>
614 _S_make_async_state(_BoundFn&& __fn);
615
616 template<typename _Res_ptr, typename _Fn,
617 typename _Res = typename _Res_ptr::element_type::result_type>
618 struct _Task_setter;
619
620 template<typename _Res_ptr, typename _BoundFn>
621 static _Task_setter<_Res_ptr, _BoundFn>
622 _S_task_setter(_Res_ptr& __ptr, _BoundFn& __call)
623 {
624 return { std::__addressof(__ptr), std::__addressof(__call) };
625 }
626 };
627
628 /// Partial specialization for reference types.
629 template<typename _Res>
631 {
632 typedef _Res& result_type;
633
634 _Result() noexcept : _M_value_ptr() { }
635
636 void
637 _M_set(_Res& __res) noexcept
638 { _M_value_ptr = std::addressof(__res); }
639
640 _Res& _M_get() noexcept { return *_M_value_ptr; }
641
642 private:
643 _Res* _M_value_ptr;
644
645 void _M_destroy() { delete this; }
646 };
647
648 /// Explicit specialization for void.
649 template<>
651 {
652 typedef void result_type;
653
654 private:
655 void _M_destroy() { delete this; }
656 };
657
658#ifndef _GLIBCXX_ASYNC_ABI_COMPAT
659
660 // Allow _Setter objects to be stored locally in std::function
661 template<typename _Res, typename _Arg>
663 <__future_base::_State_base::_Setter<_Res, _Arg>>
664 : true_type { };
665
666 // Allow _Task_setter objects to be stored locally in std::function
667 template<typename _Res_ptr, typename _Fn, typename _Res>
669 <__future_base::_Task_setter<_Res_ptr, _Fn, _Res>>
670 : true_type { };
671
672 /// Common implementation for future and shared_future.
673 template<typename _Res>
675 {
676 protected:
679
680 private:
681 __state_type _M_state;
682
683 public:
684 // Disable copying.
685 __basic_future(const __basic_future&) = delete;
686 __basic_future& operator=(const __basic_future&) = delete;
687
688 bool
689 valid() const noexcept { return static_cast<bool>(_M_state); }
690
691 void
692 wait() const
693 {
694 _State_base::_S_check(_M_state);
695 _M_state->wait();
696 }
697
698 template<typename _Rep, typename _Period>
700 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
701 {
702 _State_base::_S_check(_M_state);
703 return _M_state->wait_for(__rel);
704 }
705
706 template<typename _Clock, typename _Duration>
708 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
709 {
710 _State_base::_S_check(_M_state);
711 return _M_state->wait_until(__abs);
712 }
713
714 protected:
715 /// Wait for the state to be ready and rethrow any stored exception
718 {
719 _State_base::_S_check(_M_state);
720 _Result_base& __res = _M_state->wait();
721 if (!(__res._M_error == 0))
722 rethrow_exception(__res._M_error);
723 return static_cast<__result_type>(__res);
724 }
725
726 void _M_swap(__basic_future& __that) noexcept
727 {
728 _M_state.swap(__that._M_state);
729 }
730
731 // Construction of a future by promise::get_future()
732 explicit
733 __basic_future(const __state_type& __state) : _M_state(__state)
734 {
735 _State_base::_S_check(_M_state);
736 _M_state->_M_set_retrieved_flag();
737 }
738
739 // Copy construction from a shared_future
740 explicit
741 __basic_future(const shared_future<_Res>&) noexcept;
742
743 // Move construction from a shared_future
744 explicit
745 __basic_future(shared_future<_Res>&&) noexcept;
746
747 // Move construction from a future
748 explicit
749 __basic_future(future<_Res>&&) noexcept;
750
751 constexpr __basic_future() noexcept : _M_state() { }
752
753 struct _Reset
754 {
755 explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { }
756 ~_Reset() { _M_fut._M_state.reset(); }
757 __basic_future& _M_fut;
758 };
759 };
760
761
762 /// Primary template for future.
763 template<typename _Res>
764 class future : public __basic_future<_Res>
765 {
766 friend class promise<_Res>;
767 template<typename> friend class packaged_task;
768 template<typename _Fn, typename... _Args>
769 friend future<__async_result_of<_Fn, _Args...>>
770 async(launch, _Fn&&, _Args&&...);
771
773 typedef typename _Base_type::__state_type __state_type;
774
775 explicit
776 future(const __state_type& __state) : _Base_type(__state) { }
777
778 public:
779 constexpr future() noexcept : _Base_type() { }
780
781 /// Move constructor
782 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
783
784 // Disable copying
785 future(const future&) = delete;
786 future& operator=(const future&) = delete;
787
788 future& operator=(future&& __fut) noexcept
789 {
790 future(std::move(__fut))._M_swap(*this);
791 return *this;
792 }
793
794 /// Retrieving the value
795 _Res
797 {
798 typename _Base_type::_Reset __reset(*this);
799 return std::move(this->_M_get_result()._M_value());
800 }
801
802 shared_future<_Res> share() noexcept;
803 };
804
805 /// Partial specialization for future<R&>
806 template<typename _Res>
807 class future<_Res&> : public __basic_future<_Res&>
808 {
809 friend class promise<_Res&>;
810 template<typename> friend class packaged_task;
811 template<typename _Fn, typename... _Args>
812 friend future<__async_result_of<_Fn, _Args...>>
813 async(launch, _Fn&&, _Args&&...);
814
816 typedef typename _Base_type::__state_type __state_type;
817
818 explicit
819 future(const __state_type& __state) : _Base_type(__state) { }
820
821 public:
822 constexpr future() noexcept : _Base_type() { }
823
824 /// Move constructor
825 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
826
827 // Disable copying
828 future(const future&) = delete;
829 future& operator=(const future&) = delete;
830
831 future& operator=(future&& __fut) noexcept
832 {
833 future(std::move(__fut))._M_swap(*this);
834 return *this;
835 }
836
837 /// Retrieving the value
838 _Res&
840 {
841 typename _Base_type::_Reset __reset(*this);
842 return this->_M_get_result()._M_get();
843 }
844
845 shared_future<_Res&> share() noexcept;
846 };
847
848 /// Explicit specialization for future<void>
849 template<>
850 class future<void> : public __basic_future<void>
851 {
852 friend class promise<void>;
853 template<typename> friend class packaged_task;
854 template<typename _Fn, typename... _Args>
855 friend future<__async_result_of<_Fn, _Args...>>
856 async(launch, _Fn&&, _Args&&...);
857
859 typedef typename _Base_type::__state_type __state_type;
860
861 explicit
862 future(const __state_type& __state) : _Base_type(__state) { }
863
864 public:
865 constexpr future() noexcept : _Base_type() { }
866
867 /// Move constructor
868 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
869
870 // Disable copying
871 future(const future&) = delete;
872 future& operator=(const future&) = delete;
873
874 future& operator=(future&& __fut) noexcept
875 {
876 future(std::move(__fut))._M_swap(*this);
877 return *this;
878 }
879
880 /// Retrieving the value
881 void
883 {
884 typename _Base_type::_Reset __reset(*this);
885 this->_M_get_result();
886 }
887
888 shared_future<void> share() noexcept;
889 };
890
891
892 /// Primary template for shared_future.
893 template<typename _Res>
894 class shared_future : public __basic_future<_Res>
895 {
897
898 public:
899 constexpr shared_future() noexcept : _Base_type() { }
900
901 /// Copy constructor
902 shared_future(const shared_future& __sf) noexcept : _Base_type(__sf) { }
903
904 /// Construct from a future rvalue
906 : _Base_type(std::move(__uf))
907 { }
908
909 /// Construct from a shared_future rvalue
911 : _Base_type(std::move(__sf))
912 { }
913
914 shared_future& operator=(const shared_future& __sf) noexcept
915 {
916 shared_future(__sf)._M_swap(*this);
917 return *this;
918 }
919
920 shared_future& operator=(shared_future&& __sf) noexcept
921 {
922 shared_future(std::move(__sf))._M_swap(*this);
923 return *this;
924 }
925
926 /// Retrieving the value
927 const _Res&
928 get() const { return this->_M_get_result()._M_value(); }
929 };
930
931 /// Partial specialization for shared_future<R&>
932 template<typename _Res>
934 {
936
937 public:
938 constexpr shared_future() noexcept : _Base_type() { }
939
940 /// Copy constructor
941 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
942
943 /// Construct from a future rvalue
945 : _Base_type(std::move(__uf))
946 { }
947
948 /// Construct from a shared_future rvalue
950 : _Base_type(std::move(__sf))
951 { }
952
953 shared_future& operator=(const shared_future& __sf)
954 {
955 shared_future(__sf)._M_swap(*this);
956 return *this;
957 }
958
959 shared_future& operator=(shared_future&& __sf) noexcept
960 {
961 shared_future(std::move(__sf))._M_swap(*this);
962 return *this;
963 }
964
965 /// Retrieving the value
966 _Res&
967 get() const { return this->_M_get_result()._M_get(); }
968 };
969
970 /// Explicit specialization for shared_future<void>
971 template<>
972 class shared_future<void> : public __basic_future<void>
973 {
975
976 public:
977 constexpr shared_future() noexcept : _Base_type() { }
978
979 /// Copy constructor
980 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
981
982 /// Construct from a future rvalue
984 : _Base_type(std::move(__uf))
985 { }
986
987 /// Construct from a shared_future rvalue
989 : _Base_type(std::move(__sf))
990 { }
991
992 shared_future& operator=(const shared_future& __sf)
993 {
994 shared_future(__sf)._M_swap(*this);
995 return *this;
996 }
997
998 shared_future& operator=(shared_future&& __sf) noexcept
999 {
1000 shared_future(std::move(__sf))._M_swap(*this);
1001 return *this;
1002 }
1003
1004 // Retrieving the value
1005 void
1006 get() const { this->_M_get_result(); }
1007 };
1008
1009 // Now we can define the protected __basic_future constructors.
1010 template<typename _Res>
1011 inline __basic_future<_Res>::
1012 __basic_future(const shared_future<_Res>& __sf) noexcept
1013 : _M_state(__sf._M_state)
1014 { }
1015
1016 template<typename _Res>
1017 inline __basic_future<_Res>::
1018 __basic_future(shared_future<_Res>&& __sf) noexcept
1019 : _M_state(std::move(__sf._M_state))
1020 { }
1021
1022 template<typename _Res>
1023 inline __basic_future<_Res>::
1024 __basic_future(future<_Res>&& __uf) noexcept
1025 : _M_state(std::move(__uf._M_state))
1026 { }
1027
1028 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1029 // 2556. Wide contract for future::share()
1030 template<typename _Res>
1031 inline shared_future<_Res>
1032 future<_Res>::share() noexcept
1033 { return shared_future<_Res>(std::move(*this)); }
1034
1035 template<typename _Res>
1036 inline shared_future<_Res&>
1037 future<_Res&>::share() noexcept
1038 { return shared_future<_Res&>(std::move(*this)); }
1039
1040 inline shared_future<void>
1041 future<void>::share() noexcept
1042 { return shared_future<void>(std::move(*this)); }
1043
1044 /// Primary template for promise
1045 template<typename _Res>
1047 {
1048 typedef __future_base::_State_base _State;
1051 template<typename, typename> friend class _State::_Setter;
1052 friend _State;
1053
1054 shared_ptr<_State> _M_future;
1055 _Ptr_type _M_storage;
1056
1057 public:
1058 promise()
1059 : _M_future(std::make_shared<_State>()),
1060 _M_storage(new _Res_type())
1061 { }
1062
1063 promise(promise&& __rhs) noexcept
1064 : _M_future(std::move(__rhs._M_future)),
1065 _M_storage(std::move(__rhs._M_storage))
1066 { }
1067
1068 template<typename _Allocator>
1069 promise(allocator_arg_t, const _Allocator& __a)
1070 : _M_future(std::allocate_shared<_State>(__a)),
1071 _M_storage(__future_base::_S_allocate_result<_Res>(__a))
1072 { }
1073
1074 template<typename _Allocator>
1075 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1076 : _M_future(std::move(__rhs._M_future)),
1077 _M_storage(std::move(__rhs._M_storage))
1078 { }
1079
1080 promise(const promise&) = delete;
1081
1082 ~promise()
1083 {
1084 if (static_cast<bool>(_M_future) && !_M_future.unique())
1085 _M_future->_M_break_promise(std::move(_M_storage));
1086 }
1087
1088 // Assignment
1089 promise&
1090 operator=(promise&& __rhs) noexcept
1091 {
1092 promise(std::move(__rhs)).swap(*this);
1093 return *this;
1094 }
1095
1096 promise& operator=(const promise&) = delete;
1097
1098 void
1099 swap(promise& __rhs) noexcept
1100 {
1101 _M_future.swap(__rhs._M_future);
1102 _M_storage.swap(__rhs._M_storage);
1103 }
1104
1105 // Retrieving the result
1107 get_future()
1108 { return future<_Res>(_M_future); }
1109
1110 // Setting the result
1111 void
1112 set_value(const _Res& __r)
1113 { _M_future->_M_set_result(_State::__setter(this, __r)); }
1114
1115 void
1116 set_value(_Res&& __r)
1117 { _M_future->_M_set_result(_State::__setter(this, std::move(__r))); }
1118
1119 void
1120 set_exception(exception_ptr __p)
1121 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1122
1123 void
1124 set_value_at_thread_exit(const _Res& __r)
1125 {
1126 _M_future->_M_set_delayed_result(_State::__setter(this, __r),
1127 _M_future);
1128 }
1129
1130 void
1131 set_value_at_thread_exit(_Res&& __r)
1132 {
1133 _M_future->_M_set_delayed_result(
1134 _State::__setter(this, std::move(__r)), _M_future);
1135 }
1136
1137 void
1138 set_exception_at_thread_exit(exception_ptr __p)
1139 {
1140 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1141 _M_future);
1142 }
1143 };
1144
1145 template<typename _Res>
1146 inline void
1147 swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
1148 { __x.swap(__y); }
1149
1150 template<typename _Res, typename _Alloc>
1151 struct uses_allocator<promise<_Res>, _Alloc>
1152 : public true_type { };
1153
1154
1155 /// Partial specialization for promise<R&>
1156 template<typename _Res>
1157 class promise<_Res&>
1158 {
1159 typedef __future_base::_State_base _State;
1162 template<typename, typename> friend class _State::_Setter;
1163 friend _State;
1164
1165 shared_ptr<_State> _M_future;
1166 _Ptr_type _M_storage;
1167
1168 public:
1169 promise()
1170 : _M_future(std::make_shared<_State>()),
1171 _M_storage(new _Res_type())
1172 { }
1173
1174 promise(promise&& __rhs) noexcept
1175 : _M_future(std::move(__rhs._M_future)),
1176 _M_storage(std::move(__rhs._M_storage))
1177 { }
1178
1179 template<typename _Allocator>
1180 promise(allocator_arg_t, const _Allocator& __a)
1181 : _M_future(std::allocate_shared<_State>(__a)),
1182 _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
1183 { }
1184
1185 template<typename _Allocator>
1186 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1187 : _M_future(std::move(__rhs._M_future)),
1188 _M_storage(std::move(__rhs._M_storage))
1189 { }
1190
1191 promise(const promise&) = delete;
1192
1193 ~promise()
1194 {
1195 if (static_cast<bool>(_M_future) && !_M_future.unique())
1196 _M_future->_M_break_promise(std::move(_M_storage));
1197 }
1198
1199 // Assignment
1200 promise&
1201 operator=(promise&& __rhs) noexcept
1202 {
1203 promise(std::move(__rhs)).swap(*this);
1204 return *this;
1205 }
1206
1207 promise& operator=(const promise&) = delete;
1208
1209 void
1210 swap(promise& __rhs) noexcept
1211 {
1212 _M_future.swap(__rhs._M_future);
1213 _M_storage.swap(__rhs._M_storage);
1214 }
1215
1216 // Retrieving the result
1218 get_future()
1219 { return future<_Res&>(_M_future); }
1220
1221 // Setting the result
1222 void
1223 set_value(_Res& __r)
1224 { _M_future->_M_set_result(_State::__setter(this, __r)); }
1225
1226 void
1227 set_exception(exception_ptr __p)
1228 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1229
1230 void
1231 set_value_at_thread_exit(_Res& __r)
1232 {
1233 _M_future->_M_set_delayed_result(_State::__setter(this, __r),
1234 _M_future);
1235 }
1236
1237 void
1238 set_exception_at_thread_exit(exception_ptr __p)
1239 {
1240 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1241 _M_future);
1242 }
1243 };
1244
1245 /// Explicit specialization for promise<void>
1246 template<>
1247 class promise<void>
1248 {
1249 typedef __future_base::_State_base _State;
1252 template<typename, typename> friend class _State::_Setter;
1253 friend _State;
1254
1255 shared_ptr<_State> _M_future;
1256 _Ptr_type _M_storage;
1257
1258 public:
1259 promise()
1260 : _M_future(std::make_shared<_State>()),
1261 _M_storage(new _Res_type())
1262 { }
1263
1264 promise(promise&& __rhs) noexcept
1265 : _M_future(std::move(__rhs._M_future)),
1266 _M_storage(std::move(__rhs._M_storage))
1267 { }
1268
1269 template<typename _Allocator>
1270 promise(allocator_arg_t, const _Allocator& __a)
1271 : _M_future(std::allocate_shared<_State>(__a)),
1272 _M_storage(__future_base::_S_allocate_result<void>(__a))
1273 { }
1274
1275 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1276 // 2095. missing constructors needed for uses-allocator construction
1277 template<typename _Allocator>
1278 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1279 : _M_future(std::move(__rhs._M_future)),
1280 _M_storage(std::move(__rhs._M_storage))
1281 { }
1282
1283 promise(const promise&) = delete;
1284
1285 ~promise()
1286 {
1287 if (static_cast<bool>(_M_future) && !_M_future.unique())
1288 _M_future->_M_break_promise(std::move(_M_storage));
1289 }
1290
1291 // Assignment
1292 promise&
1293 operator=(promise&& __rhs) noexcept
1294 {
1295 promise(std::move(__rhs)).swap(*this);
1296 return *this;
1297 }
1298
1299 promise& operator=(const promise&) = delete;
1300
1301 void
1302 swap(promise& __rhs) noexcept
1303 {
1304 _M_future.swap(__rhs._M_future);
1305 _M_storage.swap(__rhs._M_storage);
1306 }
1307
1308 // Retrieving the result
1310 get_future()
1311 { return future<void>(_M_future); }
1312
1313 // Setting the result
1314 void
1315 set_value()
1316 { _M_future->_M_set_result(_State::__setter(this)); }
1317
1318 void
1319 set_exception(exception_ptr __p)
1320 { _M_future->_M_set_result(_State::__setter(__p, this)); }
1321
1322 void
1323 set_value_at_thread_exit()
1324 { _M_future->_M_set_delayed_result(_State::__setter(this), _M_future); }
1325
1326 void
1327 set_exception_at_thread_exit(exception_ptr __p)
1328 {
1329 _M_future->_M_set_delayed_result(_State::__setter(__p, this),
1330 _M_future);
1331 }
1332 };
1333
1334 template<typename _Ptr_type, typename _Fn, typename _Res>
1335 struct __future_base::_Task_setter
1336 {
1337 // Invoke the function and provide the result to the caller.
1338 _Ptr_type operator()() const
1339 {
1340 __try
1341 {
1342 (*_M_result)->_M_set((*_M_fn)());
1343 }
1344 __catch(const __cxxabiv1::__forced_unwind&)
1345 {
1346 __throw_exception_again; // will cause broken_promise
1347 }
1348 __catch(...)
1349 {
1350 (*_M_result)->_M_error = current_exception();
1351 }
1352 return std::move(*_M_result);
1353 }
1354 _Ptr_type* _M_result;
1355 _Fn* _M_fn;
1356 };
1357
1358 template<typename _Ptr_type, typename _Fn>
1359 struct __future_base::_Task_setter<_Ptr_type, _Fn, void>
1360 {
1361 _Ptr_type operator()() const
1362 {
1363 __try
1364 {
1365 (*_M_fn)();
1366 }
1367 __catch(const __cxxabiv1::__forced_unwind&)
1368 {
1369 __throw_exception_again; // will cause broken_promise
1370 }
1371 __catch(...)
1372 {
1373 (*_M_result)->_M_error = current_exception();
1374 }
1375 return std::move(*_M_result);
1376 }
1377 _Ptr_type* _M_result;
1378 _Fn* _M_fn;
1379 };
1380
1381 // Holds storage for a packaged_task's result.
1382 template<typename _Res, typename... _Args>
1383 struct __future_base::_Task_state_base<_Res(_Args...)>
1384 : __future_base::_State_base
1385 {
1386 typedef _Res _Res_type;
1387
1388 template<typename _Alloc>
1389 _Task_state_base(const _Alloc& __a)
1390 : _M_result(_S_allocate_result<_Res>(__a))
1391 { }
1392
1393 // Invoke the stored task and make the state ready.
1394 virtual void
1395 _M_run(_Args&&... __args) = 0;
1396
1397 // Invoke the stored task and make the state ready at thread exit.
1398 virtual void
1399 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0;
1400
1401 virtual shared_ptr<_Task_state_base>
1402 _M_reset() = 0;
1403
1404 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1405 _Ptr_type _M_result;
1406 };
1407
1408 // Holds a packaged_task's stored task.
1409 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1410 struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final
1411 : __future_base::_Task_state_base<_Res(_Args...)>
1412 {
1413 template<typename _Fn2>
1414 _Task_state(_Fn2&& __fn, const _Alloc& __a)
1415 : _Task_state_base<_Res(_Args...)>(__a),
1416 _M_impl(std::forward<_Fn2>(__fn), __a)
1417 { }
1418
1419 private:
1420 virtual void
1421 _M_run(_Args&&... __args)
1422 {
1423 auto __boundfn = [&] () -> _Res {
1424 return std::__invoke_r<_Res>(_M_impl._M_fn,
1425 std::forward<_Args>(__args)...);
1426 };
1427 this->_M_set_result(_S_task_setter(this->_M_result, __boundfn));
1428 }
1429
1430 virtual void
1431 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self)
1432 {
1433 auto __boundfn = [&] () -> _Res {
1434 return std::__invoke_r<_Res>(_M_impl._M_fn,
1435 std::forward<_Args>(__args)...);
1436 };
1437 this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn),
1438 std::move(__self));
1439 }
1440
1441 virtual shared_ptr<_Task_state_base<_Res(_Args...)>>
1442 _M_reset();
1443
1444 struct _Impl : _Alloc
1445 {
1446 template<typename _Fn2>
1447 _Impl(_Fn2&& __fn, const _Alloc& __a)
1448 : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { }
1449 _Fn _M_fn;
1450 } _M_impl;
1451 };
1452
1453 template<typename _Signature, typename _Fn,
1454 typename _Alloc = std::allocator<int>>
1455 static shared_ptr<__future_base::_Task_state_base<_Signature>>
1456 __create_task_state(_Fn&& __fn, const _Alloc& __a = _Alloc())
1457 {
1458 typedef typename decay<_Fn>::type _Fn2;
1459 typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State;
1460 return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a);
1461 }
1462
1463 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1464 shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>>
1465 __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset()
1466 {
1467 return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn),
1468 static_cast<_Alloc&>(_M_impl));
1469 }
1470
1471 /// packaged_task
1472 template<typename _Res, typename... _ArgTypes>
1473 class packaged_task<_Res(_ArgTypes...)>
1474 {
1475 typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type;
1476 shared_ptr<_State_type> _M_state;
1477
1478 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1479 // 3039. Unnecessary decay in thread and packaged_task
1480 template<typename _Fn, typename _Fn2 = __remove_cvref_t<_Fn>>
1481 using __not_same
1483
1484 public:
1485 // Construction and destruction
1486 packaged_task() noexcept { }
1487
1488 template<typename _Fn, typename = __not_same<_Fn>>
1489 explicit
1490 packaged_task(_Fn&& __fn)
1491 : _M_state(
1492 __create_task_state<_Res(_ArgTypes...)>(std::forward<_Fn>(__fn)))
1493 { }
1494
1495#if __cplusplus < 201703L
1496 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1497 // 2097. packaged_task constructors should be constrained
1498 // 2407. [this constructor should not be] explicit
1499 // 2921. packaged_task and type-erased allocators
1500 template<typename _Fn, typename _Alloc, typename = __not_same<_Fn>>
1501 packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn)
1502 : _M_state(__create_task_state<_Res(_ArgTypes...)>(
1503 std::forward<_Fn>(__fn), __a))
1504 { }
1505
1506 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1507 // 2095. missing constructors needed for uses-allocator construction
1508 template<typename _Allocator>
1509 packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
1510 { }
1511
1512 template<typename _Allocator>
1513 packaged_task(allocator_arg_t, const _Allocator&,
1514 const packaged_task&) = delete;
1515
1516 template<typename _Allocator>
1517 packaged_task(allocator_arg_t, const _Allocator&,
1518 packaged_task&& __other) noexcept
1519 { this->swap(__other); }
1520#endif
1521
1522 ~packaged_task()
1523 {
1524 if (static_cast<bool>(_M_state) && !_M_state.unique())
1525 _M_state->_M_break_promise(std::move(_M_state->_M_result));
1526 }
1527
1528 // No copy
1529 packaged_task(const packaged_task&) = delete;
1530 packaged_task& operator=(const packaged_task&) = delete;
1531
1532 // Move support
1533 packaged_task(packaged_task&& __other) noexcept
1534 { this->swap(__other); }
1535
1536 packaged_task& operator=(packaged_task&& __other) noexcept
1537 {
1538 packaged_task(std::move(__other)).swap(*this);
1539 return *this;
1540 }
1541
1542 void
1543 swap(packaged_task& __other) noexcept
1544 { _M_state.swap(__other._M_state); }
1545
1546 bool
1547 valid() const noexcept
1548 { return static_cast<bool>(_M_state); }
1549
1550 // Result retrieval
1552 get_future()
1553 { return future<_Res>(_M_state); }
1554
1555 // Execution
1556 void
1557 operator()(_ArgTypes... __args)
1558 {
1559 __future_base::_State_base::_S_check(_M_state);
1560 _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
1561 }
1562
1563 void
1564 make_ready_at_thread_exit(_ArgTypes... __args)
1565 {
1566 __future_base::_State_base::_S_check(_M_state);
1567 _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state);
1568 }
1569
1570 void
1571 reset()
1572 {
1573 __future_base::_State_base::_S_check(_M_state);
1574 packaged_task __tmp;
1575 __tmp._M_state = _M_state;
1576 _M_state = _M_state->_M_reset();
1577 }
1578 };
1579
1580 /// swap
1581 template<typename _Res, typename... _ArgTypes>
1582 inline void
1583 swap(packaged_task<_Res(_ArgTypes...)>& __x,
1584 packaged_task<_Res(_ArgTypes...)>& __y) noexcept
1585 { __x.swap(__y); }
1586
1587#if __cplusplus < 201703L
1588 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1589 // 2976. Dangling uses_allocator specialization for packaged_task
1590 template<typename _Res, typename _Alloc>
1591 struct uses_allocator<packaged_task<_Res>, _Alloc>
1592 : public true_type { };
1593#endif
1594
1595 // Shared state created by std::async().
1596 // Holds a deferred function and storage for its result.
1597 template<typename _BoundFn, typename _Res>
1598 class __future_base::_Deferred_state final
1599 : public __future_base::_State_base
1600 {
1601 public:
1602 explicit
1603 _Deferred_state(_BoundFn&& __fn)
1604 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1605 { }
1606
1607 private:
1608 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1609 _Ptr_type _M_result;
1610 _BoundFn _M_fn;
1611
1612 // Run the deferred function.
1613 virtual void
1614 _M_complete_async()
1615 {
1616 // Multiple threads can call a waiting function on the future and
1617 // reach this point at the same time. The call_once in _M_set_result
1618 // ensures only the first one run the deferred function, stores the
1619 // result in _M_result, swaps that with the base _M_result and makes
1620 // the state ready. Tell _M_set_result to ignore failure so all later
1621 // calls do nothing.
1622 _M_set_result(_S_task_setter(_M_result, _M_fn), true);
1623 }
1624
1625 // Caller should check whether the state is ready first, because this
1626 // function will return true even after the deferred function has run.
1627 virtual bool _M_is_deferred_future() const { return true; }
1628 };
1629
1630 // Common functionality hoisted out of the _Async_state_impl template.
1631 class __future_base::_Async_state_commonV2
1632 : public __future_base::_State_base
1633 {
1634 protected:
1635 ~_Async_state_commonV2() = default;
1636
1637 // Make waiting functions block until the thread completes, as if joined.
1638 //
1639 // This function is used by wait() to satisfy the first requirement below
1640 // and by wait_for() / wait_until() to satisfy the second.
1641 //
1642 // [futures.async]:
1643 //
1644 // - a call to a waiting function on an asynchronous return object that
1645 // shares the shared state created by this async call shall block until
1646 // the associated thread has completed, as if joined, or else time out.
1647 //
1648 // - the associated thread completion synchronizes with the return from
1649 // the first function that successfully detects the ready status of the
1650 // shared state or with the return from the last function that releases
1651 // the shared state, whichever happens first.
1652 virtual void _M_complete_async() { _M_join(); }
1653
1654 void _M_join() { std::call_once(_M_once, &thread::join, &_M_thread); }
1655
1656 thread _M_thread;
1657 once_flag _M_once;
1658 };
1659
1660 // Shared state created by std::async().
1661 // Starts a new thread that runs a function and makes the shared state ready.
1662 template<typename _BoundFn, typename _Res>
1663 class __future_base::_Async_state_impl final
1664 : public __future_base::_Async_state_commonV2
1665 {
1666 public:
1667 explicit
1668 _Async_state_impl(_BoundFn&& __fn)
1669 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1670 {
1671 _M_thread = std::thread{ [this] {
1672 __try
1673 {
1674 _M_set_result(_S_task_setter(_M_result, _M_fn));
1675 }
1676 __catch (const __cxxabiv1::__forced_unwind&)
1677 {
1678 // make the shared state ready on thread cancellation
1679 if (static_cast<bool>(_M_result))
1680 this->_M_break_promise(std::move(_M_result));
1681 __throw_exception_again;
1682 }
1683 } };
1684 }
1685
1686 // Must not destroy _M_result and _M_fn until the thread finishes.
1687 // Call join() directly rather than through _M_join() because no other
1688 // thread can be referring to this state if it is being destroyed.
1689 ~_Async_state_impl() { if (_M_thread.joinable()) _M_thread.join(); }
1690
1691 private:
1692 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1693 _Ptr_type _M_result;
1694 _BoundFn _M_fn;
1695 };
1696
1697 template<typename _BoundFn>
1699 __future_base::_S_make_deferred_state(_BoundFn&& __fn)
1700 {
1701 typedef typename remove_reference<_BoundFn>::type __fn_type;
1702 typedef _Deferred_state<__fn_type> __state_type;
1703 return std::make_shared<__state_type>(std::move(__fn));
1704 }
1705
1706 template<typename _BoundFn>
1708 __future_base::_S_make_async_state(_BoundFn&& __fn)
1709 {
1710 typedef typename remove_reference<_BoundFn>::type __fn_type;
1711 typedef _Async_state_impl<__fn_type> __state_type;
1712 return std::make_shared<__state_type>(std::move(__fn));
1713 }
1714
1715
1716 /// async
1717 template<typename _Fn, typename... _Args>
1718 _GLIBCXX_NODISCARD future<__async_result_of<_Fn, _Args...>>
1719 async(launch __policy, _Fn&& __fn, _Args&&... __args)
1720 {
1722 if ((__policy & launch::async) == launch::async)
1723 {
1724 __try
1725 {
1726 __state = __future_base::_S_make_async_state(
1727 std::thread::__make_invoker(std::forward<_Fn>(__fn),
1728 std::forward<_Args>(__args)...)
1729 );
1730 }
1731#if __cpp_exceptions
1732 catch(const system_error& __e)
1733 {
1734 if (__e.code() != errc::resource_unavailable_try_again
1735 || (__policy & launch::deferred) != launch::deferred)
1736 throw;
1737 }
1738#endif
1739 }
1740 if (!__state)
1741 {
1742 __state = __future_base::_S_make_deferred_state(
1743 std::thread::__make_invoker(std::forward<_Fn>(__fn),
1744 std::forward<_Args>(__args)...));
1745 }
1746 return future<__async_result_of<_Fn, _Args...>>(__state);
1747 }
1748
1749 /// async, potential overload
1750 template<typename _Fn, typename... _Args>
1751 _GLIBCXX_NODISCARD inline future<__async_result_of<_Fn, _Args...>>
1752 async(_Fn&& __fn, _Args&&... __args)
1753 {
1754 return std::async(launch::async|launch::deferred,
1755 std::forward<_Fn>(__fn),
1756 std::forward<_Args>(__args)...);
1757 }
1758
1759#endif // _GLIBCXX_ASYNC_ABI_COMPAT
1760#endif // _GLIBCXX_HAS_GTHREADS
1761
1762 // @} group futures
1763_GLIBCXX_END_NAMESPACE_VERSION
1764} // namespace
1765
1766#endif // C++11
1767
1768#endif // _GLIBCXX_FUTURE
const error_category & future_category() noexcept
Points to a statically-allocated object derived from error_category.
void get()
Retrieving the value.
Definition: future:882
void swap(packaged_task< _Res(_ArgTypes...)> &__x, packaged_task< _Res(_ArgTypes...)> &__y) noexcept
swap
Definition: future:1583
future(future &&__uf) noexcept
Move constructor.
Definition: future:825
error_condition make_error_condition(future_errc __errc) noexcept
Overload for make_error_condition.
Definition: future:89
_Res & get()
Retrieving the value.
Definition: future:839
shared_future(shared_future &&__sf) noexcept
Construct from a shared_future rvalue.
Definition: future:910
future(future &&__uf) noexcept
Move constructor.
Definition: future:782
future_status
Status code for futures.
Definition: future:175
future_errc
Error code for futures.
Definition: future:67
shared_future(future< _Res & > &&__uf) noexcept
Construct from a future rvalue.
Definition: future:944
virtual const char * what() const noexcept
launch
Launch code for futures.
Definition: future:138
__result_type _M_get_result() const
Wait for the state to be ready and rethrow any stored exception.
Definition: future:717
shared_future(const shared_future &__sf) noexcept
Copy constructor.
Definition: future:902
future(future &&__uf) noexcept
Move constructor.
Definition: future:868
shared_future(future< void > &&__uf) noexcept
Construct from a future rvalue.
Definition: future:983
shared_future(future< _Res > &&__uf) noexcept
Construct from a future rvalue.
Definition: future:905
_Res & get() const
Retrieving the value.
Definition: future:967
const _Res & get() const
Retrieving the value.
Definition: future:928
shared_future(const shared_future &__sf)
Copy constructor.
Definition: future:941
shared_future(shared_future &&__sf) noexcept
Construct from a shared_future rvalue.
Definition: future:988
_Res get()
Retrieving the value.
Definition: future:796
future< __async_result_of< _Fn, _Args... > > async(_Fn &&__fn, _Args &&... __args)
async, potential overload
Definition: future:1752
shared_future(const shared_future &__sf)
Copy constructor.
Definition: future:980
future< __async_result_of< _Fn, _Args... > > async(launch __policy, _Fn &&__fn, _Args &&... __args)
async
Definition: future:1719
shared_future(shared_future &&__sf) noexcept
Construct from a shared_future rvalue.
Definition: future:949
void swap(unique_ptr &__u) noexcept
Exchange the pointer and deleter with another object.
Definition: unique_ptr.h:460
void swap(shared_ptr< _Tp > &__a, shared_ptr< _Tp > &__b) noexcept
Swap overload for shared_ptr.
integral_constant< bool, true > true_type
The type used as a compile-time boolean with true value.
Definition: type_traits:75
constexpr _Tp * addressof(_Tp &__r) noexcept
Returns the actual address of the object or function referenced by r, even in the presence of an over...
Definition: move.h:140
constexpr std::remove_reference< _Tp >::type && move(_Tp &&__t) noexcept
Convert a value to an rvalue.
Definition: move.h:101
constexpr _Tp * __addressof(_Tp &__r) noexcept
Same as C++11 std::addressof.
Definition: move.h:49
constexpr _Tp && forward(typename std::remove_reference< _Tp >::type &__t) noexcept
Forward an lvalue.
Definition: move.h:76
exception_ptr current_exception() noexcept
exception_ptr make_exception_ptr(_Ex) noexcept
Obtain an exception_ptr pointing to a copy of the supplied object.
void rethrow_exception(exception_ptr)
Throw the object pointed to by the exception_ptr.
void call_once(once_flag &__once, _Callable &&__f, _Args &&... __args)
Invoke a callable and synchronize with other calls using the same flag.
Definition: mutex:712
ISO C++ entities toplevel namespace is std.
bitset< _Nb > operator&(const bitset< _Nb > &__x, const bitset< _Nb > &__y) noexcept
Global bitwise operations on bitsets.
Definition: bitset:1433
__allocated_ptr< _Alloc > __allocate_guarded(_Alloc &__a)
Allocate space for a single object using __a.
Definition: allocated_ptr.h:95
time_point
Definition: chrono:748
Exception type thrown by futures.
Definition: future:97
Primary template for future.
Definition: future:765
Primary template for shared_future.
Definition: future:895
Primary template for promise.
Definition: future:1047
Base class and enclosing scope.
Definition: future:199
Base class for results.
Definition: future:202
A result object that has storage for an object of type _Res.
Definition: future:228
A result object that uses an allocator.
Definition: future:269
Partial specialization for reference types.
Definition: future:631
Explicit specialization for void.
Definition: future:651
Common implementation for future and shared_future.
Definition: future:675
Partial specialization for future<R&>
Definition: future:808
Explicit specialization for future<void>
Definition: future:851
Partial specialization for shared_future<R&>
Definition: future:934
Explicit specialization for shared_future<void>
Definition: future:973
One of two subclasses of exception.
Definition: stdexcept:114
is_error_code_enum
Definition: system_error:60
An exception type that includes an error_code value.
Definition: system_error:429
thread
Definition: thread:74
integral_constant
Definition: type_traits:58
Define a member typedef type only if a boolean constant is true.
Definition: type_traits:2170
Non-standard RAII type for managing pointers obtained from allocators.
Definition: allocated_ptr.h:47
The standard allocator, as per [20.4].
Definition: allocator.h:121
Thrown as part of forced unwinding.
Definition: cxxabi_forced.h:49
An opaque pointer to an arbitrary exception.
Definition: exception_ptr.h:81
20.7.1.2 unique_ptr for single objects.
Definition: unique_ptr.h:242
[allocator.tag]