2 // Copyright Oliver Kowalke 2013.
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt or copy at
5 // http://www.boost.org/LICENSE_1_0.txt)
7 #ifndef BOOST_FIBERS_PACKAGED_TASK_HPP
8 #define BOOST_FIBERS_PACKAGED_TASK_HPP
12 #include <type_traits>
15 #include <boost/config.hpp>
17 #include <boost/fiber/detail/convert.hpp>
18 #include <boost/fiber/detail/disable_overload.hpp>
19 #include <boost/fiber/exceptions.hpp>
20 #include <boost/fiber/future/detail/task_base.hpp>
21 #include <boost/fiber/future/detail/task_object.hpp>
22 #include <boost/fiber/future/future.hpp>
27 template< typename Signature >
30 template< typename R, typename ... Args >
31 class packaged_task< R( Args ... ) > {
33 typedef typename detail::task_base< R, Args ... >::ptr_t ptr_t;
35 bool obtained_{ false };
39 constexpr packaged_task() noexcept = default;
41 template< typename Fn,
42 typename = detail::disable_overload< packaged_task, Fn >
44 explicit packaged_task( Fn && fn) :
45 packaged_task{ std::allocator_arg,
46 std::allocator< packaged_task >{},
47 std::forward< Fn >( fn) } {
50 template< typename Fn,
53 explicit packaged_task( std::allocator_arg_t, Allocator const& alloc, Fn && fn) {
54 typedef detail::task_object<
55 typename std::decay< Fn >::type, Allocator, R, Args ...
57 typedef std::allocator_traits<
58 typename object_t::allocator_t
61 typename object_t::allocator_t a{ alloc };
62 typename traits_t::pointer ptr{ traits_t::allocate( a, 1) };
64 traits_t::construct( a, ptr, a, std::forward< Fn >( fn) );
66 traits_t::deallocate( a, ptr, 1);
69 task_.reset( convert( ptr) );
74 task_->owner_destroyed();
78 packaged_task( packaged_task const&) = delete;
79 packaged_task & operator=( packaged_task const&) = delete;
81 packaged_task( packaged_task && other) noexcept :
82 obtained_{ other.obtained_ },
83 task_{ std::move( other.task_) } {
84 other.obtained_ = false;
87 packaged_task & operator=( packaged_task && other) noexcept {
88 if ( this == & other) return * this;
89 packaged_task tmp{ std::move( other) };
94 void swap( packaged_task & other) noexcept {
95 std::swap( obtained_, other.obtained_);
96 task_.swap( other.task_);
99 bool valid() const noexcept {
100 return nullptr != task_.get();
103 future< R > get_future() {
105 throw future_already_retrieved{};
108 throw packaged_task_uninitialized{};
112 boost::static_pointer_cast< detail::shared_state< R > >( task_) };
115 void operator()( Args ... args) {
117 throw packaged_task_uninitialized{};
119 task_->run( std::forward< Args >( args) ... );
124 throw packaged_task_uninitialized{};
128 task_ = tmp.task_->reset();
133 template< typename Signature >
134 void swap( packaged_task< Signature > & l, packaged_task< Signature > & r) noexcept {
140 #endif // BOOST_FIBERS_PACKAGED_TASK_HPP