0

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

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();
}

RpcServerConnection 托管数据交换。init 方法如下所示:

 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 继承时,我是否必须释放其他任何东西?

4

1 回答 1

1

问题可能与比赛/未定义的调用顺序有关。RpcServerConnection::finish()既连接到它的deleteLater()槽,又连接到线程的quit()槽。如果quit首先进入线程的槽,则线程将立即从事件循环中终止,然后才能对延迟删除进行任何操作。

代替:

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

尝试:

connect(client, SIGNAL(destroyed()), thread, SLOT(quit()));
于 2013-09-06T17:16:38.323 回答