QTcpServer 中的内存泄漏,在不同线程中参与连接
Memory leak in QTcpServer attending connections in different thread
我正在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()));
相关文章:
- 提升 ASIO - io_service 不要等待连接到线程
- 如何在多个线程中创建 QSql数据库连接时防止名称冲突
- 如果两个线程相互依赖,则 cpp 线程连接应使用连接导致死锁
- 视频在唤醒其他线程时输入设备断开连接
- 正在连接的等待条件变量的线程会发生什么情况?
- 如何强制线程轮流连接到字符串?
- 将信号从工作线程类连接到控制器类 - QThreads
- 多个网络连接的线程与异步 I/O
- 什么时候标准::线程::连接会因no_such_process而失败
- C++线程的向量在连接时随机崩溃
- C++线程连接会立即返回或不返回
- 如何将信号从线程连接到插槽
- 线程连接在另一个线程运行时会导致分段错误
- 线程连接问题
- Qt中的C++线程连接
- 线程连接函数阻塞调用线程
- Qt:多线程连接不工作
- 线程连接是如何工作的
- 在已完成的std::线程连接上发生死锁
- 线程连接c++行为