1 // <future> -*- C++ -*-
3 // Copyright (C) 2009 Free Software Foundation, Inc.
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)
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/>.
26 * This is a Standard C++ Library header.
29 #ifndef _GLIBCXX_FUTURE
30 #define _GLIBCXX_FUTURE 1
32 #pragma GCC system_header
34 #ifndef __GXX_EXPERIMENTAL_CXX0X__
35 # include <c++0x_warning.h>
41 #include <condition_variable>
42 #include <system_error>
49 * @defgroup futures Futures
50 * @ingroup concurrency
52 * Classes for futures support.
56 /// Error code for futures
57 enum class future_errc
58 { broken_promise, future_already_retrieved, promise_already_satisfied };
60 // TODO: requires concepts
61 // concept_map ErrorCodeEnum<future_errc> { }
63 struct is_error_code_enum<future_errc> : public true_type { };
65 /// Points to a statically-allocated object derived from error_category.
66 extern const error_category* const future_category;
68 // TODO: requires constexpr
69 inline error_code make_error_code(future_errc __errc)
70 { return error_code(static_cast<int>(__errc), *future_category); }
72 // TODO: requires constexpr
73 inline error_condition make_error_condition(future_errc __errc)
74 { return error_condition(static_cast<int>(__errc), *future_category); }
77 * @brief Exception type thrown by futures.
80 class future_error : public logic_error
85 explicit future_error(future_errc __ec)
86 : logic_error("std::future_error"), _M_code(make_error_code(__ec))
89 virtual ~future_error() throw();
95 code() const throw() { return _M_code; }
98 // Forward declarations.
99 template<typename _Result>
102 template<typename _Result>
108 template<typename _Result>
111 #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) \
112 && defined(_GLIBCXX_ATOMIC_BUILTINS_4)
114 // Holds the result of a future
115 struct _Future_result_base
117 _Future_result_base() = default;
118 _Future_result_base(const _Future_result_base&) = delete;
119 _Future_result_base& operator=(const _Future_result_base&) = delete;
121 exception_ptr _M_error;
123 // _M_destroy() allows derived classes to control deallocation,
124 // which will be needed when allocator support is added to promise.
125 // See http://gcc.gnu.org/ml/libstdc++/2009-06/msg00032.html
126 virtual void _M_destroy() = 0;
129 void operator()(_Future_result_base* __fr) const { __fr->_M_destroy(); }
133 ~_Future_result_base() = default;
136 // TODO: use template alias when available
138 template<typename _Res>
139 using _Future_ptr = unique_ptr<_Res, _Future_result_base::_Deleter>;
141 template<typename _Res>
144 typedef unique_ptr<_Res, _Future_result_base::_Deleter> type;
147 // State shared between a promise and one or more associated futures.
150 typedef _Future_ptr<_Future_result_base>::type _Future_ptr_type;
153 _Future_state() : _M_result(), _M_retrieved(false) { }
155 _Future_state(const _Future_state&) = delete;
156 _Future_state& operator=(const _Future_state&) = delete;
160 { return _M_get() != 0; }
165 _Future_result_base* const __res = _M_get();
166 return __res && !(__res->_M_error == 0);
172 _Future_result_base* const __res = _M_get();
173 return __res && (__res->_M_error == 0);
179 unique_lock<mutex> __lock(_M_mutex);
181 _M_cond.wait(__lock, std::bind(&_Future_state::_M_ready, this));
185 template<typename _Rep, typename _Period>
187 wait_for(const chrono::duration<_Rep, _Period>& __rel)
189 unique_lock<mutex> __lock(_M_mutex);
190 return _M_ready() || _M_cond.wait_for(__lock, __rel,
191 std::bind(&_Future_state::_M_ready, this));
194 template<typename _Clock, typename _Duration>
196 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
198 unique_lock<mutex> __lock(_M_mutex);
199 return _M_ready() || _M_cond.wait_until(__lock, __abs,
200 std::bind(&_Future_state::_M_ready, this));
204 _M_set_result(_Future_ptr_type __res)
207 lock_guard<mutex> __lock(_M_mutex);
209 __throw_future_error(int(future_errc::promise_already_satisfied));
210 _M_result.swap(__res);
212 _M_cond.notify_all();
216 _M_break_promise(_Future_ptr_type __res)
218 if (static_cast<bool>(__res))
221 = std::copy_exception(future_error(future_errc::broken_promise));
223 lock_guard<mutex> __lock(_M_mutex);
224 _M_result.swap(__res);
226 _M_cond.notify_all();
230 // called when this object is passed to a unique_future
232 _M_set_retrieved_flag()
234 if (_M_retrieved.test_and_set())
235 __throw_future_error(int(future_errc::future_already_retrieved));
242 lock_guard<mutex> __lock(_M_mutex);
243 return _M_result.get();
246 bool _M_ready() const { return static_cast<bool>(_M_result); }
248 _Future_ptr_type _M_result;
250 condition_variable _M_cond;
251 atomic_flag _M_retrieved;
254 // workaround for CWG issue 664 and c++/34022
255 template<typename _Result, bool = is_scalar<_Result>::value>
256 struct _Move_future_result
258 typedef _Result&& __rval_type;
259 static _Result&& _S_move(_Result& __res) { return std::move(__res); }
262 // specialization for scalar types returns rvalue not rvalue-reference
263 template<typename _Result>
264 struct _Move_future_result<_Result, true>
266 typedef _Result __rval_type;
267 static _Result _S_move(_Result __res) { return __res; }
270 template<typename _Result>
271 struct _Future_result : _Future_result_base
273 _Future_result() : _M_initialized() { }
278 _M_value().~_Result();
281 // return lvalue, future will add const or rvalue-reference
283 { return *static_cast<_Result*>(_M_addr()); }
286 _M_set(const _Result& __res)
288 ::new (_M_addr()) _Result(__res);
289 _M_initialized = true;
293 _M_set(_Result&& __res)
295 typedef _Move_future_result<_Result> _Mover;
296 ::new (_M_addr()) _Result(_Mover::_S_move(__res));
297 _M_initialized = true;
301 void _M_destroy() { delete this; }
303 void* _M_addr() { return static_cast<void*>(&_M_storage); }
305 typename aligned_storage<sizeof(_Result),
306 alignment_of<_Result>::value>::type _M_storage;
310 template<typename _Result>
311 struct _Future_result<_Result&> : _Future_result_base
313 _Future_result() : _M_value_ptr() { }
315 _Result* _M_value_ptr;
317 void _M_destroy() { delete this; }
321 struct _Future_result<void> : _Future_result_base
323 void _M_destroy() { delete this; }
326 // common implementation for unique_future and shared_future
327 template<typename _Result>
332 _Future_impl(const _Future_impl&) = delete;
333 _Future_impl& operator=(const _Future_impl&) = delete;
335 // functions to check state and wait for ready
336 bool is_ready() const { return this->_M_state->is_ready(); }
338 bool has_exception() const { return this->_M_state->has_exception(); }
340 bool has_value() const { return this->_M_state->has_value(); }
342 void wait() const { this->_M_state->wait(); }
344 template<typename _Rep, typename _Period>
346 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
347 { return this->_M_state->wait_for(__rel); }
349 template<typename _Clock, typename _Duration>
351 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
352 { return this->_M_state->wait_until(__abs); }
355 // wait for the state to be ready and rethrow any stored exception
356 _Future_result<_Result>&
359 _Future_result_base& __res = this->_M_state->wait();
360 if (!(__res._M_error == 0))
361 rethrow_exception(__res._M_error);
362 return static_cast<_Future_result<_Result>&>(__res);
365 typedef shared_ptr<_Future_state> _State_ptr;
367 // construction of a unique_future by promise::get_future()
369 _Future_impl(const _State_ptr& __state)
372 if (static_cast<bool>(this->_M_state))
373 this->_M_state->_M_set_retrieved_flag();
375 __throw_future_error(int(future_errc::future_already_retrieved));
378 // copy construction from a shared_future
380 _Future_impl(const shared_future<_Result>&);
382 // move construction from a unique_future
384 _Future_impl(unique_future<_Result>&&);
389 /// primary template for unique_future
390 template<typename _Result>
391 class unique_future : public _Future_impl<_Result>
393 typedef _Move_future_result<_Result> _Mover;
397 unique_future(unique_future&& __uf) : _Base_type(std::move(__uf)) { }
400 unique_future(const unique_future&) = delete;
401 unique_future& operator=(const unique_future&) = delete;
403 // retrieving the value
404 typename _Mover::__rval_type
406 { return _Mover::_S_move(this->_M_get_result()._M_value()); }
409 typedef _Future_impl<_Result> _Base_type;
410 typedef typename _Base_type::_State_ptr _State_ptr;
412 friend class promise<_Result>;
415 unique_future(const _State_ptr& __state) : _Base_type(__state) { }
418 // partial specialization for unique_future<R&>
419 template<typename _Result>
420 class unique_future<_Result&> : public _Future_impl<_Result&>
424 unique_future(unique_future&& __uf) : _Base_type(std::move(__uf)) { }
427 unique_future(const unique_future&) = delete;
428 unique_future& operator=(const unique_future&) = delete;
430 // retrieving the value
431 _Result& get() { return *this->_M_get_result()._M_value_ptr; }
434 typedef _Future_impl<_Result&> _Base_type;
435 typedef typename _Base_type::_State_ptr _State_ptr;
437 friend class promise<_Result&>;
440 unique_future(const _State_ptr& __state) : _Base_type(__state) { }
443 // specialization for unique_future<void>
445 class unique_future<void> : public _Future_impl<void>
449 unique_future(unique_future&& __uf) : _Base_type(std::move(__uf)) { }
452 unique_future(const unique_future&) = delete;
453 unique_future& operator=(const unique_future&) = delete;
455 // retrieving the value
456 void get() { this->_M_get_result(); }
459 typedef _Future_impl<void> _Base_type;
460 typedef _Base_type::_State_ptr _State_ptr;
462 friend class promise<void>;
465 unique_future(const _State_ptr& __state) : _Base_type(__state) { }
468 /// primary template for shared_future
469 template<typename _Result>
470 class shared_future : public _Future_impl<_Result>
474 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
476 /// Construct from a unique_future rvalue
477 shared_future(unique_future<_Result>&& __uf)
478 : _Base_type(std::move(__uf))
481 shared_future& operator=(const shared_future&) = delete;
483 // retrieving the value
486 { return this->_M_get_result()._M_value(); }
489 typedef _Future_impl<_Result> _Base_type;
492 // partial specialization for shared_future<R&>
493 template<typename _Result>
494 class shared_future<_Result&> : public _Future_impl<_Result&>
498 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
500 /// Construct from a unique_future rvalue
501 shared_future(unique_future<_Result&>&& __uf)
502 : _Base_type(std::move(__uf))
505 shared_future& operator=(const shared_future&) = delete;
507 // retrieving the value
508 _Result& get() { return *this->_M_get_result()._M_value_ptr; }
511 typedef _Future_impl<_Result&> _Base_type;
514 // specialization for shared_future<void>
516 class shared_future<void> : public _Future_impl<void>
520 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
522 /// Construct from a unique_future rvalue
523 shared_future(unique_future<void>&& __uf)
524 : _Base_type(std::move(__uf))
527 shared_future& operator=(const shared_future&) = delete;
529 // retrieving the value
530 void get() { this->_M_get_result(); }
533 typedef _Future_impl<void> _Base_type;
536 // now we can define the protected _Future_impl constructors
538 template<typename _Result>
539 _Future_impl<_Result>::_Future_impl(const shared_future<_Result>& __sf)
540 : _M_state(__sf._M_state)
543 template<typename _Result>
544 _Future_impl<_Result>::_Future_impl(unique_future<_Result>&& __uf)
545 : _M_state(std::move(__uf._M_state))
548 /// primary template for promise
549 template<typename _Result>
554 : _M_future(std::make_shared<_Future_state>()),
555 _M_storage(new _Future_result<_Result>())
558 promise(promise&& __rhs)
559 : _M_future(std::move(__rhs._M_future)),
560 _M_storage(std::move(__rhs._M_storage))
563 // TODO: requires allocator concepts
565 template<typename _Allocator>
566 promise(allocator_arg_t, const _Allocator& __a);
568 template<typename _Allocator>
569 promise(allocator_arg_t, const _Allocator&, promise&& __rhs);
572 promise(const promise&) = delete;
576 if (static_cast<bool>(_M_future) && !_M_future.unique())
577 _M_future->_M_break_promise(std::move(_M_storage));
582 operator=(promise&& __rhs)
584 promise(std::move(__rhs)).swap(*this);
588 promise& operator=(const promise&) = delete;
593 _M_future.swap(__rhs._M_future);
594 _M_storage.swap(__rhs._M_storage);
597 // retrieving the result
598 unique_future<_Result>
600 { return unique_future<_Result>(_M_future); }
602 // setting the result
604 set_value(const _Result& __r)
607 _M_storage->_M_set(__r);
608 _M_future->_M_set_result(std::move(_M_storage));
612 set_value(_Result&& __r)
615 _M_storage->_M_set(_Mover::_S_move(__r));
616 _M_future->_M_set_result(std::move(_M_storage));
620 set_exception(exception_ptr __p)
623 _M_storage->_M_error = __p;
624 _M_future->_M_set_result(std::move(_M_storage));
628 template<typename> friend class packaged_task;
629 typedef _Move_future_result<_Result> _Mover;
630 bool _M_satisfied() { return !static_cast<bool>(_M_storage); }
631 shared_ptr<_Future_state> _M_future;
632 typename _Future_ptr<_Future_result<_Result>>::type _M_storage;
635 // partial specialization for promise<R&>
636 template<typename _Result>
637 class promise<_Result&>
641 : _M_future(std::make_shared<_Future_state>()),
642 _M_storage(new _Future_result<_Result&>())
645 promise(promise&& __rhs)
646 : _M_future(std::move(__rhs._M_future)),
647 _M_storage(std::move(__rhs._M_storage))
650 // TODO: requires allocator concepts
652 template<typename _Allocator>
653 promise(allocator_arg_t, const _Allocator& __a);
655 template<typename _Allocator>
656 promise(allocator_arg_t, const _Allocator&, promise&& __rhs);
659 promise(const promise&) = delete;
663 if (static_cast<bool>(_M_future) && !_M_future.unique())
664 _M_future->_M_break_promise(std::move(_M_storage));
669 operator=(promise&& __rhs)
671 promise(std::move(__rhs)).swap(*this);
675 promise& operator=(const promise&) = delete;
680 _M_future.swap(__rhs._M_future);
681 _M_storage.swap(__rhs._M_storage);
684 // retrieving the result
685 unique_future<_Result&>
687 { return unique_future<_Result&>(_M_future); }
689 // setting the result
691 set_value(_Result& __r)
694 _M_storage->_M_value_ptr = &__r;
695 _M_future->_M_set_result(std::move(_M_storage));
699 set_exception(exception_ptr __p)
702 _M_storage->_M_error = __p;
703 _M_future->_M_set_result(std::move(_M_storage));
707 template<typename> friend class packaged_task;
708 bool _M_satisfied() { return !static_cast<bool>(_M_storage); }
709 shared_ptr<_Future_state> _M_future;
710 typename _Future_ptr<_Future_result<_Result&>>::type _M_storage;
713 // specialization for promise<void>
719 : _M_future(std::make_shared<_Future_state>()),
720 _M_storage(new _Future_result<void>())
723 promise(promise&& __rhs)
724 : _M_future(std::move(__rhs._M_future)),
725 _M_storage(std::move(__rhs._M_storage))
728 // TODO: requires allocator concepts
730 template<typename _Allocator>
731 promise(allocator_arg_t, const _Allocator& __a);
733 template<typename _Allocator>
734 promise(allocator_arg_t, const _Allocator&, promise&& __rhs);
737 promise(const promise&) = delete;
741 if (static_cast<bool>(_M_future) && !_M_future.unique())
742 _M_future->_M_break_promise(std::move(_M_storage));
747 operator=(promise&& __rhs)
749 promise(std::move(__rhs)).swap(*this);
753 promise& operator=(const promise&) = delete;
758 _M_future.swap(__rhs._M_future);
759 _M_storage.swap(__rhs._M_storage);
762 // retrieving the result
765 { return unique_future<void>(_M_future); }
767 // setting the result
771 _M_future->_M_set_result(std::move(_M_storage));
775 set_exception(exception_ptr __p)
778 _M_storage->_M_error = __p;
779 _M_future->_M_set_result(std::move(_M_storage));
783 template<typename> friend class packaged_task;
784 bool _M_satisfied() { return !static_cast<bool>(_M_storage); }
785 shared_ptr<_Future_state> _M_future;
786 _Future_ptr<_Future_result<void>>::type _M_storage;
789 // TODO: requires allocator concepts
791 template<typename _Result, class Alloc>
792 concept_map UsesAllocator<promise<_Result>, Alloc>
794 typedef Alloc allocator_type;
798 template<typename _Result, typename... _ArgTypes>
802 _S_run(promise<_Result>& __p, function<_Result(_ArgTypes...)>& __f,
805 __p.set_value(__f(std::forward<_ArgTypes>(__args)...));
809 // specialization used by packaged_task<void(...)>
810 template<typename... _ArgTypes>
811 struct _Run_task<void, _ArgTypes...>
814 _S_run(promise<void>& __p, function<void(_ArgTypes...)>& __f,
817 __f(std::forward<_ArgTypes>(__args)...);
823 template<typename _Result, typename... _ArgTypes>
824 class packaged_task<_Result(_ArgTypes...)>
827 typedef _Result result_type;
829 // construction and destruction
832 template<typename _Fn>
834 packaged_task(const _Fn& __fn) : _M_task(__fn) { }
836 template<typename _Fn>
838 packaged_task(_Fn&& __fn) : _M_task(std::move(__fn)) { }
841 packaged_task(_Result(*__fn)(_ArgTypes...)) : _M_task(__fn) { }
843 // TODO: requires allocator concepts
845 template<typename _Fn, typename _Allocator>
847 packaged_task(allocator_arg_t __tag, const _Allocator& __a, _Fn __fn)
848 : _M_task(__tag, __a, __fn), _M_promise(__tag, __a)
851 template<typename _Fn, typename _Allocator>
853 packaged_task(allocator_arg_t __tag, const _Allocator& __a, _Fn&& __fn)
854 : _M_task(__tag, __a, std::move(__fn)), _M_promise(__tag, __a)
858 ~packaged_task() = default;
861 packaged_task(packaged_task&) = delete;
862 packaged_task& operator=(packaged_task&) = delete;
865 packaged_task(packaged_task&& __other)
866 { this->swap(__other); }
868 packaged_task& operator=(packaged_task&& __other)
870 packaged_task(std::move(__other)).swap(*this);
875 swap(packaged_task& __other)
877 _M_task.swap(__other._M_task);
878 _M_promise.swap(__other._M_promise);
881 explicit operator bool() const { return static_cast<bool>(_M_task); }
884 unique_future<_Result>
889 return _M_promise.get_future();
891 __catch (const future_error& __e)
894 if (__e.code() == future_errc::future_already_retrieved)
895 throw std::bad_function_call();
903 operator()(_ArgTypes... __args)
905 if (!static_cast<bool>(_M_task) || _M_promise._M_satisfied())
908 throw std::bad_function_call();
916 _Run_task<_Result, _ArgTypes...>::_S_run(_M_promise, _M_task,
917 std::forward<_ArgTypes>(__args)...);
921 _M_promise.set_exception(current_exception());
925 void reset() { promise<_Result>().swap(_M_promise); }
928 function<_Result(_ArgTypes...)> _M_task;
929 promise<_Result> _M_promise;
932 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
933 // && _GLIBCXX_ATOMIC_BUILTINS_4
938 #endif // __GXX_EXPERIMENTAL_CXX0X__
940 #endif // _GLIBCXX_FUTURE