在我的网络库中,如果我手动run()
和restart()
io_context
,我可以对网络进行异步写入。
我现在正试图通过添加线程池来扩展规模:
.HPP
struct pool : public std::enable_shared_from_this<pool> {
pool(const pool &) = delete;
auto operator=(const pool &) -> pool & = delete;
explicit pool(pool_parameters config, db_parameters params) noexcept;
asio::io_context m_io_context;
asio::thread_pool m_workers;
asio::executor_work_guard<asio::io_context::executor_type> m_work_guard;
/// \brief Container to hold connections.
std::vector<std::unique_ptr<dbc::connection>> m_connections;
};
CPP
pool::pool(pool_parameters config, db_parameters params) noexcept
: m_config{std::move(config)},
m_params{std::move(params)},
m_work_guard{asio::make_work_guard(m_io_context)},
m_workers{m_config.thread_pool_size} {
m_connections.reserve(m_config.connection_pool_size);
asio::post(m_workers, [&]() { m_io_context.run(); });
}
哪个管理连接:
.HPP
struct abstract_connection : connection {
explicit abstract_connection(const std::shared_ptr<pool> &pool) noexcept;
~abstract_connection() override;
packet m_buffer;
asio::local::stream_protocol::endpoint m_endpoint;
asio::generic::stream_protocol::socket m_socket;
asio::io_context::strand m_strand;
};
CPP
abstract_connection::abstract_connection(const std::shared_ptr<pool> &pool) noexcept
: m_params{pool->m_params},
m_config{pool->m_config},
m_endpoint{pool->m_config.socket},
m_socket{pool->m_io_context},
m_strand{pool->m_io_context} {
m_socket.connect(m_endpoint);
m_socket.non_blocking(true);
}
abstract_connection::~abstract_connection() {
std::error_code ec;
m_socket.shutdown(asio::generic::stream_protocol::socket::shutdown_both, ec);
m_socket.close();
}
现在是令人困惑的公园。在具体连接对象的ctor上,我需要进行握手,同时在同一个类的析构函数上进行握手。这不会发生,因为套接字对象似乎表现得很奇怪:
如果我异步发送数据,没有任何内容写入套接字,有时我得到一个损坏的管道错误:
asio::dispatch(m_strand, [&]() {
m_buffer = write::startup(m_params);
asio::async_write(m_socket, asio::buffer(m_buffer), [](std::error_code ec, std::size_t len) {});
});
如果我进行同步写入,我会在从套接字读取之前出现管道损坏错误:
std::error_code ec;
auto startup = write::startup(m_params);
asio::write(m_socket, asio::buffer(startup), ec);
if (set_error(ec)) {
std::cerr << " XXX " << ec.message() << std::endl;
return;
}
m_buffer.reserve(327);
asio::read(m_socket, asio::buffer(m_buffer), ec);
std::cerr << ec.message() << std::endl;
std::cerr << m_buffer.size() << std::endl;
连接是通过unix socket完成的,我在两者之间都有socat,所以我可以看到数据的来来往往,以及破坏的管道消息。尝试使用第三方工具连接到远程工作,所有相关数据都出现在socat中,所以我认为问题出在我的代码中。
如何调试套接字的运行情况?
根据您发布的代码,您的boost::asio::thread_pool
似乎只是提前超出范围。你的abstract_connection
类只需要一个const std::shared_ptr<pool> &pool
,这意味着你的抽象连接实例没有在你的线程池中保存引用计数。对std::shared_ptr
的引用一般没有意义,因为这样,让你的abstract_connection
只在它的构造函数中使用std::shared_ptr<const pool> pool
,你应该复制或移动一个相同类型的成员。
我通过使套接字阻塞(non_blocking(false)
)解决了这个问题,如果没有Superlokkus的回答我就不会想到这个问题。