@john-lee
2021-01-03T03:58:20.000000Z
字数 891
阅读 873
Boost.Asio
coroutine
类提供对无栈协程的支持。无栈协程使程序能够用最小的开销以同步方式实现异步逻辑,如下例所示:
struct session : boost::asio::coroutine
{
boost::shared_ptr<tcp::socket> socket_;
boost::shared_ptr<std::vector<char> > buffer_;
session(boost::shared_ptr<tcp::socket> socket)
: socket_(socket),
buffer_(new std::vector<char>(1024))
{
}
void operator()(boost::system::error_code ec = boost::system::error_code(), std::size_t n = 0)
{
if (!ec) reenter (this)
{
for (;;)
{
yield socket_->async_read_some(boost::asio::buffer(*buffer_), *this);
yield boost::asio::async_write(*socket_, boost::asio::buffer(*buffer_, n), *this);
}
}
}
};
coroutine
类与伪关键字reenter
、yield
和fork
一起使用。这些都是预处理器宏,使用类似于达夫装置(Duff's Device)的技术,通过switch
语句实现。coroutine
类的文档提供了这些伪关键字的完整描述。
coroutine,HTTP 服务器 4 的例子,有栈协程。
Copyright © 2003-2020 Christopher M. Kohlhoff
Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)