libstdc++: future Source File

libstdc++

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