我尝试使用Boost::ASIO中的通道实现协同程序取消,但是我遇到了分段错误,我无法找出原因。我尝试使用调试器,但它没有告诉我太多,只是说分段错误发生在“io_ctx-〉run()"之后。
下面是我的代码:
boost::asio::awaitable<void> to_be_cancelled(
boost::asio::experimental::concurrent_channel<void(boost::system::error_code, std::string)>& end,
shared_ptr<boost::asio::io_context> io_ctx)
{
boost::asio::ip::tcp::socket sock(*io_ctx);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::tcp::v4(), 8000);
boost::asio::ip::tcp::acceptor acceptor(*io_ctx, endpoint);
co_await
(
end.async_receive(boost::asio::use_awaitable_t()) ||
acceptor.async_accept(sock, boost::asio::use_awaitable_t())
);
cout << "done\n";
}
boost::asio::awaitable<void> send_one_message(
boost::asio::experimental::concurrent_channel<void(boost::system::error_code, std::string)>& channel)
{
channel.async_send(boost::system::error_code{}, string("hello"), boost::asio::use_awaitable_t());
}
boost::asio::awaitable<void> coroutine_manager(shared_ptr<boost::asio::io_service> io_ctx)
{
auto ch = make_shared<boost::asio::experimental::concurrent_channel<void(boost::system::error_code, std::string)>>(*io_ctx, 5);
co_await (to_be_cancelled(*ch, io_ctx) && send_one_message(*ch));
}
int main()
{
auto io_ctx = std::make_shared<boost::asio::io_service>(2);
co_spawn(*io_ctx, coroutine_manager(io_ctx), boost::asio::detached);
io_ctx->run();
}
任何帮助都将不胜感激。
1条答案
按热度按时间ni65a41a1#
我在“send_one_message”函数中缺少一个“co_await”,我猜这意味着字符串将超出作用域,导致接收通道试图访问释放的内存。