【发布时间】:2014-03-02 23:46:48
【问题描述】:
在对我的 QT 应用程序进行大量测试和更改后,Visual Leak Detector 确定了令人讨厌的泄漏源(8 个字节)。 VLD 报告 QT 应用程序是干净的,除了 QThread* 指针。
一些实现背景:该应用程序由 Jeffrey Holmes Bulk download of web pages using Qt 建模为混合解决方案。感谢 Jeffrey 提供的早期解决方案!
问题:
为什么
QThread*在工作线程完成其工作时没有自行销毁?如何在工作完成后强制
QThread*删除线程和工作对象?是否应该以不同的方式实现
QThread?
代码:
void vqMDIChildDialog::processWorkQueue(bool bIsBC)
{
if (m_listOfTables.isEmpty() && currentReplicationThreads == 0)
{
}
else if (!m_listOfTables.isEmpty())
{
for (int i = 0; i < maxReplicationThreads && !m_listOfTables.isEmpty();i++)
{
QThread *thread = new QThread;
QPointer<vcSharedDataQt> worker = new vcSharedDataQt();
worker->moveToThread(thread);
QString tmpTableName (m_listOfTables.dequeue());
worker->setParentObject(this);
//
// set properties on the worker object.
//
connect(thread, SIGNAL(started()), worker, SLOT(process()));
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread,SLOT(deleteLater()));
connect(worker,
SIGNAL(updateMessageFromThread( const QString&,
const QString&,
const QString&,
const QString&,
const QString&,
const QString&,
const QString&)),
this,
SLOT(UpdateStatusBarFromThread( const QString&,
const QString&,
const QString&,
const QString&,
const QString&,
const QString&,
const QString&)));
thread->setObjectName(worker->getUniqueKey());
thread->start();
currentReplicationThreads ++;
}
}
}
Stack 不允许我回答这个问题,所以:
函数被QMutex保护:
mutex.lock();
processWorkQueue();
mutex.unlock();
这导致了内存泄漏。 QThread 显然无法在工作线程完成时被销毁。我删除了互斥锁,VLD 报告QThread 没有内存泄漏。
【问题讨论】:
-
您对
QPointer的使用毫无意义:) -
您使用的是哪个版本的 Qt? (QThread deleteLater() 行为在 4.8 左右发生了变化。)
-
感谢更新和 cmets:打开 - QT 5.2.0
标签: multithreading qt memory memory-leaks qthread