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