libstdc++
future
Go to the documentation of this file.
1// <future> -*- C++ -*-
2
3// Copyright (C) 2009-2022 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> // call_once
39#include <condition_variable> // __at_thread_exit_elt
40#include <system_error>
41#include <bits/atomic_base.h> // atomic_flag
42#include <bits/allocated_ptr.h>
43#include <bits/atomic_futex.h>
44#include <bits/exception_defines.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/std_thread.h>
50#include <bits/uses_allocator.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<>
76 struct is_error_code_enum<future_errc> : public true_type { };
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
89 make_error_condition(future_errc __errc) noexcept
90 { return error_condition(static_cast<int>(__errc), future_category()); }
91
92 /**
93 * @brief Exception type thrown by futures.
94 * @ingroup exceptions
95 */
96 class future_error : public logic_error
97 {
98 public:
99 explicit
100 future_error(future_errc __errc)
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
114 future_error(error_code __ec)
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) noexcept
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) noexcept
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) noexcept
156 {
157 return static_cast<launch>(
158 static_cast<int>(__x) ^ static_cast<int>(__y));
159 }
160
161 constexpr launch operator~(launch __x) noexcept
162 { return static_cast<launch>(~static_cast<int>(__x)); }
163
164 inline launch& operator&=(launch& __x, launch __y) noexcept
165 { return __x = __x & __y; }
166
167 inline launch& operator|=(launch& __x, launch __y) noexcept
168 { return __x = __x | __y; }
169
170 inline launch& operator^=(launch& __x, launch __y) noexcept
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.
198 struct __future_base
199 {
200 /// Base class for results.
201 struct _Result_base
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>
223 using _Ptr = unique_ptr<_Res, _Result_base::_Deleter>;
224
225 /// A result object that has storage for an object of type _Res.
226 template<typename _Res>
227 struct _Result : _Result_base
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>
287 static _Ptr<_Result_alloc<_Res, _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>
342 future_status
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
350 if (_M_is_deferred_future())
351 return future_status::deferred;
352
353 // Don't wait unless the relative time is greater than zero.
354 if (__rel > __rel.zero()
355 && _M_status._M_load_when_equal_for(_Status::__ready,
356 memory_order_acquire,
357 __rel))
358 {
359 // _GLIBCXX_RESOLVE_LIB_DEFECTS
360 // 2100. timed waiting functions must also join
361 // This call is a no-op by default except on an async future,
362 // in which case the async thread is joined. It's also not a
363 // no-op for a deferred future, but such a future will never
364 // reach this point because it returns future_status::deferred
365 // instead of waiting for the future to become ready (see
366 // above). Async futures synchronize in this call, so we need
367 // no further synchronization here.
368 _M_complete_async();
369
370 return future_status::ready;
371 }
372 return future_status::timeout;
373 }
374
375 template<typename _Clock, typename _Duration>
376 future_status
377 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
378 {
379#if __cplusplus > 201703L
380 static_assert(chrono::is_clock_v<_Clock>);
381#endif
382 // First, check if the future has been made ready. Use acquire MO
383 // to synchronize with the thread that made it ready.
384 if (_M_status._M_load(memory_order_acquire) == _Status::__ready)
385 return future_status::ready;
386
387 if (_M_is_deferred_future())
388 return future_status::deferred;
389
390 if (_M_status._M_load_when_equal_until(_Status::__ready,
391 memory_order_acquire,
392 __abs))
393 {
394 // _GLIBCXX_RESOLVE_LIB_DEFECTS
395 // 2100. timed waiting functions must also join
396 // See wait_for(...) above.
397 _M_complete_async();
398
399 return future_status::ready;
400 }
401 return future_status::timeout;
402 }
403
404 // Provide a result to the shared state and make it ready.
405 // Calls at most once: _M_result = __res();
406 void
407 _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
408 {
409 bool __did_set = false;
410 // all calls to this function are serialized,
411 // side-effects of invoking __res only happen once
412 call_once(_M_once, &_State_baseV2::_M_do_set, this,
413 std::__addressof(__res), std::__addressof(__did_set));
414 if (__did_set)
415 // Use release MO to synchronize with observers of the ready state.
416 _M_status._M_store_notify_all(_Status::__ready,
417 memory_order_release);
418 else if (!__ignore_failure)
419 __throw_future_error(int(future_errc::promise_already_satisfied));
420 }
421
422 // Provide a result to the shared state but delay making it ready
423 // until the calling thread exits.
424 // Calls at most once: _M_result = __res();
425 void
426 _M_set_delayed_result(function<_Ptr_type()> __res,
427 weak_ptr<_State_baseV2> __self)
428 {
429 bool __did_set = false;
430 unique_ptr<_Make_ready> __mr{new _Make_ready};
431 // all calls to this function are serialized,
432 // side-effects of invoking __res only happen once
433 call_once(_M_once, &_State_baseV2::_M_do_set, this,
434 std::__addressof(__res), std::__addressof(__did_set));
435 if (!__did_set)
436 __throw_future_error(int(future_errc::promise_already_satisfied));
437 __mr->_M_shared_state = std::move(__self);
438 __mr->_M_set();
439 __mr.release();
440 }
441
442 // Abandon this shared state.
443 void
444 _M_break_promise(_Ptr_type __res)
445 {
446 if (static_cast<bool>(__res))
447 {
448 __res->_M_error =
449 make_exception_ptr(future_error(future_errc::broken_promise));
450 // This function is only called when the last asynchronous result
451 // provider is abandoning this shared state, so noone can be
452 // trying to make the shared state ready at the same time, and
453 // we can access _M_result directly instead of through call_once.
454 _M_result.swap(__res);
455 // Use release MO to synchronize with observers of the ready state.
456 _M_status._M_store_notify_all(_Status::__ready,
457 memory_order_release);
458 }
459 }
460
461 // Called when this object is first passed to a future.
462 void
463 _M_set_retrieved_flag()
464 {
465 if (_M_retrieved.test_and_set())
466 __throw_future_error(int(future_errc::future_already_retrieved));
467 }
468
469 template<typename _Res, typename _Arg>
470 struct _Setter;
471
472 // set lvalues
473 template<typename _Res, typename _Arg>
474 struct _Setter<_Res, _Arg&>
475 {
476 // check this is only used by promise<R>::set_value(const R&)
477 // or promise<R&>::set_value(R&)
478 static_assert(is_same<_Res, _Arg&>::value // promise<R&>
479 || is_same<const _Res, _Arg>::value, // promise<R>
480 "Invalid specialisation");
481
482 // Used by std::promise to copy construct the result.
483 typename promise<_Res>::_Ptr_type operator()() const
484 {
485 _M_promise->_M_storage->_M_set(*_M_arg);
486 return std::move(_M_promise->_M_storage);
487 }
488 promise<_Res>* _M_promise;
489 _Arg* _M_arg;
490 };
491
492 // set rvalues
493 template<typename _Res>
494 struct _Setter<_Res, _Res&&>
495 {
496 // Used by std::promise to move construct the result.
497 typename promise<_Res>::_Ptr_type operator()() const
498 {
499 _M_promise->_M_storage->_M_set(std::move(*_M_arg));
500 return std::move(_M_promise->_M_storage);
501 }
502 promise<_Res>* _M_promise;
503 _Res* _M_arg;
504 };
505
506 // set void
507 template<typename _Res>
508 struct _Setter<_Res, void>
509 {
510 static_assert(is_void<_Res>::value, "Only used for promise<void>");
511
512 typename promise<_Res>::_Ptr_type operator()() const
513 { return std::move(_M_promise->_M_storage); }
514
515 promise<_Res>* _M_promise;
516 };
517
518 struct __exception_ptr_tag { };
519
520 // set exceptions
521 template<typename _Res>
522 struct _Setter<_Res, __exception_ptr_tag>
523 {
524 // Used by std::promise to store an exception as the result.
525 typename promise<_Res>::_Ptr_type operator()() const
526 {
527 _M_promise->_M_storage->_M_error = *_M_ex;
528 return std::move(_M_promise->_M_storage);
529 }
530
531 promise<_Res>* _M_promise;
532 exception_ptr* _M_ex;
533 };
534
535 template<typename _Res, typename _Arg>
536 __attribute__((__always_inline__))
537 static _Setter<_Res, _Arg&&>
538 __setter(promise<_Res>* __prom, _Arg&& __arg) noexcept
539 {
540 return _Setter<_Res, _Arg&&>{ __prom, std::__addressof(__arg) };
541 }
542
543 template<typename _Res>
544 __attribute__((__always_inline__))
545 static _Setter<_Res, __exception_ptr_tag>
546 __setter(exception_ptr& __ex, promise<_Res>* __prom) noexcept
547 {
548 return _Setter<_Res, __exception_ptr_tag>{ __prom, &__ex };
549 }
550
551 template<typename _Res>
552 __attribute__((__always_inline__))
553 static _Setter<_Res, void>
554 __setter(promise<_Res>* __prom) noexcept
555 {
556 return _Setter<_Res, void>{ __prom };
557 }
558
559 template<typename _Tp>
560 static void
561 _S_check(const shared_ptr<_Tp>& __p)
562 {
563 if (!static_cast<bool>(__p))
564 __throw_future_error((int)future_errc::no_state);
565 }
566
567 private:
568 // The function invoked with std::call_once(_M_once, ...).
569 void
570 _M_do_set(function<_Ptr_type()>* __f, bool* __did_set)
571 {
572 _Ptr_type __res = (*__f)();
573 // Notify the caller that we did try to set; if we do not throw an
574 // exception, the caller will be aware that it did set (e.g., see
575 // _M_set_result).
576 *__did_set = true;
577 _M_result.swap(__res); // nothrow
578 }
579
580 // Wait for completion of async function.
581 virtual void _M_complete_async() { }
582
583 // Return true if state corresponds to a deferred function.
584 virtual bool _M_is_deferred_future() const { return false; }
585
586 struct _Make_ready final : __at_thread_exit_elt
587 {
588 weak_ptr<_State_baseV2> _M_shared_state;
589 static void _S_run(void*);
590 void _M_set();
591 };
592 };
593
594#ifdef _GLIBCXX_ASYNC_ABI_COMPAT
595 class _State_base;
596 class _Async_state_common;
597#else
598 using _State_base = _State_baseV2;
599 class _Async_state_commonV2;
600#endif
601
602 template<typename _BoundFn,
603 typename _Res = decltype(std::declval<_BoundFn&>()())>
604 class _Deferred_state;
605
606 template<typename _BoundFn,
607 typename _Res = decltype(std::declval<_BoundFn&>()())>
608 class _Async_state_impl;
609
610 template<typename _Signature>
611 class _Task_state_base;
612
613 template<typename _Fn, typename _Alloc, typename _Signature>
614 class _Task_state;
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>
630 struct __future_base::_Result<_Res&> : __future_base::_Result_base
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<>
650 struct __future_base::_Result<void> : __future_base::_Result_base
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>
662 struct __is_location_invariant
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>
668 struct __is_location_invariant
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>
674 class __basic_future : public __future_base
675 {
676 protected:
677 typedef shared_ptr<_State_base> __state_type;
678 typedef __future_base::_Result<_Res>& __result_type;
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>
699 future_status
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>
707 future_status
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
716 __result_type
717 _M_get_result() const
718 {
719 _State_base::_S_check(_M_state);
720 _Result_base& __res = _M_state->wait();
721 if (!(__res._M_error == nullptr))
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 // _GLIBCXX_RESOLVE_LIB_DEFECTS
767 // 3458. Is shared_future intended to work with arrays or function types?
768 static_assert(!is_array<_Res>{}, "result type must not be an array");
769 static_assert(!is_function<_Res>{}, "result type must not be a function");
770 static_assert(is_destructible<_Res>{},
771 "result type must be destructible");
772
773 friend class promise<_Res>;
774 template<typename> friend class packaged_task;
775 template<typename _Fn, typename... _Args>
776 friend future<__async_result_of<_Fn, _Args...>>
777 async(launch, _Fn&&, _Args&&...);
778
779 typedef __basic_future<_Res> _Base_type;
780 typedef typename _Base_type::__state_type __state_type;
781
782 explicit
783 future(const __state_type& __state) : _Base_type(__state) { }
784
785 public:
786 constexpr future() noexcept : _Base_type() { }
787
788 /// Move constructor
789 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
790
791 // Disable copying
792 future(const future&) = delete;
793 future& operator=(const future&) = delete;
794
795 future& operator=(future&& __fut) noexcept
796 {
797 future(std::move(__fut))._M_swap(*this);
798 return *this;
799 }
800
801 /// Retrieving the value
802 _Res
803 get()
804 {
805 typename _Base_type::_Reset __reset(*this);
806 return std::move(this->_M_get_result()._M_value());
807 }
808
809 shared_future<_Res> share() noexcept;
810 };
811
812 /// Partial specialization for future<R&>
813 template<typename _Res>
814 class future<_Res&> : public __basic_future<_Res&>
815 {
816 friend class promise<_Res&>;
817 template<typename> friend class packaged_task;
818 template<typename _Fn, typename... _Args>
819 friend future<__async_result_of<_Fn, _Args...>>
820 async(launch, _Fn&&, _Args&&...);
821
822 typedef __basic_future<_Res&> _Base_type;
823 typedef typename _Base_type::__state_type __state_type;
824
825 explicit
826 future(const __state_type& __state) : _Base_type(__state) { }
827
828 public:
829 constexpr future() noexcept : _Base_type() { }
830
831 /// Move constructor
832 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
833
834 // Disable copying
835 future(const future&) = delete;
836 future& operator=(const future&) = delete;
837
838 future& operator=(future&& __fut) noexcept
839 {
840 future(std::move(__fut))._M_swap(*this);
841 return *this;
842 }
843
844 /// Retrieving the value
845 _Res&
846 get()
847 {
848 typename _Base_type::_Reset __reset(*this);
849 return this->_M_get_result()._M_get();
850 }
851
852 shared_future<_Res&> share() noexcept;
853 };
854
855 /// Explicit specialization for future<void>
856 template<>
857 class future<void> : public __basic_future<void>
858 {
859 friend class promise<void>;
860 template<typename> friend class packaged_task;
861 template<typename _Fn, typename... _Args>
862 friend future<__async_result_of<_Fn, _Args...>>
863 async(launch, _Fn&&, _Args&&...);
864
865 typedef __basic_future<void> _Base_type;
866 typedef typename _Base_type::__state_type __state_type;
867
868 explicit
869 future(const __state_type& __state) : _Base_type(__state) { }
870
871 public:
872 constexpr future() noexcept : _Base_type() { }
873
874 /// Move constructor
875 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
876
877 // Disable copying
878 future(const future&) = delete;
879 future& operator=(const future&) = delete;
880
881 future& operator=(future&& __fut) noexcept
882 {
883 future(std::move(__fut))._M_swap(*this);
884 return *this;
885 }
886
887 /// Retrieving the value
888 void
889 get()
890 {
891 typename _Base_type::_Reset __reset(*this);
892 this->_M_get_result();
893 }
894
895 shared_future<void> share() noexcept;
896 };
897
898
899 /// Primary template for shared_future.
900 template<typename _Res>
901 class shared_future : public __basic_future<_Res>
902 {
903 // _GLIBCXX_RESOLVE_LIB_DEFECTS
904 // 3458. Is shared_future intended to work with arrays or function types?
905 static_assert(!is_array<_Res>{}, "result type must not be an array");
906 static_assert(!is_function<_Res>{}, "result type must not be a function");
907 static_assert(is_destructible<_Res>{},
908 "result type must be destructible");
909
910 typedef __basic_future<_Res> _Base_type;
911
912 public:
913 constexpr shared_future() noexcept : _Base_type() { }
914
915 /// Copy constructor
916 shared_future(const shared_future& __sf) noexcept : _Base_type(__sf) { }
917
918 /// Construct from a future rvalue
919 shared_future(future<_Res>&& __uf) noexcept
920 : _Base_type(std::move(__uf))
921 { }
922
923 /// Construct from a shared_future rvalue
924 shared_future(shared_future&& __sf) noexcept
925 : _Base_type(std::move(__sf))
926 { }
927
928 shared_future& operator=(const shared_future& __sf) noexcept
929 {
930 shared_future(__sf)._M_swap(*this);
931 return *this;
932 }
933
934 shared_future& operator=(shared_future&& __sf) noexcept
935 {
936 shared_future(std::move(__sf))._M_swap(*this);
937 return *this;
938 }
939
940 /// Retrieving the value
941 const _Res&
942 get() const { return this->_M_get_result()._M_value(); }
943 };
944
945 /// Partial specialization for shared_future<R&>
946 template<typename _Res>
947 class shared_future<_Res&> : public __basic_future<_Res&>
948 {
949 typedef __basic_future<_Res&> _Base_type;
950
951 public:
952 constexpr shared_future() noexcept : _Base_type() { }
953
954 /// Copy constructor
955 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
956
957 /// Construct from a future rvalue
958 shared_future(future<_Res&>&& __uf) noexcept
959 : _Base_type(std::move(__uf))
960 { }
961
962 /// Construct from a shared_future rvalue
963 shared_future(shared_future&& __sf) noexcept
964 : _Base_type(std::move(__sf))
965 { }
966
967 shared_future& operator=(const shared_future& __sf)
968 {
969 shared_future(__sf)._M_swap(*this);
970 return *this;
971 }
972
973 shared_future& operator=(shared_future&& __sf) noexcept
974 {
975 shared_future(std::move(__sf))._M_swap(*this);
976 return *this;
977 }
978
979 /// Retrieving the value
980 _Res&
981 get() const { return this->_M_get_result()._M_get(); }
982 };
983
984 /// Explicit specialization for shared_future<void>
985 template<>
986 class shared_future<void> : public __basic_future<void>
987 {
988 typedef __basic_future<void> _Base_type;
989
990 public:
991 constexpr shared_future() noexcept : _Base_type() { }
992
993 /// Copy constructor
994 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
995
996 /// Construct from a future rvalue
997 shared_future(future<void>&& __uf) noexcept
998 : _Base_type(std::move(__uf))
999 { }
1000
1001 /// Construct from a shared_future rvalue
1002 shared_future(shared_future&& __sf) noexcept
1003 : _Base_type(std::move(__sf))
1004 { }
1005
1006 shared_future& operator=(const shared_future& __sf)
1007 {
1008 shared_future(__sf)._M_swap(*this);
1009 return *this;
1010 }
1011
1012 shared_future& operator=(shared_future&& __sf) noexcept
1013 {
1014 shared_future(std::move(__sf))._M_swap(*this);
1015 return *this;
1016 }
1017
1018 // Retrieving the value
1019 void
1020 get() const { this->_M_get_result(); }
1021 };
1022
1023 // Now we can define the protected __basic_future constructors.
1024 template<typename _Res>
1025 inline __basic_future<_Res>::
1026 __basic_future(const shared_future<_Res>& __sf) noexcept
1027 : _M_state(__sf._M_state)
1028 { }
1029
1030 template<typename _Res>
1031 inline __basic_future<_Res>::
1032 __basic_future(shared_future<_Res>&& __sf) noexcept
1033 : _M_state(std::move(__sf._M_state))
1034 { }
1035
1036 template<typename _Res>
1037 inline __basic_future<_Res>::
1038 __basic_future(future<_Res>&& __uf) noexcept
1039 : _M_state(std::move(__uf._M_state))
1040 { }
1041
1042 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1043 // 2556. Wide contract for future::share()
1044 template<typename _Res>
1045 inline shared_future<_Res>
1046 future<_Res>::share() noexcept
1047 { return shared_future<_Res>(std::move(*this)); }
1048
1049 template<typename _Res>
1050 inline shared_future<_Res&>
1051 future<_Res&>::share() noexcept
1052 { return shared_future<_Res&>(std::move(*this)); }
1053
1054 inline shared_future<void>
1055 future<void>::share() noexcept
1056 { return shared_future<void>(std::move(*this)); }
1057
1058 /// Primary template for promise
1059 template<typename _Res>
1060 class promise
1061 {
1062 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1063 // 3466: Specify the requirements for promise/future/[...] consistently
1064 static_assert(!is_array<_Res>{}, "result type must not be an array");
1065 static_assert(!is_function<_Res>{}, "result type must not be a function");
1066 static_assert(is_destructible<_Res>{},
1067 "result type must be destructible");
1068
1069 typedef __future_base::_State_base _State;
1070 typedef __future_base::_Result<_Res> _Res_type;
1071 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1072 template<typename, typename> friend struct _State::_Setter;
1073 friend _State;
1074
1075 shared_ptr<_State> _M_future;
1076 _Ptr_type _M_storage;
1077
1078 public:
1079 promise()
1080 : _M_future(std::make_shared<_State>()),
1081 _M_storage(new _Res_type())
1082 { }
1083
1084 promise(promise&& __rhs) noexcept
1085 : _M_future(std::move(__rhs._M_future)),
1086 _M_storage(std::move(__rhs._M_storage))
1087 { }
1088
1089 template<typename _Allocator>
1090 promise(allocator_arg_t, const _Allocator& __a)
1091 : _M_future(std::allocate_shared<_State>(__a)),
1092 _M_storage(__future_base::_S_allocate_result<_Res>(__a))
1093 { }
1094
1095 template<typename _Allocator>
1096 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1097 : _M_future(std::move(__rhs._M_future)),
1098 _M_storage(std::move(__rhs._M_storage))
1099 { }
1100
1101 promise(const promise&) = delete;
1102
1103 ~promise()
1104 {
1105 if (static_cast<bool>(_M_future) && !_M_future.unique())
1106 _M_future->_M_break_promise(std::move(_M_storage));
1107 }
1108
1109 // Assignment
1110 promise&
1111 operator=(promise&& __rhs) noexcept
1112 {
1113 promise(std::move(__rhs)).swap(*this);
1114 return *this;
1115 }
1116
1117 promise& operator=(const promise&) = delete;
1118
1119 void
1120 swap(promise& __rhs) noexcept
1121 {
1122 _M_future.swap(__rhs._M_future);
1123 _M_storage.swap(__rhs._M_storage);
1124 }
1125
1126 // Retrieving the result
1127 future<_Res>
1128 get_future()
1129 { return future<_Res>(_M_future); }
1130
1131 // Setting the result
1132 void
1133 set_value(const _Res& __r)
1134 { _M_state()._M_set_result(_State::__setter(this, __r)); }
1135
1136 void
1137 set_value(_Res&& __r)
1138 { _M_state()._M_set_result(_State::__setter(this, std::move(__r))); }
1139
1140 void
1141 set_exception(exception_ptr __p)
1142 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1143
1144 void
1145 set_value_at_thread_exit(const _Res& __r)
1146 {
1147 _M_state()._M_set_delayed_result(_State::__setter(this, __r),
1148 _M_future);
1149 }
1150
1151 void
1152 set_value_at_thread_exit(_Res&& __r)
1153 {
1154 _M_state()._M_set_delayed_result(
1155 _State::__setter(this, std::move(__r)), _M_future);
1156 }
1157
1158 void
1159 set_exception_at_thread_exit(exception_ptr __p)
1160 {
1161 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1162 _M_future);
1163 }
1164
1165 private:
1166 _State&
1167 _M_state()
1168 {
1169 __future_base::_State_base::_S_check(_M_future);
1170 return *_M_future;
1171 }
1172 };
1173
1174 template<typename _Res>
1175 inline void
1176 swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
1177 { __x.swap(__y); }
1178
1179 template<typename _Res, typename _Alloc>
1180 struct uses_allocator<promise<_Res>, _Alloc>
1181 : public true_type { };
1182
1183
1184 /// Partial specialization for promise<R&>
1185 template<typename _Res>
1186 class promise<_Res&>
1187 {
1188 typedef __future_base::_State_base _State;
1189 typedef __future_base::_Result<_Res&> _Res_type;
1190 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1191 template<typename, typename> friend struct _State::_Setter;
1192 friend _State;
1193
1194 shared_ptr<_State> _M_future;
1195 _Ptr_type _M_storage;
1196
1197 public:
1198 promise()
1199 : _M_future(std::make_shared<_State>()),
1200 _M_storage(new _Res_type())
1201 { }
1202
1203 promise(promise&& __rhs) noexcept
1204 : _M_future(std::move(__rhs._M_future)),
1205 _M_storage(std::move(__rhs._M_storage))
1206 { }
1207
1208 template<typename _Allocator>
1209 promise(allocator_arg_t, const _Allocator& __a)
1210 : _M_future(std::allocate_shared<_State>(__a)),
1211 _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
1212 { }
1213
1214 template<typename _Allocator>
1215 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1216 : _M_future(std::move(__rhs._M_future)),
1217 _M_storage(std::move(__rhs._M_storage))
1218 { }
1219
1220 promise(const promise&) = delete;
1221
1222 ~promise()
1223 {
1224 if (static_cast<bool>(_M_future) && !_M_future.unique())
1225 _M_future->_M_break_promise(std::move(_M_storage));
1226 }
1227
1228 // Assignment
1229 promise&
1230 operator=(promise&& __rhs) noexcept
1231 {
1232 promise(std::move(__rhs)).swap(*this);
1233 return *this;
1234 }
1235
1236 promise& operator=(const promise&) = delete;
1237
1238 void
1239 swap(promise& __rhs) noexcept
1240 {
1241 _M_future.swap(__rhs._M_future);
1242 _M_storage.swap(__rhs._M_storage);
1243 }
1244
1245 // Retrieving the result
1246 future<_Res&>
1247 get_future()
1248 { return future<_Res&>(_M_future); }
1249
1250 // Setting the result
1251 void
1252 set_value(_Res& __r)
1253 { _M_state()._M_set_result(_State::__setter(this, __r)); }
1254
1255 void
1256 set_exception(exception_ptr __p)
1257 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1258
1259 void
1260 set_value_at_thread_exit(_Res& __r)
1261 {
1262 _M_state()._M_set_delayed_result(_State::__setter(this, __r),
1263 _M_future);
1264 }
1265
1266 void
1267 set_exception_at_thread_exit(exception_ptr __p)
1268 {
1269 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1270 _M_future);
1271 }
1272
1273 private:
1274 _State&
1275 _M_state()
1276 {
1277 __future_base::_State_base::_S_check(_M_future);
1278 return *_M_future;
1279 }
1280 };
1281
1282 /// Explicit specialization for promise<void>
1283 template<>
1284 class promise<void>
1285 {
1286 typedef __future_base::_State_base _State;
1287 typedef __future_base::_Result<void> _Res_type;
1288 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1289 template<typename, typename> friend struct _State::_Setter;
1290 friend _State;
1291
1292 shared_ptr<_State> _M_future;
1293 _Ptr_type _M_storage;
1294
1295 public:
1296 promise()
1297 : _M_future(std::make_shared<_State>()),
1298 _M_storage(new _Res_type())
1299 { }
1300
1301 promise(promise&& __rhs) noexcept
1302 : _M_future(std::move(__rhs._M_future)),
1303 _M_storage(std::move(__rhs._M_storage))
1304 { }
1305
1306 template<typename _Allocator>
1307 promise(allocator_arg_t, const _Allocator& __a)
1308 : _M_future(std::allocate_shared<_State>(__a)),
1309 _M_storage(__future_base::_S_allocate_result<void>(__a))
1310 { }
1311
1312 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1313 // 2095. missing constructors needed for uses-allocator construction
1314 template<typename _Allocator>
1315 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1316 : _M_future(std::move(__rhs._M_future)),
1317 _M_storage(std::move(__rhs._M_storage))
1318 { }
1319
1320 promise(const promise&) = delete;
1321
1322 ~promise()
1323 {
1324 if (static_cast<bool>(_M_future) && !_M_future.unique())
1325 _M_future->_M_break_promise(std::move(_M_storage));
1326 }
1327
1328 // Assignment
1329 promise&
1330 operator=(promise&& __rhs) noexcept
1331 {
1332 promise(std::move(__rhs)).swap(*this);
1333 return *this;
1334 }
1335
1336 promise& operator=(const promise&) = delete;
1337
1338 void
1339 swap(promise& __rhs) noexcept
1340 {
1341 _M_future.swap(__rhs._M_future);
1342 _M_storage.swap(__rhs._M_storage);
1343 }
1344
1345 // Retrieving the result
1346 future<void>
1347 get_future()
1348 { return future<void>(_M_future); }
1349
1350 // Setting the result
1351 void
1352 set_value()
1353 { _M_state()._M_set_result(_State::__setter(this)); }
1354
1355 void
1356 set_exception(exception_ptr __p)
1357 { _M_state()._M_set_result(_State::__setter(__p, this)); }
1358
1359 void
1360 set_value_at_thread_exit()
1361 { _M_state()._M_set_delayed_result(_State::__setter(this), _M_future); }
1362
1363 void
1364 set_exception_at_thread_exit(exception_ptr __p)
1365 {
1366 _M_state()._M_set_delayed_result(_State::__setter(__p, this),
1367 _M_future);
1368 }
1369
1370 private:
1371 _State&
1372 _M_state()
1373 {
1374 __future_base::_State_base::_S_check(_M_future);
1375 return *_M_future;
1376 }
1377 };
1378
1379 template<typename _Ptr_type, typename _Fn, typename _Res>
1380 struct __future_base::_Task_setter
1381 {
1382 // Invoke the function and provide the result to the caller.
1383 _Ptr_type operator()() const
1384 {
1385 __try
1386 {
1387 (*_M_result)->_M_set((*_M_fn)());
1388 }
1389 __catch(const __cxxabiv1::__forced_unwind&)
1390 {
1391 __throw_exception_again; // will cause broken_promise
1392 }
1393 __catch(...)
1394 {
1395 (*_M_result)->_M_error = current_exception();
1396 }
1397 return std::move(*_M_result);
1398 }
1399 _Ptr_type* _M_result;
1400 _Fn* _M_fn;
1401 };
1402
1403 template<typename _Ptr_type, typename _Fn>
1404 struct __future_base::_Task_setter<_Ptr_type, _Fn, void>
1405 {
1406 _Ptr_type operator()() const
1407 {
1408 __try
1409 {
1410 (*_M_fn)();
1411 }
1412 __catch(const __cxxabiv1::__forced_unwind&)
1413 {
1414 __throw_exception_again; // will cause broken_promise
1415 }
1416 __catch(...)
1417 {
1418 (*_M_result)->_M_error = current_exception();
1419 }
1420 return std::move(*_M_result);
1421 }
1422 _Ptr_type* _M_result;
1423 _Fn* _M_fn;
1424 };
1425
1426 // Holds storage for a packaged_task's result.
1427 template<typename _Res, typename... _Args>
1428 struct __future_base::_Task_state_base<_Res(_Args...)>
1429 : __future_base::_State_base
1430 {
1431 typedef _Res _Res_type;
1432
1433 template<typename _Alloc>
1434 _Task_state_base(const _Alloc& __a)
1435 : _M_result(_S_allocate_result<_Res>(__a))
1436 { }
1437
1438 // Invoke the stored task and make the state ready.
1439 virtual void
1440 _M_run(_Args&&... __args) = 0;
1441
1442 // Invoke the stored task and make the state ready at thread exit.
1443 virtual void
1444 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base>) = 0;
1445
1446 virtual shared_ptr<_Task_state_base>
1447 _M_reset() = 0;
1448
1449 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1450 _Ptr_type _M_result;
1451 };
1452
1453 // Holds a packaged_task's stored task.
1454 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1455 struct __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)> final
1456 : __future_base::_Task_state_base<_Res(_Args...)>
1457 {
1458 template<typename _Fn2>
1459 _Task_state(_Fn2&& __fn, const _Alloc& __a)
1460 : _Task_state_base<_Res(_Args...)>(__a),
1461 _M_impl(std::forward<_Fn2>(__fn), __a)
1462 { }
1463
1464 private:
1465 virtual void
1466 _M_run(_Args&&... __args)
1467 {
1468 auto __boundfn = [&] () -> _Res {
1469 return std::__invoke_r<_Res>(_M_impl._M_fn,
1470 std::forward<_Args>(__args)...);
1471 };
1472 this->_M_set_result(_S_task_setter(this->_M_result, __boundfn));
1473 }
1474
1475 virtual void
1476 _M_run_delayed(_Args&&... __args, weak_ptr<_State_base> __self)
1477 {
1478 auto __boundfn = [&] () -> _Res {
1479 return std::__invoke_r<_Res>(_M_impl._M_fn,
1480 std::forward<_Args>(__args)...);
1481 };
1482 this->_M_set_delayed_result(_S_task_setter(this->_M_result, __boundfn),
1483 std::move(__self));
1484 }
1485
1486 virtual shared_ptr<_Task_state_base<_Res(_Args...)>>
1487 _M_reset();
1488
1489 struct _Impl : _Alloc
1490 {
1491 template<typename _Fn2>
1492 _Impl(_Fn2&& __fn, const _Alloc& __a)
1493 : _Alloc(__a), _M_fn(std::forward<_Fn2>(__fn)) { }
1494 _Fn _M_fn;
1495 } _M_impl;
1496 };
1497
1498 template<typename _Signature, typename _Fn,
1499 typename _Alloc = std::allocator<int>>
1500 static shared_ptr<__future_base::_Task_state_base<_Signature>>
1501 __create_task_state(_Fn&& __fn, const _Alloc& __a = _Alloc())
1502 {
1503 typedef typename decay<_Fn>::type _Fn2;
1504 typedef __future_base::_Task_state<_Fn2, _Alloc, _Signature> _State;
1505 return std::allocate_shared<_State>(__a, std::forward<_Fn>(__fn), __a);
1506 }
1507
1508 template<typename _Fn, typename _Alloc, typename _Res, typename... _Args>
1509 shared_ptr<__future_base::_Task_state_base<_Res(_Args...)>>
1510 __future_base::_Task_state<_Fn, _Alloc, _Res(_Args...)>::_M_reset()
1511 {
1512 return __create_task_state<_Res(_Args...)>(std::move(_M_impl._M_fn),
1513 static_cast<_Alloc&>(_M_impl));
1514 }
1515
1516 /// packaged_task
1517 template<typename _Res, typename... _ArgTypes>
1518 class packaged_task<_Res(_ArgTypes...)>
1519 {
1520 typedef __future_base::_Task_state_base<_Res(_ArgTypes...)> _State_type;
1521 shared_ptr<_State_type> _M_state;
1522
1523 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1524 // 3039. Unnecessary decay in thread and packaged_task
1525 template<typename _Fn, typename _Fn2 = __remove_cvref_t<_Fn>>
1526 using __not_same
1527 = typename enable_if<!is_same<packaged_task, _Fn2>::value>::type;
1528
1529 public:
1530 // Construction and destruction
1531 packaged_task() noexcept { }
1532
1533 template<typename _Fn, typename = __not_same<_Fn>>
1534 explicit
1535 packaged_task(_Fn&& __fn)
1536 : _M_state(
1537 __create_task_state<_Res(_ArgTypes...)>(std::forward<_Fn>(__fn)))
1538 { }
1539
1540#if __cplusplus < 201703L
1541 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1542 // 2097. packaged_task constructors should be constrained
1543 // 2407. [this constructor should not be] explicit
1544 // 2921. packaged_task and type-erased allocators
1545 template<typename _Fn, typename _Alloc, typename = __not_same<_Fn>>
1546 packaged_task(allocator_arg_t, const _Alloc& __a, _Fn&& __fn)
1547 : _M_state(__create_task_state<_Res(_ArgTypes...)>(
1548 std::forward<_Fn>(__fn), __a))
1549 { }
1550
1551 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1552 // 2095. missing constructors needed for uses-allocator construction
1553 template<typename _Allocator>
1554 packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
1555 { }
1556
1557 template<typename _Allocator>
1558 packaged_task(allocator_arg_t, const _Allocator&,
1559 const packaged_task&) = delete;
1560
1561 template<typename _Allocator>
1562 packaged_task(allocator_arg_t, const _Allocator&,
1563 packaged_task&& __other) noexcept
1564 { this->swap(__other); }
1565#endif
1566
1567 ~packaged_task()
1568 {
1569 if (static_cast<bool>(_M_state) && !_M_state.unique())
1570 _M_state->_M_break_promise(std::move(_M_state->_M_result));
1571 }
1572
1573 // No copy
1574 packaged_task(const packaged_task&) = delete;
1575 packaged_task& operator=(const packaged_task&) = delete;
1576
1577 // Move support
1578 packaged_task(packaged_task&& __other) noexcept
1579 { this->swap(__other); }
1580
1581 packaged_task& operator=(packaged_task&& __other) noexcept
1582 {
1583 packaged_task(std::move(__other)).swap(*this);
1584 return *this;
1585 }
1586
1587 void
1588 swap(packaged_task& __other) noexcept
1589 { _M_state.swap(__other._M_state); }
1590
1591 bool
1592 valid() const noexcept
1593 { return static_cast<bool>(_M_state); }
1594
1595 // Result retrieval
1596 future<_Res>
1597 get_future()
1598 { return future<_Res>(_M_state); }
1599
1600 // Execution
1601 void
1602 operator()(_ArgTypes... __args)
1603 {
1604 __future_base::_State_base::_S_check(_M_state);
1605 _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
1606 }
1607
1608 void
1609 make_ready_at_thread_exit(_ArgTypes... __args)
1610 {
1611 __future_base::_State_base::_S_check(_M_state);
1612 _M_state->_M_run_delayed(std::forward<_ArgTypes>(__args)..., _M_state);
1613 }
1614
1615 void
1616 reset()
1617 {
1618 __future_base::_State_base::_S_check(_M_state);
1619 packaged_task __tmp;
1620 __tmp._M_state = _M_state;
1621 _M_state = _M_state->_M_reset();
1622 }
1623 };
1624
1625 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1626 // 3117. Missing packaged_task deduction guides
1627#if __cpp_deduction_guides >= 201606
1628 template<typename _Res, typename... _ArgTypes>
1629 packaged_task(_Res(*)(_ArgTypes...)) -> packaged_task<_Res(_ArgTypes...)>;
1630
1631 template<typename _Fun, typename _Signature = typename
1632 __function_guide_helper<decltype(&_Fun::operator())>::type>
1633 packaged_task(_Fun) -> packaged_task<_Signature>;
1634#endif
1635
1636 /// swap
1637 template<typename _Res, typename... _ArgTypes>
1638 inline void
1639 swap(packaged_task<_Res(_ArgTypes...)>& __x,
1640 packaged_task<_Res(_ArgTypes...)>& __y) noexcept
1641 { __x.swap(__y); }
1642
1643#if __cplusplus < 201703L
1644 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1645 // 2976. Dangling uses_allocator specialization for packaged_task
1646 template<typename _Res, typename _Alloc>
1647 struct uses_allocator<packaged_task<_Res>, _Alloc>
1648 : public true_type { };
1649#endif
1650
1651 // Shared state created by std::async().
1652 // Holds a deferred function and storage for its result.
1653 template<typename _BoundFn, typename _Res>
1654 class __future_base::_Deferred_state final
1655 : public __future_base::_State_base
1656 {
1657 public:
1658 template<typename... _Args>
1659 explicit
1660 _Deferred_state(_Args&&... __args)
1661 : _M_result(new _Result<_Res>()),
1662 _M_fn{{std::forward<_Args>(__args)...}}
1663 { }
1664
1665 private:
1666 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1667 _Ptr_type _M_result;
1668 _BoundFn _M_fn;
1669
1670 // Run the deferred function.
1671 virtual void
1672 _M_complete_async()
1673 {
1674 // Multiple threads can call a waiting function on the future and
1675 // reach this point at the same time. The call_once in _M_set_result
1676 // ensures only the first one run the deferred function, stores the
1677 // result in _M_result, swaps that with the base _M_result and makes
1678 // the state ready. Tell _M_set_result to ignore failure so all later
1679 // calls do nothing.
1680 _M_set_result(_S_task_setter(_M_result, _M_fn), true);
1681 }
1682
1683 // Caller should check whether the state is ready first, because this
1684 // function will return true even after the deferred function has run.
1685 virtual bool _M_is_deferred_future() const { return true; }
1686 };
1687
1688 // Common functionality hoisted out of the _Async_state_impl template.
1689 class __future_base::_Async_state_commonV2
1690 : public __future_base::_State_base
1691 {
1692 protected:
1693 ~_Async_state_commonV2() = default;
1694
1695 // Make waiting functions block until the thread completes, as if joined.
1696 //
1697 // This function is used by wait() to satisfy the first requirement below
1698 // and by wait_for() / wait_until() to satisfy the second.
1699 //
1700 // [futures.async]:
1701 //
1702 // - a call to a waiting function on an asynchronous return object that
1703 // shares the shared state created by this async call shall block until
1704 // the associated thread has completed, as if joined, or else time out.
1705 //
1706 // - the associated thread completion synchronizes with the return from
1707 // the first function that successfully detects the ready status of the
1708 // shared state or with the return from the last function that releases
1709 // the shared state, whichever happens first.
1710 virtual void _M_complete_async() { _M_join(); }
1711
1712 void _M_join() { std::call_once(_M_once, &thread::join, &_M_thread); }
1713
1714 thread _M_thread;
1715 once_flag _M_once;
1716 };
1717
1718 // Shared state created by std::async().
1719 // Starts a new thread that runs a function and makes the shared state ready.
1720 template<typename _BoundFn, typename _Res>
1721 class __future_base::_Async_state_impl final
1722 : public __future_base::_Async_state_commonV2
1723 {
1724 public:
1725 template<typename... _Args>
1726 explicit
1727 _Async_state_impl(_Args&&... __args)
1728 : _M_result(new _Result<_Res>()),
1729 _M_fn{{std::forward<_Args>(__args)...}}
1730 {
1731 _M_thread = std::thread{&_Async_state_impl::_M_run, this};
1732 }
1733
1734 // Must not destroy _M_result and _M_fn until the thread finishes.
1735 // Call join() directly rather than through _M_join() because no other
1736 // thread can be referring to this state if it is being destroyed.
1737 ~_Async_state_impl()
1738 {
1739 if (_M_thread.joinable())
1740 _M_thread.join();
1741 }
1742
1743 private:
1744 void
1745 _M_run()
1746 {
1747 __try
1748 {
1749 _M_set_result(_S_task_setter(_M_result, _M_fn));
1750 }
1751 __catch (const __cxxabiv1::__forced_unwind&)
1752 {
1753 // make the shared state ready on thread cancellation
1754 if (static_cast<bool>(_M_result))
1755 this->_M_break_promise(std::move(_M_result));
1756 __throw_exception_again;
1757 }
1758 }
1759
1760 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1761 _Ptr_type _M_result;
1762 _BoundFn _M_fn;
1763 };
1764
1765
1766 /// async
1767 template<typename _Fn, typename... _Args>
1768 _GLIBCXX_NODISCARD future<__async_result_of<_Fn, _Args...>>
1769 async(launch __policy, _Fn&& __fn, _Args&&... __args)
1770 {
1771 using _Wr = std::thread::_Call_wrapper<_Fn, _Args...>;
1772 using _As = __future_base::_Async_state_impl<_Wr>;
1773 using _Ds = __future_base::_Deferred_state<_Wr>;
1774
1775 std::shared_ptr<__future_base::_State_base> __state;
1776 if ((__policy & launch::async) == launch::async)
1777 {
1778 __try
1779 {
1780 __state = std::make_shared<_As>(std::forward<_Fn>(__fn),
1781 std::forward<_Args>(__args)...);
1782 }
1783#if __cpp_exceptions
1784 catch(const system_error& __e)
1785 {
1786 if (__e.code() != errc::resource_unavailable_try_again
1787 || (__policy & launch::deferred) != launch::deferred)
1788 throw;
1789 }
1790#endif
1791 }
1792 if (!__state)
1793 {
1794 __state = std::make_shared<_Ds>(std::forward<_Fn>(__fn),
1795 std::forward<_Args>(__args)...);
1796 }
1797 return future<__async_result_of<_Fn, _Args...>>(std::move(__state));
1798 }
1799
1800 /// async, potential overload
1801 template<typename _Fn, typename... _Args>
1802 _GLIBCXX_NODISCARD inline future<__async_result_of<_Fn, _Args...>>
1803 async(_Fn&& __fn, _Args&&... __args)
1804 {
1805 return std::async(launch::async|launch::deferred,
1806 std::forward<_Fn>(__fn),
1807 std::forward<_Args>(__args)...);
1808 }
1809
1810#endif // _GLIBCXX_ASYNC_ABI_COMPAT
1811#endif // _GLIBCXX_HAS_GTHREADS
1812
1813 /// @} group futures
1814_GLIBCXX_END_NAMESPACE_VERSION
1815} // namespace
1816
1817#endif // C++11
1818
1819#endif // _GLIBCXX_FUTURE