completion_handler类型为
auto init = [](auto completion_handler, bool should_complete) {
boost::asio::detail::awaitable_handler<boost::asio::any_io_executor> ch = std::move(completion_handler);
if (should_complete) {
std::move(ch)();
} else {
// What is happend if completion_handler is neither invoked nor stored ?
}
};
awaitable_handler
间接继承自
awaitable_thread
,在销毁时确实负责堆栈的展开:
// Clean up with a last ditch effort to ensure the thread is unwound within
// the context of the executor.
~awaitable_thread()
{
if (bottom_of_stack_.valid())
{
// Coroutine "stack unwinding" must be performed through the executor.
auto* bottom_frame = bottom_of_stack_.frame_;
(post)(bottom_frame->u_.executor_,
[a = std::move(bottom_of_stack_)]() mutable
{
(void)awaitable<awaitable_thread_entry_point, Executor>(
std::move(a));
});
}
}
通常情况下,所有权会从一个处理程序转移到另一个处理者,但在这里,没有任何内容再引用它,因此它不再存在。
尽管这是实现的细节,但如果coro永远无法恢复,则引用计数将变为零。此外,在这一过程中,您可能会发现一些不错的代码注释很有见地,例如。
impl/awaitable.hpp
一开始是
// An awaitable_thread represents a thread-of-execution that is composed of one
// or more "stack frames", with each frame represented by an awaitable_frame.
// All execution occurs in the context of the awaitable_thread's executor. An
// awaitable_thread continues to "pump" the stack frames by repeatedly resuming
// the top stack frame until the stack is empty, or until ownership of the
// stack is transferred to another awaitable_thread object.
//
// +------------------------------------+
// | top_of_stack_ |
// | V
// +--------------+---+ +-----------------+
// | | | |
// | awaitable_thread |<---------------------------+ awaitable_frame |
// | | attached_thread_ | |
// +--------------+---+ (Set only when +---+-------------+
// | frames are being |
// | actively pumped | caller_
// | by a thread, and |
// | then only for V
// | the top frame.) +-----------------+
// | | |
// | | awaitable_frame |
// | | |
// | +---+-------------+
// | |
// | | caller_
// | :
// | :
// | |
// | V
// | +-----------------+
// | bottom_of_stack_ | |
// +------------------------------->| awaitable_frame |
// | |
// +-----------------+
文档?
我找到了Tanner Sansbury解释堆叠式协程的等效语义的旧答案[我的重点]:
协程被挂起,直到操作完成并调用完成处理程序、io_service被销毁,
或Boost。Asio检测到合作已经暂停,无法恢复
,此时Boost。阿西奥会破坏协同游戏。
从…起
What does boost::asio::spawn do?