我正在尝试在qt中使用线程但我在使用的代码中遇到了一些奇怪的错误。
我正在使用线程的函数。
QThreadPool::globalInstance()->setMaxThreadCount(size);
QFutureSynchronizer<void> synchronizer;
for(quint64 i=0;i<size;i++)
{
synchronizer.addFuture(QtConcurrent::run(this, &Market::tickerForThread,markets[permission[i]],QString("%1%2/value").arg(url).arg(permission[i])));
}
synchronizer.waitForFinished();
和fucntions
void Market::tickerForThread(QVariantMap &vMap,QString url)
{
vMap=QJsonDocument::fromJson(getnetwork->getAction(url)).object().value("value").toObject().toVariantMap();
}
QByteArray GetNetwork::getAction(QString url)
{
QEventLoop loop;
QNetworkReply *reply=getNAM->get(QNetworkRequest(QUrl(url)));
connect(reply,SIGNAL(finished()),&loop,SLOT(quit()));
loop.exec();
if(reply->error()!=QNetworkReply::NoError)
{
QString error=QString("Network Error file:%1 line:%2 error:%3")
.arg(__FILE__)
.arg(__LINE__)
.arg(reply->errorString());
emit errorOccured(error);
return error.toLatin1();
}
return reply->readAll();
}
和我得到的错误
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNetworkAccessManager(0xa64d80), parent's thread is QThread(0x6f9270), current thread is QThread(0xad4490)
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNetworkAccessManager(0xa64d80), parent's thread is QThread(0x6f9270), current thread is QThread(0xacc3c0)
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNetworkAccessManager(0xa64d80), parent's thread is QThread(0x6f9270), current thread is QThread(0xacbd90)
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QNetworkAccessManager(0xa64d80), parent's thread is QThread(0x6f9270), current thread is QThread(0xad4b20)
错误的原因是什么?如何解决? 谢谢你的回复。
答案 0 :(得分:4)
错误的原因是什么?如何解决?
父母和孩子必须生活在同一个主题中。解决方案是将它们分别移动到同一个线程中。
您需要将QNAM实例移动到子线程,否则需要移动子项。如果没有明确的背景,我无法告诉你更具体的建议。