2 // experimental/impl/co_spawn.hpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
11 #ifndef BOOST_ASIO_EXPERIMENTAL_IMPL_CO_SPAWN_HPP
12 #define BOOST_ASIO_EXPERIMENTAL_IMPL_CO_SPAWN_HPP
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
18 #include <boost/asio/detail/config.hpp>
25 #include <boost/asio/async_result.hpp>
26 #include <boost/asio/detail/thread_context.hpp>
27 #include <boost/asio/detail/thread_info_base.hpp>
28 #include <boost/asio/detail/type_traits.hpp>
29 #include <boost/asio/dispatch.hpp>
30 #include <boost/asio/post.hpp>
32 #include <boost/asio/detail/push_options.hpp>
36 namespace experimental {
39 // Promise object for coroutine at top of thread-of-execution "stack".
40 template <typename Executor>
46 void operator()(awaiter* a)
53 typedef std::unique_ptr<awaiter, deleter> ptr;
55 typedef Executor executor_type;
60 static_cast<Executor*>(static_cast<void*>(executor_))->~Executor();
63 void set_executor(const Executor& ex)
65 new (&executor_) Executor(ex);
69 executor_type get_executor() const noexcept
71 return *static_cast<const Executor*>(static_cast<const void*>(executor_));
74 awaiter* get_return_object()
79 auto initial_suspend()
81 return std::experimental::suspend_always();
86 return std::experimental::suspend_always();
101 if (--ref_count_ == 0)
102 coroutine_handle<awaiter>::from_promise(*this).destroy();
105 void unhandled_exception()
107 pending_exception_ = std::current_exception();
110 void rethrow_unhandled_exception()
112 if (pending_exception_)
114 std::exception_ptr ex = std::exchange(pending_exception_, nullptr);
115 std::rethrow_exception(ex);
120 std::size_t ref_count_ = 0;
121 std::exception_ptr pending_exception_ = nullptr;
122 alignas(Executor) unsigned char executor_[sizeof(Executor)];
123 bool has_executor_ = false;
126 // Base promise for coroutines further down the thread-of-execution "stack".
127 template <typename Executor>
131 #if !defined(BOOST_ASIO_DISABLE_AWAITEE_RECYCLING)
132 void* operator new(std::size_t size)
134 return boost::asio::detail::thread_info_base::allocate(
135 boost::asio::detail::thread_info_base::awaitee_tag(),
136 boost::asio::detail::thread_context::thread_call_stack::top(),
140 void operator delete(void* pointer, std::size_t size)
142 boost::asio::detail::thread_info_base::deallocate(
143 boost::asio::detail::thread_info_base::awaitee_tag(),
144 boost::asio::detail::thread_context::thread_call_stack::top(),
147 #endif // !defined(BOOST_ASIO_DISABLE_AWAITEE_RECYCLING)
149 auto initial_suspend()
151 return std::experimental::suspend_never();
154 struct final_suspender
158 bool await_ready() const noexcept
163 void await_suspend(coroutine_handle<void>)
165 this_->wake_caller();
168 void await_resume() const noexcept
175 return final_suspender{this};
178 void set_except(std::exception_ptr e)
180 pending_exception_ = e;
183 void unhandled_exception()
185 set_except(std::current_exception());
188 void rethrow_exception()
190 if (pending_exception_)
192 std::exception_ptr ex = std::exchange(pending_exception_, nullptr);
193 std::rethrow_exception(ex);
197 awaiter<Executor>* top()
202 coroutine_handle<void> caller()
220 class awaitable_executor
223 explicit awaitable_executor(awaitee_base* a)
228 bool await_ready() const noexcept
230 return this_->awaiter_ != nullptr;
233 template <typename U, typename Ex>
234 void await_suspend(coroutine_handle<detail::awaitee<U, Ex>> h) noexcept
236 this_->resume_on_attach_ = h;
239 Executor await_resume()
241 return this_->awaiter_->get_executor();
248 awaitable_executor await_transform(this_coro::executor_t) noexcept
250 return awaitable_executor(this);
253 class awaitable_token
256 explicit awaitable_token(awaitee_base* a)
261 bool await_ready() const noexcept
263 return this_->awaiter_ != nullptr;
266 template <typename U, typename Ex>
267 void await_suspend(coroutine_handle<detail::awaitee<U, Ex>> h) noexcept
269 this_->resume_on_attach_ = h;
272 await_token<Executor> await_resume()
274 return await_token<Executor>(this_->awaiter_);
281 awaitable_token await_transform(this_coro::token_t) noexcept
283 return awaitable_token(this);
286 template <typename T>
287 awaitable<T, Executor> await_transform(awaitable<T, Executor>& t) const
292 template <typename T>
293 awaitable<T, Executor> await_transform(awaitable<T, Executor>&& t) const
298 std::experimental::suspend_always await_transform(
299 std::experimental::suspend_always) const
301 return std::experimental::suspend_always();
304 void attach_caller(coroutine_handle<awaiter<Executor>> h)
307 this->attach_callees(&h.promise());
310 template <typename U>
311 void attach_caller(coroutine_handle<awaitee<U, Executor>> h)
314 if (h.promise().awaiter_)
315 this->attach_callees(h.promise().awaiter_);
317 h.promise().unattached_callee_ = this;
320 void attach_callees(awaiter<Executor>* a)
322 for (awaitee_base* curr = this; curr != nullptr;
323 curr = std::exchange(curr->unattached_callee_, nullptr))
326 if (curr->resume_on_attach_)
327 return std::exchange(curr->resume_on_attach_, nullptr).resume();
332 awaiter<Executor>* awaiter_ = nullptr;
333 coroutine_handle<void> caller_ = nullptr;
334 awaitee_base<Executor>* unattached_callee_ = nullptr;
335 std::exception_ptr pending_exception_ = nullptr;
336 coroutine_handle<void> resume_on_attach_ = nullptr;
340 // Promise object for coroutines further down the thread-of-execution "stack".
341 template <typename T, typename Executor>
343 : public awaitee_base<Executor>
350 awaitee(awaitee&& other) noexcept
351 : awaitee_base<Executor>(std::move(other))
358 static_cast<T*>(static_cast<void*>(result_))->~T();
361 awaitable<T, Executor> get_return_object()
363 return awaitable<T, Executor>(this);
366 template <typename U>
367 void return_value(U&& u)
369 new (&result_) T(std::forward<U>(u));
375 this->caller_ = nullptr;
376 this->rethrow_exception();
377 return std::move(*static_cast<T*>(static_cast<void*>(result_)));
381 alignas(T) unsigned char result_[sizeof(T)];
382 bool has_result_ = false;
385 // Promise object for coroutines further down the thread-of-execution "stack".
386 template <typename Executor>
387 class awaitee<void, Executor>
388 : public awaitee_base<Executor>
391 awaitable<void, Executor> get_return_object()
393 return awaitable<void, Executor>(this);
402 this->caller_ = nullptr;
403 this->rethrow_exception();
407 template <typename Executor>
411 typedef Executor executor_type;
413 awaiter_task(awaiter<Executor>* a)
414 : awaiter_(a->add_ref())
418 awaiter_task(awaiter_task&& other) noexcept
419 : awaiter_(std::exchange(other.awaiter_, nullptr))
427 // Coroutine "stack unwinding" must be performed through the executor.
428 executor_type ex(awaiter_->get_executor());
430 [a = std::move(awaiter_)]() mutable
432 typename awaiter<Executor>::ptr(std::move(a));
437 executor_type get_executor() const noexcept
439 return awaiter_->get_executor();
443 typename awaiter<Executor>::ptr awaiter_;
446 template <typename Executor>
447 class co_spawn_handler : public awaiter_task<Executor>
450 using awaiter_task<Executor>::awaiter_task;
454 typename awaiter<Executor>::ptr ptr(std::move(this->awaiter_));
455 coroutine_handle<awaiter<Executor>>::from_promise(*ptr.get()).resume();
459 template <typename Executor, typename T>
460 class await_handler_base : public awaiter_task<Executor>
463 typedef awaitable<T, Executor> awaitable_type;
465 await_handler_base(await_token<Executor> token)
466 : awaiter_task<Executor>(token.awaiter_),
471 await_handler_base(await_handler_base&& other) noexcept
472 : awaiter_task<Executor>(std::move(other)),
473 awaitee_(std::exchange(other.awaitee_, nullptr))
477 void attach_awaitee(const awaitable<T, Executor>& a)
479 awaitee_ = a.awaitee_;
483 awaitee<T, Executor>* awaitee_;
486 template <typename, typename...> class await_handler;
488 template <typename Executor>
489 class await_handler<Executor, void>
490 : public await_handler_base<Executor, void>
493 using await_handler_base<Executor, void>::await_handler_base;
497 typename awaiter<Executor>::ptr ptr(std::move(this->awaiter_));
498 this->awaitee_->return_void();
499 this->awaitee_->wake_caller();
500 ptr->rethrow_unhandled_exception();
504 template <typename Executor>
505 class await_handler<Executor, boost::system::error_code>
506 : public await_handler_base<Executor, void>
509 typedef void return_type;
511 using await_handler_base<Executor, void>::await_handler_base;
513 void operator()(const boost::system::error_code& ec)
515 typename awaiter<Executor>::ptr ptr(std::move(this->awaiter_));
518 this->awaitee_->set_except(
519 std::make_exception_ptr(boost::system::system_error(ec)));
522 this->awaitee_->return_void();
523 this->awaitee_->wake_caller();
524 ptr->rethrow_unhandled_exception();
528 template <typename Executor>
529 class await_handler<Executor, std::exception_ptr>
530 : public await_handler_base<Executor, void>
533 using await_handler_base<Executor, void>::await_handler_base;
535 void operator()(std::exception_ptr ex)
537 typename awaiter<Executor>::ptr ptr(std::move(this->awaiter_));
539 this->awaitee_->set_except(ex);
541 this->awaitee_->return_void();
542 this->awaitee_->wake_caller();
543 ptr->rethrow_unhandled_exception();
547 template <typename Executor, typename T>
548 class await_handler<Executor, T>
549 : public await_handler_base<Executor, T>
552 using await_handler_base<Executor, T>::await_handler_base;
554 template <typename Arg>
555 void operator()(Arg&& arg)
557 typename awaiter<Executor>::ptr ptr(std::move(this->awaiter_));
558 this->awaitee_->return_value(std::forward<Arg>(arg));
559 this->awaitee_->wake_caller();
560 ptr->rethrow_unhandled_exception();
564 template <typename Executor, typename T>
565 class await_handler<Executor, boost::system::error_code, T>
566 : public await_handler_base<Executor, T>
569 using await_handler_base<Executor, T>::await_handler_base;
571 template <typename Arg>
572 void operator()(const boost::system::error_code& ec, Arg&& arg)
574 typename awaiter<Executor>::ptr ptr(std::move(this->awaiter_));
577 this->awaitee_->set_except(
578 std::make_exception_ptr(boost::system::system_error(ec)));
581 this->awaitee_->return_value(std::forward<Arg>(arg));
582 this->awaitee_->wake_caller();
583 ptr->rethrow_unhandled_exception();
587 template <typename Executor, typename T>
588 class await_handler<Executor, std::exception_ptr, T>
589 : public await_handler_base<Executor, T>
592 using await_handler_base<Executor, T>::await_handler_base;
594 template <typename Arg>
595 void operator()(std::exception_ptr ex, Arg&& arg)
597 typename awaiter<Executor>::ptr ptr(std::move(this->awaiter_));
599 this->awaitee_->set_except(ex);
601 this->awaitee_->return_value(std::forward<Arg>(arg));
602 this->awaitee_->wake_caller();
603 ptr->rethrow_unhandled_exception();
607 template <typename Executor, typename... Ts>
609 : public await_handler_base<Executor, std::tuple<Ts...>>
612 using await_handler_base<Executor, std::tuple<Ts...>>::await_handler_base;
614 template <typename... Args>
615 void operator()(Args&&... args)
617 typename awaiter<Executor>::ptr ptr(std::move(this->awaiter_));
618 this->awaitee_->return_value(
619 std::forward_as_tuple(std::forward<Args>(args)...));
620 this->awaitee_->wake_caller();
621 ptr->rethrow_unhandled_exception();
625 template <typename Executor, typename... Ts>
626 class await_handler<Executor, boost::system::error_code, Ts...>
627 : public await_handler_base<Executor, std::tuple<Ts...>>
630 using await_handler_base<Executor, std::tuple<Ts...>>::await_handler_base;
632 template <typename... Args>
633 void operator()(const boost::system::error_code& ec, Args&&... args)
635 typename awaiter<Executor>::ptr ptr(std::move(this->awaiter_));
638 this->awaitee_->set_except(
639 std::make_exception_ptr(boost::system::system_error(ec)));
643 this->awaitee_->return_value(
644 std::forward_as_tuple(std::forward<Args>(args)...));
646 this->awaitee_->wake_caller();
647 ptr->rethrow_unhandled_exception();
651 template <typename Executor, typename... Ts>
652 class await_handler<Executor, std::exception_ptr, Ts...>
653 : public await_handler_base<Executor, std::tuple<Ts...>>
656 using await_handler_base<Executor, std::tuple<Ts...>>::await_handler_base;
658 template <typename... Args>
659 void operator()(std::exception_ptr ex, Args&&... args)
661 typename awaiter<Executor>::ptr ptr(std::move(this->awaiter_));
663 this->awaitee_->set_except(ex);
666 this->awaitee_->return_value(
667 std::forward_as_tuple(std::forward<Args>(args)...));
669 this->awaitee_->wake_caller();
670 ptr->rethrow_unhandled_exception();
674 template <typename T>
675 struct awaitable_signature;
677 template <typename T, typename Executor>
678 struct awaitable_signature<awaitable<T, Executor>>
680 typedef void type(std::exception_ptr, T);
683 template <typename Executor>
684 struct awaitable_signature<awaitable<void, Executor>>
686 typedef void type(std::exception_ptr);
689 template <typename T, typename Executor, typename F, typename Handler>
690 awaiter<Executor>* co_spawn_entry_point(awaitable<T, Executor>*,
691 executor_work_guard<Executor> work_guard, F f, Handler handler)
701 (dispatch)(work_guard.get_executor(),
702 [handler = std::move(handler), t = std::move(t)]() mutable
704 handler(std::exception_ptr(), std::move(t));
712 (dispatch)(work_guard.get_executor(),
713 [handler = std::move(handler), e = std::current_exception()]() mutable
720 template <typename Executor, typename F, typename Handler>
721 awaiter<Executor>* co_spawn_entry_point(awaitable<void, Executor>*,
722 executor_work_guard<Executor> work_guard, F f, Handler handler)
724 std::exception_ptr e = nullptr;
732 e = std::current_exception();
735 (dispatch)(work_guard.get_executor(),
736 [handler = std::move(handler), e]() mutable
742 template <typename Executor, typename F, typename CompletionToken>
743 auto co_spawn(const Executor& ex, F&& f, CompletionToken&& token)
745 typedef typename result_of<F()>::type awaitable_type;
746 typedef typename awaitable_type::executor_type executor_type;
747 typedef typename awaitable_signature<awaitable_type>::type signature_type;
749 async_completion<CompletionToken, signature_type> completion(token);
751 executor_type ex2(ex);
752 auto work_guard = make_work_guard(completion.completion_handler, ex2);
754 auto* a = (co_spawn_entry_point)(
755 static_cast<awaitable_type*>(nullptr), std::move(work_guard),
756 std::forward<F>(f), std::move(completion.completion_handler));
758 a->set_executor(ex2);
759 (post)(co_spawn_handler<executor_type>(a));
761 return completion.result.get();
764 #if defined(_MSC_VER)
765 # pragma warning(push)
766 # pragma warning(disable:4033)
767 #endif // defined(_MSC_VER)
769 #if defined(_MSC_VER)
770 template <typename T> T dummy_return()
772 return std::move(*static_cast<T*>(nullptr));
776 inline void dummy_return()
779 #endif // defined(_MSC_VER)
781 template <typename Awaitable>
782 inline Awaitable make_dummy_awaitable()
784 for (;;) co_await std::experimental::suspend_always();
785 #if defined(_MSC_VER)
786 co_return dummy_return<typename Awaitable::value_type>();
787 #endif // defined(_MSC_VER)
790 #if defined(_MSC_VER)
791 # pragma warning(pop)
792 #endif // defined(_MSC_VER)
794 } // namespace detail
795 } // namespace experimental
797 template <typename Executor, typename R, typename... Args>
798 class async_result<experimental::await_token<Executor>, R(Args...)>
801 typedef experimental::detail::await_handler<
802 Executor, typename decay<Args>::type...> completion_handler_type;
804 typedef typename experimental::detail::await_handler<
805 Executor, Args...>::awaitable_type return_type;
807 async_result(completion_handler_type& h)
808 : awaitable_(experimental::detail::make_dummy_awaitable<return_type>())
810 h.attach_awaitee(awaitable_);
815 return std::move(awaitable_);
819 return_type awaitable_;
822 #if !defined(BOOST_ASIO_NO_DEPRECATED)
824 template <typename Executor, typename R, typename... Args>
825 struct handler_type<experimental::await_token<Executor>, R(Args...)>
827 typedef experimental::detail::await_handler<
828 Executor, typename decay<Args>::type...> type;
831 template <typename Executor, typename... Args>
832 class async_result<experimental::detail::await_handler<Executor, Args...>>
835 typedef typename experimental::detail::await_handler<
836 Executor, Args...>::awaitable_type type;
838 async_result(experimental::detail::await_handler<Executor, Args...>& h)
839 : awaitable_(experimental::detail::make_dummy_awaitable<type>())
841 h.attach_awaitee(awaitable_);
846 return std::move(awaitable_);
853 #endif // !defined(BOOST_ASIO_NO_DEPRECATED)
858 namespace std { namespace experimental {
860 template <typename Executor, typename... Args>
861 struct coroutine_traits<
862 boost::asio::experimental::detail::awaiter<Executor>*, Args...>
864 typedef boost::asio::experimental::detail::awaiter<Executor> promise_type;
867 template <typename T, typename Executor, typename... Args>
868 struct coroutine_traits<
869 boost::asio::experimental::awaitable<T, Executor>, Args...>
871 typedef boost::asio::experimental::detail::awaitee<T, Executor> promise_type;
874 }} // namespace std::experimental
876 #include <boost/asio/detail/pop_options.hpp>
878 #endif // BOOST_ASIO_EXPERIMENTAL_IMPL_CO_SPAWN_HPP