OSDN Git Service

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