libstdc++

future
Go to the documentation of this file.
1 // <future> -*- C++ -*-
2
3 // Copyright (C) 2009-2013 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 <functional>
39 #include <mutex>
40 #include <thread>
41 #include <condition_variable>
42 #include <system_error>
43 #include <atomic>
44 #include <bits/functexcept.h>
45 #include <bits/unique_ptr.h>
46 #include <bits/shared_ptr.h>
47 #include <bits/uses_allocator.h>
48 #include <bits/alloc_traits.h>
49
50 namespace std _GLIBCXX_VISIBILITY(default)
51 {
52 _GLIBCXX_BEGIN_NAMESPACE_VERSION
53
54 /**
55 * @defgroup futures Futures
56 * @ingroup concurrency
57 *
58 * Classes for futures support.
59 * @{
60 */
61
62 /// Error code for futures
63 enum class future_errc
64 {
65 future_already_retrieved = 1,
66 promise_already_satisfied,
67 no_state,
68 broken_promise
69 };
70
71 /// Specialization.
72 template<>
73 struct is_error_code_enum<future_errc> : public true_type { };
74
75 /// Points to a statically-allocated object derived from error_category.
76 const error_category&
77 future_category() noexcept;
78
79 /// Overload for make_error_code.
80 inline error_code
81 make_error_code(future_errc __errc) noexcept
82 { return error_code(static_cast<int>(__errc), future_category()); }
83
84 /// Overload for make_error_condition.
85 inline error_condition
86 make_error_condition(future_errc __errc) noexcept
87 { return error_condition(static_cast<int>(__errc), future_category()); }
88
89 /**
90 * @brief Exception type thrown by futures.
91 * @ingroup exceptions
92 */
93 class future_error : public logic_error
94 {
95 error_code _M_code;
96
97 public:
98 explicit future_error(error_code __ec)
99 : logic_error("std::future_error"), _M_code(__ec)
100 { }
101
102 virtual ~future_error() noexcept;
103
104 virtual const char*
105 what() const noexcept;
106
107 const error_code&
108 code() const noexcept { return _M_code; }
109 };
110
111 // Forward declarations.
112 template<typename _Res>
113 class future;
114
115 template<typename _Res>
116 class shared_future;
117
118 template<typename _Signature>
119 class packaged_task;
120
121 template<typename _Res>
122 class promise;
123
124 /// Launch code for futures
125 enum class launch
126 {
127 async = 1,
128 deferred = 2
129 };
130
131 constexpr launch operator&(launch __x, launch __y)
132 {
133 return static_cast<launch>(
134 static_cast<int>(__x) & static_cast<int>(__y));
135 }
136
137 constexpr launch operator|(launch __x, launch __y)
138 {
139 return static_cast<launch>(
140 static_cast<int>(__x) | static_cast<int>(__y));
141 }
142
143 constexpr launch operator^(launch __x, launch __y)
144 {
145 return static_cast<launch>(
146 static_cast<int>(__x) ^ static_cast<int>(__y));
147 }
148
149 constexpr launch operator~(launch __x)
150 { return static_cast<launch>(~static_cast<int>(__x)); }
151
152 inline launch& operator&=(launch& __x, launch __y)
153 { return __x = __x & __y; }
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 /// Status code for futures
162 enum class future_status
163 {
164 ready,
165 timeout,
166 deferred
167 };
168
169 template<typename _Fn, typename... _Args>
170 future<typename result_of<_Fn(_Args...)>::type>
171 async(launch __policy, _Fn&& __fn, _Args&&... __args);
172
173 template<typename _Fn, typename... _Args>
174 future<typename result_of<_Fn(_Args...)>::type>
175 async(_Fn&& __fn, _Args&&... __args);
176
177 #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) \
178 && (ATOMIC_INT_LOCK_FREE > 1)
179
180 /// Base class and enclosing scope.
181 struct __future_base
182 {
183 /// Base class for results.
184 struct _Result_base
185 {
186 exception_ptr _M_error;
187
188 _Result_base(const _Result_base&) = delete;
189 _Result_base& operator=(const _Result_base&) = delete;
190
191 // _M_destroy() allows derived classes to control deallocation
192 virtual void _M_destroy() = 0;
193
194 struct _Deleter
195 {
196 void operator()(_Result_base* __fr) const { __fr->_M_destroy(); }
197 };
198
199 protected:
200 _Result_base();
201 virtual ~_Result_base();
202 };
203
204 /// Result.
205 template<typename _Res>
206 struct _Result : _Result_base
207 {
208 private:
209 typedef alignment_of<_Res> __a_of;
210 typedef aligned_storage<sizeof(_Res), __a_of::value> __align_storage;
211 typedef typename __align_storage::type __align_type;
212
213 __align_type _M_storage;
214 bool _M_initialized;
215
216 public:
217 _Result() noexcept : _M_initialized() { }
218
219 ~_Result()
220 {
221 if (_M_initialized)
222 _M_value().~_Res();
223 }
224
225 // Return lvalue, future will add const or rvalue-reference
226 _Res&
227 _M_value() noexcept { return *static_cast<_Res*>(_M_addr()); }
228
229 void
230 _M_set(const _Res& __res)
231 {
232 ::new (_M_addr()) _Res(__res);
233 _M_initialized = true;
234 }
235
236 void
237 _M_set(_Res&& __res)
238 {
239 ::new (_M_addr()) _Res(std::move(__res));
240 _M_initialized = true;
241 }
242
243 private:
244 void _M_destroy() { delete this; }
245
246 void* _M_addr() noexcept { return static_cast<void*>(&_M_storage); }
247 };
248
249 /// A unique_ptr based on the instantiating type.
250 template<typename _Res>
251 using _Ptr = unique_ptr<_Res, _Result_base::_Deleter>;
252
253 /// Result_alloc.
254 template<typename _Res, typename _Alloc>
255 struct _Result_alloc final : _Result<_Res>, _Alloc
256 {
257 typedef typename allocator_traits<_Alloc>::template
258 rebind_alloc<_Result_alloc> __allocator_type;
259
260 explicit
261 _Result_alloc(const _Alloc& __a) : _Result<_Res>(), _Alloc(__a)
262 { }
263
264 private:
265 void _M_destroy()
266 {
267 typedef allocator_traits<__allocator_type> __traits;
268 __allocator_type __a(*this);
269 __traits::destroy(__a, this);
270 __traits::deallocate(__a, this, 1);
271 }
272 };
273
274 template<typename _Res, typename _Allocator>
275 static _Ptr<_Result_alloc<_Res, _Allocator>>
276 _S_allocate_result(const _Allocator& __a)
277 {
278 typedef _Result_alloc<_Res, _Allocator> __result_type;
279 typedef allocator_traits<typename __result_type::__allocator_type>
280 __traits;
281 typename __traits::allocator_type __a2(__a);
282 __result_type* __p = __traits::allocate(__a2, 1);
283 __try
284 {
285 __traits::construct(__a2, __p, __a);
286 }
287 __catch(...)
288 {
289 __traits::deallocate(__a2, __p, 1);
290 __throw_exception_again;
291 }
292 return _Ptr<__result_type>(__p);
293 }
294
295
296 /// Base class for state between a promise and one or more
297 /// associated futures.
298 class _State_base
299 {
300 typedef _Ptr<_Result_base> _Ptr_type;
301
302 _Ptr_type _M_result;
303 mutex _M_mutex;
304 condition_variable _M_cond;
305 atomic_flag _M_retrieved;
306 once_flag _M_once;
307
308 public:
309 _State_base() noexcept : _M_result(), _M_retrieved(ATOMIC_FLAG_INIT) { }
310 _State_base(const _State_base&) = delete;
311 _State_base& operator=(const _State_base&) = delete;
312 virtual ~_State_base();
313
314 _Result_base&
315 wait()
316 {
317 _M_run_deferred();
318 unique_lock<mutex> __lock(_M_mutex);
319 _M_cond.wait(__lock, [&] { return _M_ready(); });
320 return *_M_result;
321 }
322
323 template<typename _Rep, typename _Period>
324 future_status
325 wait_for(const chrono::duration<_Rep, _Period>& __rel)
326 {
327 unique_lock<mutex> __lock(_M_mutex);
328 if (_M_cond.wait_for(__lock, __rel, [&] { return _M_ready(); }))
329 return future_status::ready;
330 return future_status::timeout;
331 }
332
333 template<typename _Clock, typename _Duration>
334 future_status
335 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
336 {
337 unique_lock<mutex> __lock(_M_mutex);
338 if (_M_cond.wait_until(__lock, __abs, [&] { return _M_ready(); }))
339 return future_status::ready;
340 return future_status::timeout;
341 }
342
343 void
344 _M_set_result(function<_Ptr_type()> __res, bool __ignore_failure = false)
345 {
346 bool __set = __ignore_failure;
347 // all calls to this function are serialized,
348 // side-effects of invoking __res only happen once
349 call_once(_M_once, &_State_base::_M_do_set, this, ref(__res),
350 ref(__set));
351 if (!__set)
352 __throw_future_error(int(future_errc::promise_already_satisfied));
353 }
354
355 void
356 _M_break_promise(_Ptr_type __res)
357 {
358 if (static_cast<bool>(__res))
359 {
360 error_code __ec(make_error_code(future_errc::broken_promise));
361 __res->_M_error = copy_exception(future_error(__ec));
362 {
363 lock_guard<mutex> __lock(_M_mutex);
364 _M_result.swap(__res);
365 }
366 _M_cond.notify_all();
367 }
368 }
369
370 // Called when this object is passed to a future.
371 void
372 _M_set_retrieved_flag()
373 {
374 if (_M_retrieved.test_and_set())
375 __throw_future_error(int(future_errc::future_already_retrieved));
376 }
377
378 template<typename _Res, typename _Arg>
379 struct _Setter;
380
381 // set lvalues
382 template<typename _Res, typename _Arg>
383 struct _Setter<_Res, _Arg&>
384 {
385 // check this is only used by promise<R>::set_value(const R&)
386 // or promise<R>::set_value(R&)
387 static_assert(is_same<_Res, _Arg&>::value // promise<R&>
388 || is_same<const _Res, _Arg>::value, // promise<R>
389 "Invalid specialisation");
390
391 typename promise<_Res>::_Ptr_type operator()()
392 {
393 _State_base::_S_check(_M_promise->_M_future);
394 _M_promise->_M_storage->_M_set(_M_arg);
395 return std::move(_M_promise->_M_storage);
396 }
397 promise<_Res>* _M_promise;
398 _Arg& _M_arg;
399 };
400
401 // set rvalues
402 template<typename _Res>
403 struct _Setter<_Res, _Res&&>
404 {
405 typename promise<_Res>::_Ptr_type operator()()
406 {
407 _State_base::_S_check(_M_promise->_M_future);
408 _M_promise->_M_storage->_M_set(std::move(_M_arg));
409 return std::move(_M_promise->_M_storage);
410 }
411 promise<_Res>* _M_promise;
412 _Res& _M_arg;
413 };
414
415 struct __exception_ptr_tag { };
416
417 // set exceptions
418 template<typename _Res>
419 struct _Setter<_Res, __exception_ptr_tag>
420 {
421 typename promise<_Res>::_Ptr_type operator()()
422 {
423 _State_base::_S_check(_M_promise->_M_future);
424 _M_promise->_M_storage->_M_error = _M_ex;
425 return std::move(_M_promise->_M_storage);
426 }
427
428 promise<_Res>* _M_promise;
429 exception_ptr& _M_ex;
430 };
431
432 template<typename _Res, typename _Arg>
433 static _Setter<_Res, _Arg&&>
434 __setter(promise<_Res>* __prom, _Arg&& __arg)
435 {
436 return _Setter<_Res, _Arg&&>{ __prom, __arg };
437 }
438
439 template<typename _Res>
440 static _Setter<_Res, __exception_ptr_tag>
441 __setter(exception_ptr& __ex, promise<_Res>* __prom)
442 {
443 return _Setter<_Res, __exception_ptr_tag>{ __prom, __ex };
444 }
445
446 static _Setter<void, void>
447 __setter(promise<void>* __prom);
448
449 template<typename _Tp>
450 static void
451 _S_check(const shared_ptr<_Tp>& __p)
452 {
453 if (!static_cast<bool>(__p))
454 __throw_future_error((int)future_errc::no_state);
455 }
456
457 private:
458 void
459 _M_do_set(function<_Ptr_type()>& __f, bool& __set)
460 {
461 _Ptr_type __res = __f();
462 {
463 lock_guard<mutex> __lock(_M_mutex);
464 _M_result.swap(__res);
465 }
466 _M_cond.notify_all();
467 __set = true;
468 }
469
470 bool _M_ready() const noexcept { return static_cast<bool>(_M_result); }
471
472 // Misnamed: waits for completion of async function.
473 virtual void _M_run_deferred() { }
474 };
475
476 template<typename _BoundFn, typename = typename _BoundFn::result_type>
477 class _Deferred_state;
478
479 class _Async_state_common;
480
481 template<typename _BoundFn, typename = typename _BoundFn::result_type>
482 class _Async_state_impl;
483
484 template<typename _Signature>
485 class _Task_state;
486
487 template<typename _BoundFn>
488 static std::shared_ptr<_State_base>
489 _S_make_deferred_state(_BoundFn&& __fn);
490
491 template<typename _BoundFn>
492 static std::shared_ptr<_State_base>
493 _S_make_async_state(_BoundFn&& __fn);
494
495 template<typename _Res_ptr, typename _Res>
496 struct _Task_setter;
497
498 template<typename _Res_ptr, typename _BoundFn>
499 class _Task_setter_helper
500 {
501 typedef typename remove_reference<_BoundFn>::type::result_type __res;
502 public:
503 typedef _Task_setter<_Res_ptr, __res> __type;
504 };
505
506 template<typename _Res_ptr, typename _BoundFn>
507 static typename _Task_setter_helper<_Res_ptr, _BoundFn>::__type
508 _S_task_setter(_Res_ptr& __ptr, _BoundFn&& __call)
509 {
510 typedef _Task_setter_helper<_Res_ptr, _BoundFn> __helper_type;
511 typedef typename __helper_type::__type _Setter;
512 return _Setter{ __ptr, std::ref(__call) };
513 }
514 };
515
516 /// Partial specialization for reference types.
517 template<typename _Res>
518 struct __future_base::_Result<_Res&> : __future_base::_Result_base
519 {
520 _Result() noexcept : _M_value_ptr() { }
521
522 void _M_set(_Res& __res) noexcept { _M_value_ptr = &__res; }
523
524 _Res& _M_get() noexcept { return *_M_value_ptr; }
525
526 private:
527 _Res* _M_value_ptr;
528
529 void _M_destroy() { delete this; }
530 };
531
532 /// Explicit specialization for void.
533 template<>
534 struct __future_base::_Result<void> : __future_base::_Result_base
535 {
536 private:
537 void _M_destroy() { delete this; }
538 };
539
540
541 /// Common implementation for future and shared_future.
542 template<typename _Res>
543 class __basic_future : public __future_base
544 {
545 protected:
546 typedef shared_ptr<_State_base> __state_type;
547 typedef __future_base::_Result<_Res>& __result_type;
548
549 private:
550 __state_type _M_state;
551
552 public:
553 // Disable copying.
554 __basic_future(const __basic_future&) = delete;
555 __basic_future& operator=(const __basic_future&) = delete;
556
557 bool
558 valid() const noexcept { return static_cast<bool>(_M_state); }
559
560 void
561 wait() const
562 {
563 _State_base::_S_check(_M_state);
564 _M_state->wait();
565 }
566
567 template<typename _Rep, typename _Period>
568 future_status
569 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
570 {
571 _State_base::_S_check(_M_state);
572 return _M_state->wait_for(__rel);
573 }
574
575 template<typename _Clock, typename _Duration>
576 future_status
577 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
578 {
579 _State_base::_S_check(_M_state);
580 return _M_state->wait_until(__abs);
581 }
582
583 protected:
584 /// Wait for the state to be ready and rethrow any stored exception
585 __result_type
586 _M_get_result() const
587 {
588 _State_base::_S_check(_M_state);
589 _Result_base& __res = _M_state->wait();
590 if (!(__res._M_error == 0))
591 rethrow_exception(__res._M_error);
592 return static_cast<__result_type>(__res);
593 }
594
595 void _M_swap(__basic_future& __that) noexcept
596 {
597 _M_state.swap(__that._M_state);
598 }
599
600 // Construction of a future by promise::get_future()
601 explicit
602 __basic_future(const __state_type& __state) : _M_state(__state)
603 {
604 _State_base::_S_check(_M_state);
605 _M_state->_M_set_retrieved_flag();
606 }
607
608 // Copy construction from a shared_future
609 explicit
610 __basic_future(const shared_future<_Res>&) noexcept;
611
612 // Move construction from a shared_future
613 explicit
614 __basic_future(shared_future<_Res>&&) noexcept;
615
616 // Move construction from a future
617 explicit
618 __basic_future(future<_Res>&&) noexcept;
619
620 constexpr __basic_future() noexcept : _M_state() { }
621
622 struct _Reset
623 {
624 explicit _Reset(__basic_future& __fut) noexcept : _M_fut(__fut) { }
625 ~_Reset() { _M_fut._M_state.reset(); }
626 __basic_future& _M_fut;
627 };
628 };
629
630
631 /// Primary template for future.
632 template<typename _Res>
633 class future : public __basic_future<_Res>
634 {
635 friend class promise<_Res>;
636 template<typename> friend class packaged_task;
637 template<typename _Fn, typename... _Args>
638 friend future<typename result_of<_Fn(_Args...)>::type>
639 async(launch, _Fn&&, _Args&&...);
640
641 typedef __basic_future<_Res> _Base_type;
642 typedef typename _Base_type::__state_type __state_type;
643
644 explicit
645 future(const __state_type& __state) : _Base_type(__state) { }
646
647 public:
648 constexpr future() noexcept : _Base_type() { }
649
650 /// Move constructor
651 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
652
653 // Disable copying
654 future(const future&) = delete;
655 future& operator=(const future&) = delete;
656
657 future& operator=(future&& __fut) noexcept
658 {
659 future(std::move(__fut))._M_swap(*this);
660 return *this;
661 }
662
663 /// Retrieving the value
664 _Res
665 get()
666 {
667 typename _Base_type::_Reset __reset(*this);
668 return std::move(this->_M_get_result()._M_value());
669 }
670
671 shared_future<_Res> share();
672 };
673
674 /// Partial specialization for future<R&>
675 template<typename _Res>
676 class future<_Res&> : public __basic_future<_Res&>
677 {
678 friend class promise<_Res&>;
679 template<typename> friend class packaged_task;
680 template<typename _Fn, typename... _Args>
681 friend future<typename result_of<_Fn(_Args...)>::type>
682 async(launch, _Fn&&, _Args&&...);
683
684 typedef __basic_future<_Res&> _Base_type;
685 typedef typename _Base_type::__state_type __state_type;
686
687 explicit
688 future(const __state_type& __state) : _Base_type(__state) { }
689
690 public:
691 constexpr future() noexcept : _Base_type() { }
692
693 /// Move constructor
694 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
695
696 // Disable copying
697 future(const future&) = delete;
698 future& operator=(const future&) = delete;
699
700 future& operator=(future&& __fut) noexcept
701 {
702 future(std::move(__fut))._M_swap(*this);
703 return *this;
704 }
705
706 /// Retrieving the value
707 _Res&
708 get()
709 {
710 typename _Base_type::_Reset __reset(*this);
711 return this->_M_get_result()._M_get();
712 }
713
714 shared_future<_Res&> share();
715 };
716
717 /// Explicit specialization for future<void>
718 template<>
719 class future<void> : public __basic_future<void>
720 {
721 friend class promise<void>;
722 template<typename> friend class packaged_task;
723 template<typename _Fn, typename... _Args>
724 friend future<typename result_of<_Fn(_Args...)>::type>
725 async(launch, _Fn&&, _Args&&...);
726
727 typedef __basic_future<void> _Base_type;
728 typedef typename _Base_type::__state_type __state_type;
729
730 explicit
731 future(const __state_type& __state) : _Base_type(__state) { }
732
733 public:
734 constexpr future() noexcept : _Base_type() { }
735
736 /// Move constructor
737 future(future&& __uf) noexcept : _Base_type(std::move(__uf)) { }
738
739 // Disable copying
740 future(const future&) = delete;
741 future& operator=(const future&) = delete;
742
743 future& operator=(future&& __fut) noexcept
744 {
745 future(std::move(__fut))._M_swap(*this);
746 return *this;
747 }
748
749 /// Retrieving the value
750 void
751 get()
752 {
753 typename _Base_type::_Reset __reset(*this);
754 this->_M_get_result();
755 }
756
757 shared_future<void> share();
758 };
759
760
761 /// Primary template for shared_future.
762 template<typename _Res>
763 class shared_future : public __basic_future<_Res>
764 {
765 typedef __basic_future<_Res> _Base_type;
766
767 public:
768 constexpr shared_future() noexcept : _Base_type() { }
769
770 /// Copy constructor
771 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
772
773 /// Construct from a future rvalue
774 shared_future(future<_Res>&& __uf) noexcept
775 : _Base_type(std::move(__uf))
776 { }
777
778 /// Construct from a shared_future rvalue
779 shared_future(shared_future&& __sf) noexcept
780 : _Base_type(std::move(__sf))
781 { }
782
783 shared_future& operator=(const shared_future& __sf)
784 {
785 shared_future(__sf)._M_swap(*this);
786 return *this;
787 }
788
789 shared_future& operator=(shared_future&& __sf) noexcept
790 {
791 shared_future(std::move(__sf))._M_swap(*this);
792 return *this;
793 }
794
795 /// Retrieving the value
796 const _Res&
797 get() const { return this->_M_get_result()._M_value(); }
798 };
799
800 /// Partial specialization for shared_future<R&>
801 template<typename _Res>
802 class shared_future<_Res&> : public __basic_future<_Res&>
803 {
804 typedef __basic_future<_Res&> _Base_type;
805
806 public:
807 constexpr shared_future() noexcept : _Base_type() { }
808
809 /// Copy constructor
810 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
811
812 /// Construct from a future rvalue
813 shared_future(future<_Res&>&& __uf) noexcept
814 : _Base_type(std::move(__uf))
815 { }
816
817 /// Construct from a shared_future rvalue
818 shared_future(shared_future&& __sf) noexcept
819 : _Base_type(std::move(__sf))
820 { }
821
822 shared_future& operator=(const shared_future& __sf)
823 {
824 shared_future(__sf)._M_swap(*this);
825 return *this;
826 }
827
828 shared_future& operator=(shared_future&& __sf) noexcept
829 {
830 shared_future(std::move(__sf))._M_swap(*this);
831 return *this;
832 }
833
834 /// Retrieving the value
835 _Res&
836 get() const { return this->_M_get_result()._M_get(); }
837 };
838
839 /// Explicit specialization for shared_future<void>
840 template<>
841 class shared_future<void> : public __basic_future<void>
842 {
843 typedef __basic_future<void> _Base_type;
844
845 public:
846 constexpr shared_future() noexcept : _Base_type() { }
847
848 /// Copy constructor
849 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
850
851 /// Construct from a future rvalue
852 shared_future(future<void>&& __uf) noexcept
853 : _Base_type(std::move(__uf))
854 { }
855
856 /// Construct from a shared_future rvalue
857 shared_future(shared_future&& __sf) noexcept
858 : _Base_type(std::move(__sf))
859 { }
860
861 shared_future& operator=(const shared_future& __sf)
862 {
863 shared_future(__sf)._M_swap(*this);
864 return *this;
865 }
866
867 shared_future& operator=(shared_future&& __sf) noexcept
868 {
869 shared_future(std::move(__sf))._M_swap(*this);
870 return *this;
871 }
872
873 // Retrieving the value
874 void
875 get() const { this->_M_get_result(); }
876 };
877
878 // Now we can define the protected __basic_future constructors.
879 template<typename _Res>
880 inline __basic_future<_Res>::
881 __basic_future(const shared_future<_Res>& __sf) noexcept
882 : _M_state(__sf._M_state)
883 { }
884
885 template<typename _Res>
886 inline __basic_future<_Res>::
887 __basic_future(shared_future<_Res>&& __sf) noexcept
888 : _M_state(std::move(__sf._M_state))
889 { }
890
891 template<typename _Res>
892 inline __basic_future<_Res>::
893 __basic_future(future<_Res>&& __uf) noexcept
894 : _M_state(std::move(__uf._M_state))
895 { }
896
897 template<typename _Res>
898 inline shared_future<_Res>
899 future<_Res>::share()
900 { return shared_future<_Res>(std::move(*this)); }
901
902 template<typename _Res>
903 inline shared_future<_Res&>
904 future<_Res&>::share()
905 { return shared_future<_Res&>(std::move(*this)); }
906
907 inline shared_future<void>
908 future<void>::share()
909 { return shared_future<void>(std::move(*this)); }
910
911 /// Primary template for promise
912 template<typename _Res>
913 class promise
914 {
915 typedef __future_base::_State_base _State;
916 typedef __future_base::_Result<_Res> _Res_type;
917 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
918 template<typename, typename> friend class _State::_Setter;
919
920 shared_ptr<_State> _M_future;
921 _Ptr_type _M_storage;
922
923 public:
924 promise()
925 : _M_future(std::make_shared<_State>()),
926 _M_storage(new _Res_type())
927 { }
928
929 promise(promise&& __rhs) noexcept
930 : _M_future(std::move(__rhs._M_future)),
931 _M_storage(std::move(__rhs._M_storage))
932 { }
933
934 template<typename _Allocator>
935 promise(allocator_arg_t, const _Allocator& __a)
936 : _M_future(std::allocate_shared<_State>(__a)),
937 _M_storage(__future_base::_S_allocate_result<_Res>(__a))
938 { }
939
940 template<typename _Allocator>
941 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
942 : _M_future(std::move(__rhs._M_future)),
943 _M_storage(std::move(__rhs._M_storage))
944 { }
945
946 promise(const promise&) = delete;
947
948 ~promise()
949 {
950 if (static_cast<bool>(_M_future) && !_M_future.unique())
951 _M_future->_M_break_promise(std::move(_M_storage));
952 }
953
954 // Assignment
955 promise&
956 operator=(promise&& __rhs) noexcept
957 {
958 promise(std::move(__rhs)).swap(*this);
959 return *this;
960 }
961
962 promise& operator=(const promise&) = delete;
963
964 void
965 swap(promise& __rhs) noexcept
966 {
967 _M_future.swap(__rhs._M_future);
968 _M_storage.swap(__rhs._M_storage);
969 }
970
971 // Retrieving the result
972 future<_Res>
973 get_future()
974 { return future<_Res>(_M_future); }
975
976 // Setting the result
977 void
978 set_value(const _Res& __r)
979 {
980 auto __setter = _State::__setter(this, __r);
981 _M_future->_M_set_result(std::move(__setter));
982 }
983
984 void
985 set_value(_Res&& __r)
986 {
987 auto __setter = _State::__setter(this, std::move(__r));
988 _M_future->_M_set_result(std::move(__setter));
989 }
990
991 void
992 set_exception(exception_ptr __p)
993 {
994 auto __setter = _State::__setter(__p, this);
995 _M_future->_M_set_result(std::move(__setter));
996 }
997 };
998
999 template<typename _Res>
1000 inline void
1001 swap(promise<_Res>& __x, promise<_Res>& __y) noexcept
1002 { __x.swap(__y); }
1003
1004 template<typename _Res, typename _Alloc>
1005 struct uses_allocator<promise<_Res>, _Alloc>
1006 : public true_type { };
1007
1008
1009 /// Partial specialization for promise<R&>
1010 template<typename _Res>
1011 class promise<_Res&>
1012 {
1013 typedef __future_base::_State_base _State;
1014 typedef __future_base::_Result<_Res&> _Res_type;
1015 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1016 template<typename, typename> friend class _State::_Setter;
1017
1018 shared_ptr<_State> _M_future;
1019 _Ptr_type _M_storage;
1020
1021 public:
1022 promise()
1023 : _M_future(std::make_shared<_State>()),
1024 _M_storage(new _Res_type())
1025 { }
1026
1027 promise(promise&& __rhs) noexcept
1028 : _M_future(std::move(__rhs._M_future)),
1029 _M_storage(std::move(__rhs._M_storage))
1030 { }
1031
1032 template<typename _Allocator>
1033 promise(allocator_arg_t, const _Allocator& __a)
1034 : _M_future(std::allocate_shared<_State>(__a)),
1035 _M_storage(__future_base::_S_allocate_result<_Res&>(__a))
1036 { }
1037
1038 template<typename _Allocator>
1039 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1040 : _M_future(std::move(__rhs._M_future)),
1041 _M_storage(std::move(__rhs._M_storage))
1042 { }
1043
1044 promise(const promise&) = delete;
1045
1046 ~promise()
1047 {
1048 if (static_cast<bool>(_M_future) && !_M_future.unique())
1049 _M_future->_M_break_promise(std::move(_M_storage));
1050 }
1051
1052 // Assignment
1053 promise&
1054 operator=(promise&& __rhs) noexcept
1055 {
1056 promise(std::move(__rhs)).swap(*this);
1057 return *this;
1058 }
1059
1060 promise& operator=(const promise&) = delete;
1061
1062 void
1063 swap(promise& __rhs) noexcept
1064 {
1065 _M_future.swap(__rhs._M_future);
1066 _M_storage.swap(__rhs._M_storage);
1067 }
1068
1069 // Retrieving the result
1070 future<_Res&>
1071 get_future()
1072 { return future<_Res&>(_M_future); }
1073
1074 // Setting the result
1075 void
1076 set_value(_Res& __r)
1077 {
1078 auto __setter = _State::__setter(this, __r);
1079 _M_future->_M_set_result(std::move(__setter));
1080 }
1081
1082 void
1083 set_exception(exception_ptr __p)
1084 {
1085 auto __setter = _State::__setter(__p, this);
1086 _M_future->_M_set_result(std::move(__setter));
1087 }
1088 };
1089
1090 /// Explicit specialization for promise<void>
1091 template<>
1092 class promise<void>
1093 {
1094 typedef __future_base::_State_base _State;
1095 typedef __future_base::_Result<void> _Res_type;
1096 typedef __future_base::_Ptr<_Res_type> _Ptr_type;
1097 template<typename, typename> friend class _State::_Setter;
1098
1099 shared_ptr<_State> _M_future;
1100 _Ptr_type _M_storage;
1101
1102 public:
1103 promise()
1104 : _M_future(std::make_shared<_State>()),
1105 _M_storage(new _Res_type())
1106 { }
1107
1108 promise(promise&& __rhs) noexcept
1109 : _M_future(std::move(__rhs._M_future)),
1110 _M_storage(std::move(__rhs._M_storage))
1111 { }
1112
1113 template<typename _Allocator>
1114 promise(allocator_arg_t, const _Allocator& __a)
1115 : _M_future(std::allocate_shared<_State>(__a)),
1116 _M_storage(__future_base::_S_allocate_result<void>(__a))
1117 { }
1118
1119 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1120 // 2095. missing constructors needed for uses-allocator construction
1121 template<typename _Allocator>
1122 promise(allocator_arg_t, const _Allocator&, promise&& __rhs)
1123 : _M_future(std::move(__rhs._M_future)),
1124 _M_storage(std::move(__rhs._M_storage))
1125 { }
1126
1127 promise(const promise&) = delete;
1128
1129 ~promise()
1130 {
1131 if (static_cast<bool>(_M_future) && !_M_future.unique())
1132 _M_future->_M_break_promise(std::move(_M_storage));
1133 }
1134
1135 // Assignment
1136 promise&
1137 operator=(promise&& __rhs) noexcept
1138 {
1139 promise(std::move(__rhs)).swap(*this);
1140 return *this;
1141 }
1142
1143 promise& operator=(const promise&) = delete;
1144
1145 void
1146 swap(promise& __rhs) noexcept
1147 {
1148 _M_future.swap(__rhs._M_future);
1149 _M_storage.swap(__rhs._M_storage);
1150 }
1151
1152 // Retrieving the result
1153 future<void>
1154 get_future()
1155 { return future<void>(_M_future); }
1156
1157 // Setting the result
1158 void set_value();
1159
1160 void
1161 set_exception(exception_ptr __p)
1162 {
1163 auto __setter = _State::__setter(__p, this);
1164 _M_future->_M_set_result(std::move(__setter));
1165 }
1166 };
1167
1168 // set void
1169 template<>
1170 struct __future_base::_State_base::_Setter<void, void>
1171 {
1172 promise<void>::_Ptr_type operator()()
1173 {
1174 _State_base::_S_check(_M_promise->_M_future);
1175 return std::move(_M_promise->_M_storage);
1176 }
1177
1178 promise<void>* _M_promise;
1179 };
1180
1181 inline __future_base::_State_base::_Setter<void, void>
1182 __future_base::_State_base::__setter(promise<void>* __prom)
1183 {
1184 return _Setter<void, void>{ __prom };
1185 }
1186
1187 inline void
1188 promise<void>::set_value()
1189 {
1190 auto __setter = _State::__setter(this);
1191 _M_future->_M_set_result(std::move(__setter));
1192 }
1193
1194
1195 template<typename _Ptr_type, typename _Res>
1196 struct __future_base::_Task_setter
1197 {
1198 _Ptr_type operator()()
1199 {
1200 __try
1201 {
1202 _M_result->_M_set(_M_fn());
1203 }
1204 __catch(...)
1205 {
1206 _M_result->_M_error = current_exception();
1207 }
1208 return std::move(_M_result);
1209 }
1210 _Ptr_type& _M_result;
1211 std::function<_Res()> _M_fn;
1212 };
1213
1214 template<typename _Ptr_type>
1215 struct __future_base::_Task_setter<_Ptr_type, void>
1216 {
1217 _Ptr_type operator()()
1218 {
1219 __try
1220 {
1221 _M_fn();
1222 }
1223 __catch(...)
1224 {
1225 _M_result->_M_error = current_exception();
1226 }
1227 return std::move(_M_result);
1228 }
1229 _Ptr_type& _M_result;
1230 std::function<void()> _M_fn;
1231 };
1232
1233 template<typename _Res, typename... _Args>
1234 struct __future_base::_Task_state<_Res(_Args...)> final
1235 : __future_base::_State_base
1236 {
1237 typedef _Res _Res_type;
1238
1239 _Task_state(std::function<_Res(_Args...)> __task)
1240 : _M_result(new _Result<_Res>()), _M_task(std::move(__task))
1241 { }
1242
1243 template<typename _Func, typename _Alloc>
1244 _Task_state(_Func&& __task, const _Alloc& __a)
1245 : _M_result(_S_allocate_result<_Res>(__a)),
1246 _M_task(allocator_arg, __a, std::move(__task))
1247 { }
1248
1249 void
1250 _M_run(_Args... __args)
1251 {
1252 // bound arguments decay so wrap lvalue references
1253 auto __boundfn = std::__bind_simple(std::ref(_M_task),
1254 _S_maybe_wrap_ref(std::forward<_Args>(__args))...);
1255 auto __setter = _S_task_setter(_M_result, std::move(__boundfn));
1256 _M_set_result(std::move(__setter));
1257 }
1258
1259 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1260 _Ptr_type _M_result;
1261 std::function<_Res(_Args...)> _M_task;
1262
1263 template<typename _Tp>
1264 static reference_wrapper<_Tp>
1265 _S_maybe_wrap_ref(_Tp& __t)
1266 { return std::ref(__t); }
1267
1268 template<typename _Tp>
1269 static typename enable_if<!is_lvalue_reference<_Tp>::value,
1270 _Tp>::type&&
1271 _S_maybe_wrap_ref(_Tp&& __t)
1272 { return std::forward<_Tp>(__t); }
1273 };
1274
1275 template<typename _Task, typename _Fn, bool
1276 = is_same<_Task, typename decay<_Fn>::type>::value>
1277 struct __constrain_pkgdtask
1278 { typedef void __type; };
1279
1280 template<typename _Task, typename _Fn>
1281 struct __constrain_pkgdtask<_Task, _Fn, true>
1282 { };
1283
1284 /// packaged_task
1285 template<typename _Res, typename... _ArgTypes>
1286 class packaged_task<_Res(_ArgTypes...)>
1287 {
1288 typedef __future_base::_Task_state<_Res(_ArgTypes...)> _State_type;
1289 shared_ptr<_State_type> _M_state;
1290
1291 public:
1292 // Construction and destruction
1293 packaged_task() noexcept { }
1294
1295 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1296 // 2095. missing constructors needed for uses-allocator construction
1297 template<typename _Allocator>
1298 explicit
1299 packaged_task(allocator_arg_t, const _Allocator& __a) noexcept
1300 { }
1301
1302 template<typename _Fn, typename = typename
1303 __constrain_pkgdtask<packaged_task, _Fn>::__type>
1304 explicit
1305 packaged_task(_Fn&& __fn)
1306 : _M_state(std::make_shared<_State_type>(std::forward<_Fn>(__fn)))
1307 { }
1308
1309 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1310 // 2097. packaged_task constructors should be constrained
1311 template<typename _Fn, typename _Allocator, typename = typename
1312 __constrain_pkgdtask<packaged_task, _Fn>::__type>
1313 explicit
1314 packaged_task(allocator_arg_t, const _Allocator& __a, _Fn&& __fn)
1315 : _M_state(std::allocate_shared<_State_type>(__a,
1316 std::forward<_Fn>(__fn)))
1317 { }
1318
1319 ~packaged_task()
1320 {
1321 if (static_cast<bool>(_M_state) && !_M_state.unique())
1322 _M_state->_M_break_promise(std::move(_M_state->_M_result));
1323 }
1324
1325 // No copy
1326 packaged_task(const packaged_task&) = delete;
1327 packaged_task& operator=(const packaged_task&) = delete;
1328
1329 template<typename _Allocator>
1330 explicit
1331 packaged_task(allocator_arg_t, const _Allocator&,
1332 const packaged_task&) = delete;
1333
1334 // Move support
1335 packaged_task(packaged_task&& __other) noexcept
1336 { this->swap(__other); }
1337
1338 template<typename _Allocator>
1339 explicit
1340 packaged_task(allocator_arg_t, const _Allocator&,
1341 packaged_task&& __other) noexcept
1342 { this->swap(__other); }
1343
1344 packaged_task& operator=(packaged_task&& __other) noexcept
1345 {
1346 packaged_task(std::move(__other)).swap(*this);
1347 return *this;
1348 }
1349
1350 void
1351 swap(packaged_task& __other) noexcept
1352 { _M_state.swap(__other._M_state); }
1353
1354 bool
1355 valid() const noexcept
1356 { return static_cast<bool>(_M_state); }
1357
1358 // Result retrieval
1359 future<_Res>
1360 get_future()
1361 { return future<_Res>(_M_state); }
1362
1363 // Execution
1364 void
1365 operator()(_ArgTypes... __args)
1366 {
1367 __future_base::_State_base::_S_check(_M_state);
1368 _M_state->_M_run(std::forward<_ArgTypes>(__args)...);
1369 }
1370
1371 void
1372 reset()
1373 {
1374 __future_base::_State_base::_S_check(_M_state);
1375 packaged_task(std::move(_M_state->_M_task)).swap(*this);
1376 }
1377 };
1378
1379 /// swap
1380 template<typename _Res, typename... _ArgTypes>
1381 inline void
1382 swap(packaged_task<_Res(_ArgTypes...)>& __x,
1383 packaged_task<_Res(_ArgTypes...)>& __y) noexcept
1384 { __x.swap(__y); }
1385
1386 template<typename _Res, typename _Alloc>
1387 struct uses_allocator<packaged_task<_Res>, _Alloc>
1388 : public true_type { };
1389
1390
1391 template<typename _BoundFn, typename _Res>
1392 class __future_base::_Deferred_state final
1393 : public __future_base::_State_base
1394 {
1395 public:
1396 explicit
1397 _Deferred_state(_BoundFn&& __fn)
1398 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1399 { }
1400
1401 private:
1402 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1403 _Ptr_type _M_result;
1404 _BoundFn _M_fn;
1405
1406 virtual void
1407 _M_run_deferred()
1408 {
1409 // safe to call multiple times so ignore failure
1410 _M_set_result(_S_task_setter(_M_result, _M_fn), true);
1411 }
1412 };
1413
1414 class __future_base::_Async_state_common : public __future_base::_State_base
1415 {
1416 protected:
1417 #ifdef _GLIBCXX_ASYNC_ABI_COMPAT
1418 ~_Async_state_common();
1419 #else
1420 ~_Async_state_common() = default;
1421 #endif
1422
1423 // Allow non-timed waiting functions to block until the thread completes,
1424 // as if joined.
1425 virtual void _M_run_deferred() { _M_join(); }
1426
1427 void _M_join() { std::call_once(_M_once, &thread::join, ref(_M_thread)); }
1428
1429 thread _M_thread;
1430 once_flag _M_once;
1431 };
1432
1433 template<typename _BoundFn, typename _Res>
1434 class __future_base::_Async_state_impl final
1435 : public __future_base::_Async_state_common
1436 {
1437 public:
1438 explicit
1439 _Async_state_impl(_BoundFn&& __fn)
1440 : _M_result(new _Result<_Res>()), _M_fn(std::move(__fn))
1441 {
1442 _M_thread = std::thread{ [this] {
1443 _M_set_result(_S_task_setter(_M_result, _M_fn));
1444 } };
1445 }
1446
1447 ~_Async_state_impl() { _M_join(); }
1448
1449 private:
1450 typedef __future_base::_Ptr<_Result<_Res>> _Ptr_type;
1451 _Ptr_type _M_result;
1452 _BoundFn _M_fn;
1453 };
1454
1455 template<typename _BoundFn>
1456 inline std::shared_ptr<__future_base::_State_base>
1457 __future_base::_S_make_deferred_state(_BoundFn&& __fn)
1458 {
1459 typedef typename remove_reference<_BoundFn>::type __fn_type;
1460 typedef _Deferred_state<__fn_type> __state_type;
1461 return std::make_shared<__state_type>(std::move(__fn));
1462 }
1463
1464 template<typename _BoundFn>
1465 inline std::shared_ptr<__future_base::_State_base>
1466 __future_base::_S_make_async_state(_BoundFn&& __fn)
1467 {
1468 typedef typename remove_reference<_BoundFn>::type __fn_type;
1469 typedef _Async_state_impl<__fn_type> __state_type;
1470 return std::make_shared<__state_type>(std::move(__fn));
1471 }
1472
1473
1474 /// async
1475 template<typename _Fn, typename... _Args>
1476 future<typename result_of<_Fn(_Args...)>::type>
1477 async(launch __policy, _Fn&& __fn, _Args&&... __args)
1478 {
1479 typedef typename result_of<_Fn(_Args...)>::type result_type;
1480 std::shared_ptr<__future_base::_State_base> __state;
1481 if ((__policy & (launch::async|launch::deferred)) == launch::async)
1482 {
1483 __state = __future_base::_S_make_async_state(std::__bind_simple(
1484 std::forward<_Fn>(__fn), std::forward<_Args>(__args)...));
1485 }
1486 else
1487 {
1488 __state = __future_base::_S_make_deferred_state(std::__bind_simple(
1489 std::forward<_Fn>(__fn), std::forward<_Args>(__args)...));
1490 }
1491 return future<result_type>(__state);
1492 }
1493
1494 /// async, potential overload
1495 template<typename _Fn, typename... _Args>
1496 inline future<typename result_of<_Fn(_Args...)>::type>
1497 async(_Fn&& __fn, _Args&&... __args)
1498 {
1499 return async(launch::async|launch::deferred, std::forward<_Fn>(__fn),
1500 std::forward<_Args>(__args)...);
1501 }
1502
1503 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
1504 // && ATOMIC_INT_LOCK_FREE
1505
1506 // @} group futures
1507 _GLIBCXX_END_NAMESPACE_VERSION
1508 } // namespace
1509
1510 #endif // C++11
1511
1512 #endif // _GLIBCXX_FUTURE