【问题标题】:asio aync_send memory leakasio aync_send 内存泄漏
【发布时间】:2018-02-25 19:35:41
【问题描述】:

我有下一个sn-p:

void TcpConnection::Send(const std::vector<uint8_t>& buffer) {
std::shared_ptr<std::vector<uint8_t>> bufferCopy = std::make_shared<std::vector<uint8_t>>(buffer);

auto socket = m_socket;

m_socket->async_send(asio::buffer(bufferCopy->data(), bufferCopy->size()), [socket, bufferCopy](const boost::system::error_code& err, size_t bytesSent)
{
    if (err)
    {
        logwarning << "clientcomms_t::sendNext encountered error: " << err.message();

        // Assume that the communications path is no longer
        // valid.
        socket->close();
        }
    });
}

此代码会导致内存泄漏。如果注释了 m_socket->async_send 调用,则没有内存泄漏。我不明白为什么在调度回调后没有释放 bufferCopy。我做错了什么? 使用 Windows。

【问题讨论】:

  • 您能提供更多信息吗?您使用的是哪个分析工具?确切的信息是什么?
  • 我使用 VS 分析工具。上面的函数调用非常频繁,所以为了安全起见复制了缓冲区。应用程序内存使用量不断增长。
  • 触发async_send 而没有在处理程序中做一些有用的事情是一种气味。 IIRC 有多个 async_send 同时触发是未定义的,这可能是你的情况。

标签: c++ boost memory-leaks asio


【解决方案1】:

由于您没有显示任何相关代码,并且显示的代码不包含严格的问题,因此我将根据代码气味进行假设。

气味是你有一个不是enable_shared_from_this&lt;TcpConnection&gt; 派生的TcpConnection 类。这让我怀疑你没有提前计划,因为在完成任何异步操作(如async_send)后,没有可能合理的方式可以继续使用实例。

这让我怀疑你有一个非常简单的问题,那就是你的完成处理程序永远不会运行。只有一种情况可以解释这一点,这让我假设你永远不会 run() ios_service 实例

这是现场的情况:

Live On Coliru

#include <boost/asio.hpp>
namespace asio = boost::asio;
using asio::ip::tcp;

#include <iostream>
auto& logwarning = std::clog;

struct TcpConnection {
    using Buffer = std::vector<uint8_t>;
    void Send(Buffer const &);

    TcpConnection(asio::io_service& svc) : m_socket(std::make_shared<tcp::socket>(svc)) {}
    tcp::socket& socket() const { return *m_socket; }
  private:
    std::shared_ptr<tcp::socket> m_socket;
};

void TcpConnection::Send(Buffer const &buffer) {
    auto bufferCopy = std::make_shared<Buffer>(buffer);
    auto socket     = m_socket;

    m_socket->async_send(asio::buffer(bufferCopy->data(), bufferCopy->size()),
         [socket, bufferCopy](const boost::system::error_code &err, size_t /*bytesSent*/) {
             if (err) {
                 logwarning << "clientcomms_t::sendNext encountered error: " << err.message();

                 // Assume that the communications path is no longer
                 // valid.
                 socket->close();
             }

         });
}

int main() {
    asio::io_service svc;
    tcp::acceptor a(svc, tcp::v4());
    a.bind({{}, 6767});
    a.listen();

    boost::system::error_code ec;
    do {
        TcpConnection conn(svc);
        a.accept(conn.socket(), ec);

        char const* greeting = "whale hello there!\n";
        conn.Send({greeting, greeting+strlen(greeting)});
    } while (!ec);
}

您会看到任何客户端,例如连接netcat localhost 6767 将收到问候语,之后,令人惊讶地连接将保持打开状态,而不是关闭。

无论哪种方式,您都希望服务器端关闭连接,因为

  • async_send 出现传输错误
  • 或,因为在完成处理程序运行后,它被销毁,因此捕获的共享指针被销毁。这不仅会释放复制的缓冲区,而且也会运行socket 的析构函数,从而关闭连接。

这清楚地证实了完成处理程序永远不会运行。修复很“简单”,找个地方运行服务:

int main() {
    asio::io_service svc;
    tcp::acceptor a(svc, tcp::v4());
    a.set_option(tcp::acceptor::reuse_address());
    a.bind({{}, 6767});
    a.listen();

    std::thread th;

    {
        asio::io_service::work keep(svc); // prevent service running out of work early
        th = std::thread([&svc] { svc.run(); });

        boost::system::error_code ec;
        for (int i = 0; i < 11 && !ec; ++i) {
            TcpConnection conn(svc);
            a.accept(conn.socket(), ec);

            char const* greeting = "whale hello there!\n";
            conn.Send({greeting, greeting+strlen(greeting)});
        }
    }

    th.join();
}

这会运行 11 个连接并无泄漏地退出。

更好:

当接受循环也是异步的时,它会变得更加简洁,并且TcpConnection 被正确共享,如上所示:

Live On Coliru

#include <boost/asio.hpp>
namespace asio = boost::asio;
using asio::ip::tcp;

#include <memory>
#include <thread>
#include <iostream>
auto& logwarning = std::clog;

struct TcpConnection : std::enable_shared_from_this<TcpConnection> {
    using Buffer = std::vector<uint8_t>;

    TcpConnection(asio::io_service& svc) : m_socket(svc) {}

    void start() {
        char const* greeting = "whale hello there!\n";
        Send({greeting, greeting+strlen(greeting)});
    }

    void Send(Buffer);

  private:
    friend struct Server;
    Buffer m_output;
    tcp::socket m_socket;
};

struct Server {
    Server(unsigned short port) {
        _acceptor.set_option(tcp::acceptor::reuse_address());
        _acceptor.bind({{}, port});
        _acceptor.listen();

        do_accept();
    }

    ~Server() {
        keep.reset();
        _svc.post([this] { _acceptor.cancel(); });
        if (th.joinable())
            th.join();
    }

  private:
    void do_accept() {
        auto conn = std::make_shared<TcpConnection>(_svc);
        _acceptor.async_accept(conn->m_socket, [this,conn](boost::system::error_code ec) {
            if (ec)
                logwarning << "accept failed: " << ec.message() << "\n";
            else {
                conn->start();
                do_accept();
            }
        });
    }

    asio::io_service _svc;
    // prevent service running out of work early:
    std::unique_ptr<asio::io_service::work> keep{std::make_unique<asio::io_service::work>(_svc)};
    std::thread th{[this]{_svc.run();}}; // TODO handle handler exceptions

    tcp::acceptor _acceptor{_svc, tcp::v4()};
};

void TcpConnection::Send(Buffer buffer) {
    m_output  = std::move(buffer);
    auto self = shared_from_this();

    m_socket.async_send(asio::buffer(m_output),
         [self](const boost::system::error_code &err, size_t /*bytesSent*/) {
             if (err) {
                 logwarning << "clientcomms_t::sendNext encountered error: " << err.message() << "\n";
                 // not holding on to `self` means the socket gets closed
             }

             // do more with `self` which points to the TcpConnection instance...
         });
}

int main() {
    Server server(6868);
    std::this_thread::sleep_for(std::chrono::seconds(3));
}

【讨论】:

  • 感谢您的回答。我的代码有run()。一个连接也经常用于数据发送。可以根据用户要求关闭连接。所以连接不能包含缓冲区作为成员,因为缓冲区可以在异步发送之前被覆盖。
  • 我发现了问题。我在接收器应用程序的控制台中打印了很多信息。因此,接收方工作非常缓慢,发送方无法发送更多数据(调度 async_send)。
  • 你的回答很好,可以帮助别人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 2013-03-18
相关资源
最近更新 更多