Background thread and QNetworkAccessManager



  • My scenario is a background thread that processes some database entries and then sends of some data to a server. The returned data can be massive, so the processing has to happen in that thread.

    I have one QNAM in the program that is naturally created on the main thread (which also is the UI thread). It seems to be impossible to use this QNAM from within the thread. Why is that?

    @
    #pragma once

    #include <QtCore/QObject>

    class Sync : public QObject {
    Q_OBJECT
    public Q_SLOTS:
    void run();

    private Q_SLOTS:
    void onFinished();
    };
    @

    @
    #include <QtCore/QCoreApplication>
    #include "Sync.h"

    #include <QtCore/QThread>
    #include <QtCore/QUrl>
    #include <QtNetwork/QNetworkAccessManager>
    #include <QtNetwork/QNetworkRequest>
    #include <QtNetwork/QNetworkReply>

    void Sync::onFinished() {
    QObject* a = sender();
    }

    void Sync::run() {
    auto nam = qApp->property("nam").value<QNetworkAccessManager*>();
    auto reply = nam->get(QNetworkRequest(QUrl("http://google.com")));
    connect(reply, SIGNAL(finished()), this, SLOT(onFinished()));
    }

    int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    QThread* thread = new QThread();
    Sync* sync = new Sync;
    sync->moveToThread(thread);
    thread->start();
    
    QNetworkAccessManager nam;
    a.setProperty("nam", QVariant::fromValue(&nam));
    
    QMetaObject::invokeMethod(sync, "run");
    
    return a.exec&#40;&#41;;
    

    }
    @


  • Moderators

    [quote author="philk" date="1391010064"]My scenario is a background thread that processes some database entries and then sends of some data to a server. The returned data can be massive, so the processing has to happen in that thread.

    I have one QNAM in the program that is naturally created on the main thread (which also is the UI thread). It seems to be impossible to use this QNAM from within the thread. Why is that?[/quote]Yes, parallel processing is required for large data sets.

    However, QNAM is not thread-safe, so you can't simply call its functions from different threads. The same applies to lots of other classes. See http://qt-project.org/doc/qt-5/threads-reentrancy.html

    I'd follow Thiago's advice at http://lists.qt-project.org/pipermail/interest/2014-January/010946.html


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.