【发布时间】:2012-03-01 08:29:51
【问题描述】:
我对此有一些疑问:
首先我创建我的对象并将它移动到一个线程:
FileUploader *fileUploader = new FileUploader(fileList_, start, (offset == 0 ? (fileList_.count() - start) : offset));
QThread *fileUploaderThread = new QThread;
fileUploader->moveToThread(fileUploaderThread);
fileUploaderThreads_.append(fileUploaderThread);
fileUploaders_.append(fileUploader); // contains pointers to the objects
connect(fileUploader, SIGNAL(progressChangedAt(int)), model_, SLOT(reportProgressChanged(int)), Qt::QueuedConnection);
connect(fileUploader, SIGNAL(statusChangedAt(int)), model_, SLOT(reportStatusChanged(int)), Qt::QueuedConnection);
connect(fileUploader, SIGNAL(finished()), fileUploaderThread, SLOT(quit()), Qt::QueuedConnection);
connect(fileUploaderThread, SIGNAL(finished()), this, SLOT(checkIfFinished()), Qt::QueuedConnection);
插槽中的 checkIfFinished() 我想检查所有线程,看看它们是否退出。 qDebug()
foreach(QThread *thread, fileUploaderThreads_) { // or FileUploader* fileuploader, fileUploaders_ ?
if(thread && !thread->isFinished()) {
qDebug() << "not finished " << thread->currentThreadId();
return; // not done
}
}
当它被打印出来时,我只得到主线程 ID,而不是线程。我试图打印线程ID,但没有运气(在它们启动后)。 我这样做的原因是因为编写“高级 Qt 编程 - Mark S”的人对 QThreads 做了类似的事情,他将其放在列表中并检查它们是否完成。现在唯一起作用的是在 fileUploader 完成时终止线程的连接。
另外,我如何存储线程的指针?如果它们似乎没有指向正确的线程,我将如何将它们全部删除。
编辑:
我尝试将 QObjects 存储在一个列表中,然后这样做:
QThread *senderx = qobject_cast<QThread*>(sender());
qDebug() << "one thread done" << senderx;
foreach(FileUploader *fileUploader, fileUploaders_) {
if(fileUploader && !fileUploader->thread()->isFinished()) {
qDebug() << "not finished " << fileUploader->thread();
return; // not done
}
}
//done
qDebug() << "done";
setButtonState(false);
我最后一次通话的结果是:
一个线程完成 QThread(0x43ee180)
未完成 QThread(0x43ee180)
这怎么可能?它完成了,但方法却另有说明。
【问题讨论】:
标签: c++ multithreading qt