I am trying to use thread in qt but I get some strange error in the codes I used.

the Function I am using threads.

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

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

and the error I got

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)

what is the cause of error and how can it be solved? Thank you for your replies.

有帮助吗?

解决方案

what is the cause of error and how can it be solved?

Parents and children have to live in the same thread. The solution is to move them into the same thread respectively.

You will either need to move your QNAM instance to the children's thread, or the children will need to be moved. I could not tell you more concrete advice than this without further context clarified.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top