c++ - 连接池析构函数阻止子对象析构函数中的网络通信
问题描述
我有一个使用带有 2 个线程的新 thread_pool 的连接池。我的池中也有 2 个连接。连接池是这样实现的:
.hpp
/// \brief Connection pool.
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;
~pool();
/// \brief Run loop.
asio::io_context m_io_context;
/// \brief Used to keep the io_context from running out of work.
asio::executor_work_guard<asio::io_context::executor_type> m_work_guard;
/// \brief Thread pool where tasks are asynchronously executed.
asio::thread_pool m_workers;
/// \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(); });
}
pool::~pool() {
std::cerr << "~pool" << std::endl;
m_work_guard.reset();
m_workers.join();
m_io_context.stop();
}
我还有一个连接对象,它在构造函数上进行连接握手,在析构函数上进行断开握手。
问题是,当连接被破坏时,池已经停止了工作守卫,因此没有数据包发送到远程系统。
如何在工作守卫被销毁之前强制断开握手?我可以为每个连接对象添加手动断开方法,但我想坚持使用 RAII。
解决方案
推荐阅读
- html - 我正在尝试使用图像创建超链接
- python - 从在 colab.google 上学习 python 开始 屏幕截图中显示的老化错误
- python - "banana" < "orange" 是 True 而 "banana" < "Orange" 是 False 但为什么呢?
- ruby-on-rails - 使用 Roo gem 导入 CSV 时拒绝不在关联表中的项目而不是创建新记录
- python - python中的Ode求解器
- java - Java 字符串缩短器
- php - 来自sql表的echo变量的PHP变量
- python - pygame 的导入模块适用于 Jupiter 笔记本,但不适用于 IDLE (Mac)
- java - java,通过创建 Throwable 对象来抛出未经检查的异常
- node.js - 部署到 Heroku 失败