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