简体   繁体   中英

Qt infinite loop in another thread

I am trying to setup an infinite loop in another thread. The purpose is to download some data from an URL, send the data to the main thread and sleep for some seconds:

DataFetcher::DataFetcher(QUrl url, int fetchRateSec) :
    url {url},
    fetchRateSec {fetchRateSec}
{

}

void DataFetcher::run()
{
    QNetworkAccessManager* manager = new QNetworkAccessManager();
    QObject::connect(manager, &QNetworkAccessManager::finished, this, &DataFetcher::onReply);

    while (true) {
        QNetworkRequest req;
        req.setUrl(url);
        manager->get(req);
        qDebug() << "run";
        sleep(fetchRateSec);
    }
}


void DataFetcher::onReply(QNetworkReply* reply)
{
    qDebug() << "repl";
    emit fetched(reply->readAll());
}

class DataFetcher : public QThread
{
    Q_OBJECT
public:
    DataFetcher(QUrl, int);
    void run() override;
signals:
    void fetched(QString);
private:
    const QUrl url;
    const int fetchRateSec;   
private slots:
    void onReply(QNetworkReply*);
};

But onReply is never called.

It is interesting because the qDebug in the while loop is executed as it should.

Im a bit nooby with QT so i might have missed something regarding how to connect the slots / signals but i think i got it right following some other examples.

It looks about right from the accepted answer in How do I write a Qt HTTP GET request?

what could be the problem here?

Per the discussion in the comments, it seems like the whole business of threading is not needed.

One of Qt's strongest attributes is that it is event-driven. You generally create a program by describing what you want to happen ( slots ) in response to certain events ( signals ). Explicitly waiting or sleeping is very rare in Qt-based applications (usually only testing), and is generally considered a no-no in event-driven development.

For your specific problem, a solution might look like this. You can create a QTimer in the main thread and connect its timeout signal to a function to make your HTTP request. You can then connect a slot to the QNetworkAccessManager::finished signal , which will run when your response completes. All of this can take place in the main thread, relying on the thread's event loop to manage the callbacks. No need to manage a separate thread yourself, and no looping, sleeping, blocking, or anything like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM