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 // Forward declarations.
96 template<typename _Result>
99 template<typename _Result>
105 template<typename _Result>
108 // Holds the result of a future
109 struct _Future_result_base
111 _Future_result_base() = default;
112 _Future_result_base(const _Future_result_base&) = delete;
113 _Future_result_base& operator=(const _Future_result_base&) = delete;
115 exception_ptr _M_error;
117 // _M_destroy() allows derived classes to control deallocation,
118 // which will be needed when allocator support is added to promise.
119 // See http://gcc.gnu.org/ml/libstdc++/2009-06/msg00032.html
120 virtual void _M_destroy() = 0;
123 void operator()(_Future_result_base* __fr) const { __fr->_M_destroy(); }
127 ~_Future_result_base() = default;
130 // TODO: use template alias when available
132 template<typename _Res>
133 using _Future_ptr = unique_ptr<_Res, _Future_result_base::_Deleter>;
135 template<typename _Res>
138 typedef unique_ptr<_Res, _Future_result_base::_Deleter> type;
141 // State shared between a promise and one or more associated futures.
144 typedef _Future_ptr<_Future_result_base>::type _Future_ptr_type;
147 _Future_state() : _M_result(), _M_retrieved(false) { }
149 _Future_state(const _Future_state&) = delete;
150 _Future_state& operator=(const _Future_state&) = delete;
154 { return _M_get() != 0; }
159 _Future_result_base* const __res = _M_get();
160 return __res && !(__res->_M_error == 0);
166 _Future_result_base* const __res = _M_get();
167 return __res && (__res->_M_error == 0);
173 unique_lock<mutex> __lock(_M_mutex);
175 _M_cond.wait(__lock, std::bind(&_Future_state::_M_ready, this));
179 template<typename _Rep, typename _Period>
181 wait_for(const chrono::duration<_Rep, _Period>& __rel)
183 unique_lock<mutex> __lock(_M_mutex);
184 return _M_ready() || _M_cond.wait_for(__lock, __rel,
185 std::bind(&_Future_state::_M_ready, this));
188 template<typename _Clock, typename _Duration>
190 wait_until(const chrono::time_point<_Clock, _Duration>& __abs)
192 unique_lock<mutex> __lock(_M_mutex);
193 return _M_ready() || _M_cond.wait_until(__lock, __abs,
194 std::bind(&_Future_state::_M_ready, this));
198 _M_set_result(_Future_ptr_type __res)
201 lock_guard<mutex> __lock(_M_mutex);
203 throw future_error(future_errc::promise_already_satisfied);
204 _M_result.swap(__res);
206 _M_cond.notify_all();
210 _M_break_promise(_Future_ptr_type __res)
212 if (static_cast<bool>(__res))
215 = std::copy_exception(future_error(future_errc::broken_promise));
217 lock_guard<mutex> __lock(_M_mutex);
218 _M_result.swap(__res);
220 _M_cond.notify_all();
224 // called when this object is passed to a unique_future
226 _M_set_retrieved_flag()
228 if (_M_retrieved.test_and_set())
229 throw future_error(future_errc::future_already_retrieved);
236 lock_guard<mutex> __lock(_M_mutex);
237 return _M_result.get();
240 bool _M_ready() const { return static_cast<bool>(_M_result); }
242 _Future_ptr_type _M_result;
244 condition_variable _M_cond;
245 atomic_flag _M_retrieved;
248 // workaround for CWG issue 664 and c++/34022
249 template<typename _Result, bool = is_scalar<_Result>::value>
250 struct _Move_future_result
252 typedef _Result&& __rval_type;
253 static _Result&& _S_move(_Result& __res) { return std::move(__res); }
256 // specialization for scalar types returns rvalue not rvalue-reference
257 template<typename _Result>
258 struct _Move_future_result<_Result, true>
260 typedef _Result __rval_type;
261 static _Result _S_move(_Result __res) { return __res; }
264 template<typename _Result>
265 struct _Future_result : _Future_result_base
267 _Future_result() : _M_initialized() { }
272 _M_value().~_Result();
275 // return lvalue, future will add const or rvalue-reference
277 { return *static_cast<_Result*>(_M_addr()); }
280 _M_set(const _Result& __res)
282 ::new (_M_addr()) _Result(__res);
283 _M_initialized = true;
287 _M_set(_Result&& __res)
289 typedef _Move_future_result<_Result> _Mover;
290 ::new (_M_addr()) _Result(_Mover::_S_move(__res));
291 _M_initialized = true;
295 void _M_destroy() { delete this; }
297 void* _M_addr() { return static_cast<void*>(&_M_storage); }
299 typename aligned_storage<sizeof(_Result),
300 alignment_of<_Result>::value>::type _M_storage;
304 template<typename _Result>
305 struct _Future_result<_Result&> : _Future_result_base
307 _Future_result() : _M_value_ptr() { }
309 _Result* _M_value_ptr;
311 void _M_destroy() { delete this; }
315 struct _Future_result<void> : _Future_result_base
317 void _M_destroy() { delete this; }
320 // common implementation for unique_future and shared_future
321 template<typename _Result>
326 _Future_impl(const _Future_impl&) = delete;
327 _Future_impl& operator=(const _Future_impl&) = delete;
329 // functions to check state and wait for ready
330 bool is_ready() const { return this->_M_state->is_ready(); }
332 bool has_exception() const { return this->_M_state->has_exception(); }
334 bool has_value() const { return this->_M_state->has_value(); }
336 void wait() const { this->_M_state->wait(); }
338 template<typename _Rep, typename _Period>
340 wait_for(const chrono::duration<_Rep, _Period>& __rel) const
341 { return this->_M_state->wait_for(__rel); }
343 template<typename _Clock, typename _Duration>
345 wait_until(const chrono::time_point<_Clock, _Duration>& __abs) const
346 { return this->_M_state->wait_until(__abs); }
349 // wait for the state to be ready and rethrow any stored exception
350 _Future_result<_Result>&
353 _Future_result_base& __res = this->_M_state->wait();
354 if (!(__res._M_error == 0))
355 rethrow_exception(__res._M_error);
356 return static_cast<_Future_result<_Result>&>(__res);
359 typedef shared_ptr<_Future_state> _State_ptr;
361 // construction of a unique_future by promise::get_future()
363 _Future_impl(const _State_ptr& __state)
366 if (static_cast<bool>(this->_M_state))
367 this->_M_state->_M_set_retrieved_flag();
369 throw future_error(future_errc::future_already_retrieved);
372 // copy construction from a shared_future
374 _Future_impl(const shared_future<_Result>&);
376 // move construction from a unique_future
378 _Future_impl(unique_future<_Result>&&);
383 /// primary template for unique_future
384 template<typename _Result>
385 class unique_future : public _Future_impl<_Result>
387 typedef _Move_future_result<_Result> _Mover;
391 unique_future(unique_future&& __uf) : _Base_type(std::move(__uf)) { }
394 unique_future(const unique_future&) = delete;
395 unique_future& operator=(const unique_future&) = delete;
397 // retrieving the value
398 typename _Mover::__rval_type
400 { return _Mover::_S_move(this->_M_get_result()._M_value()); }
403 typedef _Future_impl<_Result> _Base_type;
404 typedef typename _Base_type::_State_ptr _State_ptr;
406 friend class promise<_Result>;
409 unique_future(const _State_ptr& __state) : _Base_type(__state) { }
412 // partial specialization for unique_future<R&>
413 template<typename _Result>
414 class unique_future<_Result&> : public _Future_impl<_Result&>
418 unique_future(unique_future&& __uf) : _Base_type(std::move(__uf)) { }
421 unique_future(const unique_future&) = delete;
422 unique_future& operator=(const unique_future&) = delete;
424 // retrieving the value
425 _Result& get() { return *this->_M_get_result()._M_value_ptr; }
428 typedef _Future_impl<_Result&> _Base_type;
429 typedef typename _Base_type::_State_ptr _State_ptr;
431 friend class promise<_Result&>;
434 unique_future(const _State_ptr& __state) : _Base_type(__state) { }
437 // specialization for unique_future<void>
439 class unique_future<void> : public _Future_impl<void>
443 unique_future(unique_future&& __uf) : _Base_type(std::move(__uf)) { }
446 unique_future(const unique_future&) = delete;
447 unique_future& operator=(const unique_future&) = delete;
449 // retrieving the value
450 void get() { this->_M_get_result(); }
453 typedef _Future_impl<void> _Base_type;
454 typedef _Base_type::_State_ptr _State_ptr;
456 friend class promise<void>;
459 unique_future(const _State_ptr& __state) : _Base_type(__state) { }
462 /// primary template for shared_future
463 template<typename _Result>
464 class shared_future : public _Future_impl<_Result>
468 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
470 /// Construct from a unique_future rvalue
471 shared_future(unique_future<_Result>&& __uf)
472 : _Base_type(std::move(__uf))
475 shared_future& operator=(const shared_future&) = delete;
477 // retrieving the value
480 { return this->_M_get_result()._M_value(); }
483 typedef _Future_impl<_Result> _Base_type;
486 // partial specialization for shared_future<R&>
487 template<typename _Result>
488 class shared_future<_Result&> : public _Future_impl<_Result&>
492 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
494 /// Construct from a unique_future rvalue
495 shared_future(unique_future<_Result&>&& __uf)
496 : _Base_type(std::move(__uf))
499 shared_future& operator=(const shared_future&) = delete;
501 // retrieving the value
502 _Result& get() { return *this->_M_get_result()._M_value_ptr; }
505 typedef _Future_impl<_Result&> _Base_type;
508 // specialization for shared_future<void>
510 class shared_future<void> : public _Future_impl<void>
514 shared_future(const shared_future& __sf) : _Base_type(__sf) { }
516 /// Construct from a unique_future rvalue
517 shared_future(unique_future<void>&& __uf)
518 : _Base_type(std::move(__uf))
521 shared_future& operator=(const shared_future&) = delete;
523 // retrieving the value
524 void get() { this->_M_get_result(); }
527 typedef _Future_impl<void> _Base_type;
530 // now we can define the protected _Future_impl constructors
532 template<typename _Result>
533 _Future_impl<_Result>::_Future_impl(const shared_future<_Result>& __sf)
534 : _M_state(__sf._M_state)
537 template<typename _Result>
538 _Future_impl<_Result>::_Future_impl(unique_future<_Result>&& __uf)
539 : _M_state(std::move(__uf._M_state))
542 /// primary template for promise
543 template<typename _Result>
548 : _M_future(std::make_shared<_Future_state>()),
549 _M_storage(new _Future_result<_Result>())
552 promise(promise&& __rhs)
553 : _M_future(std::move(__rhs._M_future)),
554 _M_storage(std::move(__rhs._M_storage))
557 // TODO: requires allocator concepts
559 template<typename _Allocator>
560 promise(allocator_arg_t, const _Allocator& __a);
562 template<typename _Allocator>
563 promise(allocator_arg_t, const _Allocator&, promise&& __rhs);
566 promise(const promise&) = delete;
570 if (static_cast<bool>(_M_future) && !_M_future.unique())
571 _M_future->_M_break_promise(std::move(_M_storage));
576 operator=(promise&& __rhs)
578 promise(std::move(__rhs)).swap(*this);
582 promise& operator=(const promise&) = delete;
587 _M_future.swap(__rhs._M_future);
588 _M_storage.swap(__rhs._M_storage);
591 // retrieving the result
592 unique_future<_Result>
594 { return unique_future<_Result>(_M_future); }
596 // setting the result
598 set_value(const _Result& __r)
601 _M_storage->_M_set(__r);
602 _M_future->_M_set_result(std::move(_M_storage));
606 set_value(_Result&& __r)
609 _M_storage->_M_set(_Mover::_S_move(__r));
610 _M_future->_M_set_result(std::move(_M_storage));
614 set_exception(exception_ptr __p)
617 _M_storage->_M_error = __p;
618 _M_future->_M_set_result(std::move(_M_storage));
622 template<typename> friend class packaged_task;
623 typedef _Move_future_result<_Result> _Mover;
624 bool _M_satisfied() { return !static_cast<bool>(_M_storage); }
625 shared_ptr<_Future_state> _M_future;
626 typename _Future_ptr<_Future_result<_Result>>::type _M_storage;
629 // partial specialization for promise<R&>
630 template<typename _Result>
631 class promise<_Result&>
635 : _M_future(std::make_shared<_Future_state>()),
636 _M_storage(new _Future_result<_Result&>())
639 promise(promise&& __rhs)
640 : _M_future(std::move(__rhs._M_future)),
641 _M_storage(std::move(__rhs._M_storage))
644 // TODO: requires allocator concepts
646 template<typename _Allocator>
647 promise(allocator_arg_t, const _Allocator& __a);
649 template<typename _Allocator>
650 promise(allocator_arg_t, const _Allocator&, promise&& __rhs);
653 promise(const promise&) = delete;
657 if (static_cast<bool>(_M_future) && !_M_future.unique())
658 _M_future->_M_break_promise(std::move(_M_storage));
663 operator=(promise&& __rhs)
665 promise(std::move(__rhs)).swap(*this);
669 promise& operator=(const promise&) = delete;
674 _M_future.swap(__rhs._M_future);
675 _M_storage.swap(__rhs._M_storage);
678 // retrieving the result
679 unique_future<_Result&>
681 { return unique_future<_Result&>(_M_future); }
683 // setting the result
685 set_value(_Result& __r)
688 _M_storage->_M_value_ptr = &__r;
689 _M_future->_M_set_result(std::move(_M_storage));
693 set_exception(exception_ptr __p)
696 _M_storage->_M_error = __p;
697 _M_future->_M_set_result(std::move(_M_storage));
701 template<typename> friend class packaged_task;
702 bool _M_satisfied() { return !static_cast<bool>(_M_storage); }
703 shared_ptr<_Future_state> _M_future;
704 typename _Future_ptr<_Future_result<_Result&>>::type _M_storage;
707 // specialization for promise<void>
713 : _M_future(std::make_shared<_Future_state>()),
714 _M_storage(new _Future_result<void>())
717 promise(promise&& __rhs)
718 : _M_future(std::move(__rhs._M_future)),
719 _M_storage(std::move(__rhs._M_storage))
722 // TODO: requires allocator concepts
724 template<typename _Allocator>
725 promise(allocator_arg_t, const _Allocator& __a);
727 template<typename _Allocator>
728 promise(allocator_arg_t, const _Allocator&, promise&& __rhs);
731 promise(const promise&) = delete;
735 if (static_cast<bool>(_M_future) && !_M_future.unique())
736 _M_future->_M_break_promise(std::move(_M_storage));
741 operator=(promise&& __rhs)
743 promise(std::move(__rhs)).swap(*this);
747 promise& operator=(const promise&) = delete;
752 _M_future.swap(__rhs._M_future);
753 _M_storage.swap(__rhs._M_storage);
756 // retrieving the result
759 { return unique_future<void>(_M_future); }
761 // setting the result
765 _M_future->_M_set_result(std::move(_M_storage));
769 set_exception(exception_ptr __p)
772 _M_storage->_M_error = __p;
773 _M_future->_M_set_result(std::move(_M_storage));
777 template<typename> friend class packaged_task;
778 bool _M_satisfied() { return !static_cast<bool>(_M_storage); }
779 shared_ptr<_Future_state> _M_future;
780 _Future_ptr<_Future_result<void>>::type _M_storage;
783 // TODO: requires allocator concepts
785 template<typename _Result, class Alloc>
786 concept_map UsesAllocator<promise<_Result>, Alloc>
788 typedef Alloc allocator_type;
792 template<typename _Result, typename... _ArgTypes>
796 _S_run(promise<_Result>& __p, function<_Result(_ArgTypes...)>& __f,
799 __p.set_value(__f(std::forward<_ArgTypes>(__args)...));
803 // specialization used by packaged_task<void(...)>
804 template<typename... _ArgTypes>
805 struct _Run_task<void, _ArgTypes...>
808 _S_run(promise<void>& __p, function<void(_ArgTypes...)>& __f,
811 __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