QTcpServer 中的内存泄漏,在不同线程中参与连接

Memory leak in QTcpServer attending connections in different thread

本文关键字:线程 连接 内存 泄漏 QTcpServer      更新时间:2023-10-16

我正在Windows 7上的Qt 4.7中开发RPC服务器。为了同时参加多个执行,每个请求都在单独的线程中运行(因为函数可能会阻塞)。我继承了QTcpServer并重新实现了传入连接函数,它看起来像这样:

void RpcServer::incomingConnection(int socketDescriptor){
    QThread *thread = new QThread();
    RpcServerConnection *client = new RpcServerConnection(socketDescriptor);
    client->moveToThread(thread);    
    connect(thread, SIGNAL(started()), client, SLOT(init()));
    connect(client, SIGNAL(finish()), thread, SLOT(quit()));
    connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
    thread->start();
}

RpcServer连接管理的数据交换。初始化方法如下所示:

 void RpcServerConnection::init(){
        qDebug() << "ServerSocket(" << QThread::currentThreadId() << "): Init";
        clientConnection = new QTcpSocket();
        clientConnection->setSocketDescriptor(socketDescriptor);
        connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readFromSocket()));
        connect(clientConnection, SIGNAL(disconnected()), this, SLOT(deleteLater()));
        connect(this, SIGNAL(finish()), this, SLOT(deleteLater()));
    }

一旦收到所有数据并发送响应,就会发出完成信号。调试我可以看到所有线程和套接字都被删除了。但是,进程内存会随着每个新连接而增加,并且在结束时不会释放它......

从 QTcpServer 继承时,我必须释放其他任何内容吗?

问题可能出在种族/未定义的调用顺序上。 RpcServerConnection::finish()既连接到其deleteLater()插槽,也连接到线程的quit()插槽。如果首先进入线程的quit槽,则线程将立即从事件循环终止,然后才能对延迟删除执行任何操作。

而不是:

connect(client, SIGNAL(finish()), thread, SLOT(quit()));

尝试:

connect(client, SIGNAL(destroyed()), thread, SLOT(quit()));