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