Boost.Asio spawn 的用法
官方文档例子
void go()
{
auto self(shared_from_this());
boost::asio::spawn(strand_,
[this, self](boost::asio::yield_context yield)
{
try
{
char data[128];
for (;;)
{
timer_.expires_from_now(std::chrono::seconds(10));
std::size_t n = socket_.async_read_some(boost::asio::buffer(data), yield);
boost::asio::async_write(socket_, boost::asio::buffer(data, n), yield);
}
}
catch (std::exception& e)
{
socket_.close();
timer_.cancel();
}
});
}
改进:将read和write分别包装成spawn,互相调用
void Connection::startRead(boost::asio::yield_context yield) {
boost::asio::spawn(strand_, [this](boost::asio::yield_context yield) {
startWrite(yield);
});
}
void Connection::startWrite(boost::asio::yield_context yield) {
boost::asio::spawn(strand_, [this](boost::asio::yield_context yield) {
startRead(yield);
});
}