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