首页 > 解决方案 > 连接池析构函数阻止子对象析构函数中的网络通信

问题描述

我有一个使用带有 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。

标签: c++c++11boost-asio

解决方案


推荐阅读