Allow nested calls to completion handler when using yield_context.
diff --git a/asio/include/asio/impl/spawn.hpp b/asio/include/asio/impl/spawn.hpp index 6e2708c..4e00809 100644 --- a/asio/include/asio/impl/spawn.hpp +++ b/asio/include/asio/impl/spawn.hpp
@@ -17,6 +17,7 @@ #include "asio/detail/config.hpp" #include "asio/async_result.hpp" +#include "asio/detail/atomic_count.hpp" #include "asio/detail/handler_alloc_helpers.hpp" #include "asio/detail/handler_cont_helpers.hpp" #include "asio/detail/handler_invoke_helpers.hpp" @@ -37,6 +38,7 @@ : coro_(ctx.coro_.lock()), ca_(ctx.ca_), handler_(ctx.handler_), + ready_(0), ec_(ctx.ec_), value_(0) { @@ -46,20 +48,23 @@ { *ec_ = asio::error_code(); *value_ = ASIO_MOVE_CAST(T)(value); - (*coro_)(); + if (--*ready_ == 0) + (*coro_)(); } void operator()(asio::error_code ec, T value) { *ec_ = ec; *value_ = ASIO_MOVE_CAST(T)(value); - (*coro_)(); + if (--*ready_ == 0) + (*coro_)(); } //private: shared_ptr<typename basic_yield_context<Handler>::callee_type> coro_; typename basic_yield_context<Handler>::caller_type& ca_; Handler& handler_; + atomic_count* ready_; asio::error_code* ec_; T* value_; }; @@ -72,6 +77,7 @@ : coro_(ctx.coro_.lock()), ca_(ctx.ca_), handler_(ctx.handler_), + ready_(0), ec_(ctx.ec_) { } @@ -79,19 +85,22 @@ void operator()() { *ec_ = asio::error_code(); - (*coro_)(); + if (--*ready_ == 0) + (*coro_)(); } void operator()(asio::error_code ec) { *ec_ = ec; - (*coro_)(); + if (--*ready_ == 0) + (*coro_)(); } //private: shared_ptr<typename basic_yield_context<Handler>::callee_type> coro_; typename basic_yield_context<Handler>::caller_type& ca_; Handler& handler_; + atomic_count* ready_; asio::error_code* ec_; }; @@ -171,8 +180,10 @@ explicit async_result(detail::coro_handler<Handler, T>& h) : handler_(h), - ca_(h.ca_) + ca_(h.ca_), + ready_(2) { + h.ready_ = &ready_; out_ec_ = h.ec_; if (!out_ec_) h.ec_ = &ec_; h.value_ = &value_; @@ -181,7 +192,8 @@ type get() { handler_.coro_.reset(); // Must not hold shared_ptr to coro while suspended. - ca_(); + if (--ready_ != 0) + ca_(); if (!out_ec_ && ec_) throw asio::system_error(ec_); return ASIO_MOVE_CAST(type)(value_); } @@ -189,6 +201,7 @@ private: detail::coro_handler<Handler, T>& handler_; typename basic_yield_context<Handler>::caller_type& ca_; + detail::atomic_count ready_; asio::error_code* out_ec_; asio::error_code ec_; type value_; @@ -202,8 +215,10 @@ explicit async_result(detail::coro_handler<Handler, void>& h) : handler_(h), - ca_(h.ca_) + ca_(h.ca_), + ready_(2) { + h.ready_ = &ready_; out_ec_ = h.ec_; if (!out_ec_) h.ec_ = &ec_; } @@ -211,13 +226,15 @@ void get() { handler_.coro_.reset(); // Must not hold shared_ptr to coro while suspended. - ca_(); + if (--ready_ != 0) + ca_(); if (!out_ec_ && ec_) throw asio::system_error(ec_); } private: detail::coro_handler<Handler, void>& handler_; typename basic_yield_context<Handler>::caller_type& ca_; + detail::atomic_count ready_; asio::error_code* out_ec_; asio::error_code ec_; };