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>
46 #if defined(_GLIBCXX_HAS_GTHREADS) && defined(_GLIBCXX_USE_C99_STDINT_TR1) \
47 && defined(_GLIBCXX_ATOMIC_BUILTINS_4)
52 * @defgroup futures Futures
53 * @ingroup concurrency
55 * Classes for futures support.
59 /// Error code for futures
60 enum class future_errc
61 { broken_promise, future_already_retrieved, promise_already_satisfied };
63 // TODO: requires concepts
64 // concept_map ErrorCodeEnum<future_errc> { }
66 struct is_error_code_enum<future_errc> : public true_type { };
68 /// Points to a statically-allocated object derived from error_category.
69 extern const error_category* const future_category;
71 // TODO: requires constexpr
72 inline error_code make_error_code(future_errc __errc)
73 { return error_code(static_cast<int>(__errc), *future_category); }
75 // TODO: requires constexpr
76 inline error_condition make_error_condition(future_errc __errc)
77 { return error_condition(static_cast<int>(__errc), *future_category); }
79 /// Exception type thrown by futures.
80 class future_error : public logic_error
83 explicit future_error(future_errc __ec)
84 : logic_error("std::future_error"), _M_code(make_error_code(__ec))
87 const error_code& code() const throw() { return _M_code; }
89 const char* what() const throw() { return _M_code.message().c_str(); }
95 // Holds the result of a future
96 struct _Future_result_base
98 _Future_result_base() = default;
99 _Future_result_base(const _Future_result_base&) = delete;
100 _Future_result_base& operator=(const _Future_result_base&) = delete;
102 exception_ptr _M_error;
104 // _M_destroy() allows derived classes to control deallocation,
105 // which will be needed when allocator support is added to promise.
106 // See http://gcc.gnu.org/ml/libstdc++/2009-06/msg00032.html
107 virtual void _M_destroy() = 0;
110 void operator()(_Future_result_base* __fr) const { __fr->_M_destroy(); }
114 ~_Future_result_base() = default;
117 // TODO: use template alias when available
119 template<typename _Res>
120 using _Future_ptr = unique_ptr<_Res, _Future_result_base::_Deleter>;
122 template<typename _Res>
125 typedef unique_ptr<_Res, _Future_result_base::_Deleter> type;
128 // State shared between a promise and one or more associated futures.
131 typedef _Future_ptr<_Future_result_base>::type _Future_ptr_type;
134 _Future_state() : _M_result(), _M_retrieved(false) { }
136 _Future_state(const _Future_state&) = delete;
137 _Future_state& operator=(const _Future_state&) = delete;
141 { return _M_get() != 0; }
146 _Future_result_base* const __res = _M_get();
147 return __res && !(__res->_M_error == 0);
153 _Future_result_base* const __res = _M_get();
154 return __res && (__res->_M_error == 0);
160 unique_lock<mutex> __lock(_M_mutex);
162 _M_cond.wait(__lock, std::bind(&_Future_state::_M_ready, this));
166 template<typename _Rep, typename _Period>
168 wait_for(const chrono::duration<_Rep, _Period>& __rel)
170 unique_lock<mutex> __lock(_M_mutex);
171 return _M_ready() || _M_cond.wait_for(__lock, __rel,
172 std::bind(&_Future_state::_M_ready, this));
175 template<typename _Clock, typename _Duration>
177 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
179 unique_lock<mutex> __lock(_M_mutex);
180 return _M_ready() || _M_cond.wait_until(__lock, __abs,
181 std::bind(&_Future_state::_M_ready, this));
185 _M_set_result(_Future_ptr_type __res)
188 lock_guard<mutex> __lock(_M_mutex);
190 throw future_error(future_errc::promise_already_satisfied);
191 _M_result.swap(__res);
193 _M_cond.notify_all();
197 _M_break_promise(_Future_ptr_type __res)
199 if (static_cast<bool>(__res))
202 = std::copy_exception(future_error(future_errc::broken_promise));
204 lock_guard<mutex> __lock(_M_mutex);
205 _M_result.swap(__res);
207 _M_cond.notify_all();
211 // called when this object is passed to a unique_future
213 _M_set_retrieved_flag()
215 if (_M_retrieved.test_and_set())
216 throw future_error(future_errc::future_already_retrieved);
223 lock_guard<mutex> __lock(_M_mutex);
224 return _M_result.get();
227 bool _M_ready() const { return static_cast<bool>(_M_result); }
229 _Future_ptr_type _M_result;
231 condition_variable _M_cond;
232 atomic_flag _M_retrieved;
235 // workaround for CWG issue 664 and c++/34022
236 template<typename _Result, bool = is_scalar<_Result>::value>
237 struct _Move_future_result
239 typedef _Result&& __rval_type;
240 static _Result&& _S_move(_Result& __res) { return std::move(__res); }
243 // specialization for scalar types returns rvalue not rvalue-reference
244 template<typename _Result>
245 struct _Move_future_result<_Result, true>
247 typedef _Result __rval_type;
248 static _Result _S_move(_Result __res) { return __res; }
251 template<typename _Result>
252 struct _Future_result : _Future_result_base
254 _Future_result() : _M_initialized() { }
259 _M_value().~_Result();
262 // return lvalue, future will add const or rvalue-reference
264 { return *static_cast<_Result*>(_M_addr()); }
267 _M_set(const _Result& __res)
269 ::new (_M_addr()) _Result(__res);
270 _M_initialized = true;
274 _M_set(_Result&& __res)
276 typedef _Move_future_result<_Result> _Mover;
277 ::new (_M_addr()) _Result(_Mover::_S_move(__res));
278 _M_initialized = true;
282 void _M_destroy() { delete this; }
284 void* _M_addr() { return static_cast<void*>(&_M_storage); }
286 typename aligned_storage<sizeof(_Result),
287 alignment_of<_Result>::value>::type _M_storage;
291 template<typename _Result>
292 struct _Future_result<_Result&> : _Future_result_base
294 _Future_result() : _M_value_ptr() { }
296 _Result* _M_value_ptr;
298 void _M_destroy() { delete this; }
302 struct _Future_result<void> : _Future_result_base
304 void _M_destroy() { delete this; }
308 template<typename _Result>
312 template<typename _Result>
315 // common implementation for unique_future and shared_future
316 template<typename _Result>
321 _Future_impl(const _Future_impl&) = delete;
322 _Future_impl& operator=(const _Future_impl&) = delete;
324 // functions to check state and wait for ready
325 bool is_ready() const { return this->_M_state->is_ready(); }
327 bool has_exception() const { return this->_M_state->has_exception(); }
329 bool has_value() const { return this->_M_state->has_value(); }
331 void wait() const { this->_M_state->wait(); }
333 template<typename _Rep, typename _Period>
335 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
336 { return this->_M_state->wait_for(__rel); }
338 template<typename _Clock, typename _Duration>
340 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
341 { return this->_M_state->wait_until(__abs); }
344 // wait for the state to be ready and rethrow any stored exception
345 _Future_result<_Result>&
348 _Future_result_base& __res = this->_M_state->wait();
349 if (!(__res._M_error == 0))
350 rethrow_exception(__res._M_error);
351 return static_cast<_Future_result<_Result>&>(__res);
354 typedef shared_ptr<_Future_state> _State_ptr;
356 // construction of a unique_future by promise::get_future()
358 _Future_impl(const _State_ptr& __state)
361 if (static_cast<bool>(this->_M_state))
362 this->_M_state->_M_set_retrieved_flag();
364 throw future_error(future_errc::future_already_retrieved);
367 // copy construction from a shared_future
369 _Future_impl(const shared_future<_Result>&);
371 // move construction from a unique_future
373 _Future_impl(unique_future<_Result>&&);
379 template<typename _Result>
382 // primary template for unique_future
383 template<typename _Result>
384 class unique_future : public _Future_impl<_Result>
386 typedef _Move_future_result<_Result> _Mover;
390 unique_future(unique_future&& __uf) : _Base_type(std::move(__uf)) { }
393 unique_future(const unique_future&) = delete;
394 unique_future& operator=(const unique_future&) = delete;
396 // retrieving the value
397 typename _Mover::__rval_type
399 { return _Mover::_S_move(this->_M_get_result()._M_value()); }
402 typedef _Future_impl<_Result> _Base_type;
403 typedef typename _Base_type::_State_ptr _State_ptr;
405 friend class promise<_Result>;
408 unique_future(const _State_ptr& __state) : _Base_type(__state) { }
411 // partial specialization for unique_future<R&>
412 template<typename _Result>
413 class unique_future<_Result&> : public _Future_impl<_Result&>
417 unique_future(unique_future&& __uf) : _Base_type(std::move(__uf)) { }
420 unique_future(const unique_future&) = delete;
421 unique_future& operator=(const unique_future&) = delete;
423 // retrieving the value
424 _Result& get() { return *this->_M_get_result()._M_value_ptr; }
427 typedef _Future_impl<_Result&> _Base_type;
428 typedef typename _Base_type::_State_ptr _State_ptr;
430 friend class promise<_Result&>;
433 unique_future(const _State_ptr& __state) : _Base_type(__state) { }
436 // specialization for unique_future<void>
438 class unique_future<void> : public _Future_impl<void>
442 unique_future(unique_future&& __uf) : _Base_type(std::move(__uf)) { }
445 unique_future(const unique_future&) = delete;
446 unique_future& operator=(const unique_future&) = delete;
448 // retrieving the value
449 void get() { this->_M_get_result(); }
452 typedef _Future_impl<void> _Base_type;
453 typedef _Base_type::_State_ptr _State_ptr;
455 friend class promise<void>;
458 unique_future(const _State_ptr& __state) : _Base_type(__state) { }
461 // primary template for unique_future
462 template<typename _Result>
463 class shared_future : public _Future_impl<_Result>
467 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
469 /// Construct from a unique_future rvalue
470 shared_future(unique_future<_Result>&& __uf)
471 : _Base_type(std::move(__uf))
474 shared_future& operator=(const shared_future&) = delete;
476 // retrieving the value
479 { return this->_M_get_result()._M_value(); }
482 typedef _Future_impl<_Result> _Base_type;
485 // partial specialization for shared_future<R&>
486 template<typename _Result>
487 class shared_future<_Result&> : public _Future_impl<_Result&>
491 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
493 /// Construct from a unique_future rvalue
494 shared_future(unique_future<_Result&>&& __uf)
495 : _Base_type(std::move(__uf))
498 shared_future& operator=(const shared_future&) = delete;
500 // retrieving the value
501 _Result& get() { return *this->_M_get_result()._M_value_ptr; }
504 typedef _Future_impl<_Result&> _Base_type;
507 // specialization for shared_future<void>
509 class shared_future<void> : public _Future_impl<void>
513 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
515 /// Construct from a unique_future rvalue
516 shared_future(unique_future<void>&& __uf)
517 : _Base_type(std::move(__uf))
520 shared_future& operator=(const shared_future&) = delete;
522 // retrieving the value
523 void get() { this->_M_get_result(); }
526 typedef _Future_impl<void> _Base_type;
529 // now we can define the protected _Future_impl constructors
531 template<typename _Result>
532 _Future_impl<_Result>::_Future_impl(const shared_future<_Result>& __sf)
533 : _M_state(__sf._M_state)
536 template<typename _Result>
537 _Future_impl<_Result>::_Future_impl(unique_future<_Result>&& __uf)
538 : _M_state(std::move(__uf._M_state))
541 template<typename> class packaged_task; // undefined
543 // primary template for promise
544 template<typename _Result>
549 : _M_future(std::make_shared<_Future_state>()),
550 _M_storage(new _Future_result<_Result>())
553 promise(promise&& __rhs)
554 : _M_future(std::move(__rhs._M_future)),
555 _M_storage(std::move(__rhs._M_storage))
558 // TODO: requires allocator concepts
560 template<typename _Allocator>
561 promise(allocator_arg_t, const _Allocator& __a);
563 template<typename _Allocator>
564 promise(allocator_arg_t, const _Allocator&, promise&& __rhs);
567 promise(const promise&) = delete;
571 if (static_cast<bool>(_M_future) && !_M_future.unique())
572 _M_future->_M_break_promise(std::move(_M_storage));
577 operator=(promise&& __rhs)
579 promise(std::move(__rhs)).swap(*this);
583 promise& operator=(const promise&) = delete;
588 _M_future.swap(__rhs._M_future);
589 _M_storage.swap(__rhs._M_storage);
592 // retrieving the result
593 unique_future<_Result>
595 { return unique_future<_Result>(_M_future); }
597 // setting the result
599 set_value(const _Result& __r)
602 _M_storage->_M_set(__r);
603 _M_future->_M_set_result(std::move(_M_storage));
607 set_value(_Result&& __r)
610 _M_storage->_M_set(_Mover::_S_move(__r));
611 _M_future->_M_set_result(std::move(_M_storage));
615 set_exception(exception_ptr __p)
618 _M_storage->_M_error = __p;
619 _M_future->_M_set_result(std::move(_M_storage));
623 template<typename> friend class packaged_task;
624 typedef _Move_future_result<_Result> _Mover;
625 bool _M_satisfied() { return !static_cast<bool>(_M_storage); }
626 shared_ptr<_Future_state> _M_future;
627 typename _Future_ptr<_Future_result<_Result>>::type _M_storage;
630 // partial specialization for promise<R&>
631 template<typename _Result>
632 class promise<_Result&>
636 : _M_future(std::make_shared<_Future_state>()),
637 _M_storage(new _Future_result<_Result&>())
640 promise(promise&& __rhs)
641 : _M_future(std::move(__rhs._M_future)),
642 _M_storage(std::move(__rhs._M_storage))
645 // TODO: requires allocator concepts
647 template<typename _Allocator>
648 promise(allocator_arg_t, const _Allocator& __a);
650 template<typename _Allocator>
651 promise(allocator_arg_t, const _Allocator&, promise&& __rhs);
654 promise(const promise&) = delete;
658 if (static_cast<bool>(_M_future) && !_M_future.unique())
659 _M_future->_M_break_promise(std::move(_M_storage));
664 operator=(promise&& __rhs)
666 promise(std::move(__rhs)).swap(*this);
670 promise& operator=(const promise&) = delete;
675 _M_future.swap(__rhs._M_future);
676 _M_storage.swap(__rhs._M_storage);
679 // retrieving the result
680 unique_future<_Result&>
682 { return unique_future<_Result&>(_M_future); }
684 // setting the result
686 set_value(_Result& __r)
689 _M_storage->_M_value_ptr = &__r;
690 _M_future->_M_set_result(std::move(_M_storage));
694 set_exception(exception_ptr __p)
697 _M_storage->_M_error = __p;
698 _M_future->_M_set_result(std::move(_M_storage));
702 template<typename> friend class packaged_task;
703 bool _M_satisfied() { return !static_cast<bool>(_M_storage); }
704 shared_ptr<_Future_state> _M_future;
705 typename _Future_ptr<_Future_result<_Result&>>::type _M_storage;
708 // specialization for promise<void>
714 : _M_future(std::make_shared<_Future_state>()),
715 _M_storage(new _Future_result<void>())
718 promise(promise&& __rhs)
719 : _M_future(std::move(__rhs._M_future)),
720 _M_storage(std::move(__rhs._M_storage))
723 // TODO: requires allocator concepts
725 template<typename _Allocator>
726 promise(allocator_arg_t, const _Allocator& __a);
728 template<typename _Allocator>
729 promise(allocator_arg_t, const _Allocator&, promise&& __rhs);
732 promise(const promise&) = delete;
736 if (static_cast<bool>(_M_future) && !_M_future.unique())
737 _M_future->_M_break_promise(std::move(_M_storage));
742 operator=(promise&& __rhs)
744 promise(std::move(__rhs)).swap(*this);
748 promise& operator=(const promise&) = delete;
753 _M_future.swap(__rhs._M_future);
754 _M_storage.swap(__rhs._M_storage);
757 // retrieving the result
760 { return unique_future<void>(_M_future); }
762 // setting the result
766 _M_future->_M_set_result(std::move(_M_storage));
770 set_exception(exception_ptr __p)
773 _M_storage->_M_error = __p;
774 _M_future->_M_set_result(std::move(_M_storage));
778 template<typename> friend class packaged_task;
779 bool _M_satisfied() { return !static_cast<bool>(_M_storage); }
780 shared_ptr<_Future_state> _M_future;
781 _Future_ptr<_Future_result<void>>::type _M_storage;
784 // TODO: requires allocator concepts
786 template<typename _Result, class Alloc>
787 concept_map UsesAllocator<promise<_Result>, Alloc>
789 typedef Alloc allocator_type;
793 template<typename _Result, typename... _ArgTypes>
797 _S_run(promise<_Result>& __p, function<_Result(_ArgTypes...)>& __f,
800 __p.set_value(__f(std::forward<_ArgTypes>(__args)...));
804 // specialization used by packaged_task<void(...)>
805 template<typename... _ArgTypes>
806 struct _Run_task<void, _ArgTypes...>
809 _S_run(promise<void>& __p, function<void(_ArgTypes...)>& __f,
812 __f(std::forward<_ArgTypes>(__args)...);
817 template<typename _Result, typename... _ArgTypes>
818 class packaged_task<_Result(_ArgTypes...)>
821 typedef _Result result_type;
823 // construction and destruction
826 template<typename _Fn>
828 packaged_task(const _Fn& __fn) : _M_task(__fn) { }
830 template<typename _Fn>
832 packaged_task(_Fn&& __fn) : _M_task(std::move(__fn)) { }
835 packaged_task(_Result(*__fn)(_ArgTypes...)) : _M_task(__fn) { }
837 // TODO: requires allocator concepts
839 template<typename _Fn, typename _Allocator>
841 packaged_task(allocator_arg_t __tag, const _Allocator& __a, _Fn __fn)
842 : _M_task(__tag, __a, __fn), _M_promise(__tag, __a)
845 template<typename _Fn, typename _Allocator>
847 packaged_task(allocator_arg_t __tag, const _Allocator& __a, _Fn&& __fn)
848 : _M_task(__tag, __a, std::move(__fn)), _M_promise(__tag, __a)
852 ~packaged_task() = default;
855 packaged_task(packaged_task&) = delete;
856 packaged_task& operator=(packaged_task&) = delete;
859 packaged_task(packaged_task&& __other)
860 { this->swap(__other); }
862 packaged_task& operator=(packaged_task&& __other)
864 packaged_task(std::move(__other)).swap(*this);
869 swap(packaged_task& __other)
871 _M_task.swap(__other._M_task);
872 _M_promise.swap(__other._M_promise);
875 explicit operator bool() const { return static_cast<bool>(_M_task); }
878 unique_future<_Result>
883 return _M_promise.get_future();
885 catch (const future_error& __e)
887 if (__e.code() == future_errc::future_already_retrieved)
888 throw std::bad_function_call();
895 operator()(_ArgTypes... __args)
897 if (!static_cast<bool>(_M_task) || _M_promise._M_satisfied())
898 throw std::bad_function_call();
901 _Run_task<_Result, _ArgTypes...>::_S_run(_M_promise, _M_task,
902 std::forward<_ArgTypes>(__args)...);
906 _M_promise.set_exception(current_exception());
910 void reset() { promise<_Result>().swap(_M_promise); }
913 function<_Result(_ArgTypes...)> _M_task;
914 promise<_Result> _M_promise;
920 #endif // _GLIBCXX_HAS_GTHREADS && _GLIBCXX_USE_C99_STDINT_TR1
921 // && _GLIBCXX_ATOMIC_BUILTINS_4
923 #endif // __GXX_EXPERIMENTAL_CXX0X__
925 #endif // _GLIBCXX_FUTURE