Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How quit QApplication with QThread



  • If is line with singleShot comment, program exit correctly (Worker destructor is called). What is correct way, how quit application if is called QCoreApplication::quit(). I need call Worker destructor.

    #include <QCoreApplication>
    
    #include <QThread>
    #include <QDebug>
    #include <QTimer>
    #include <QAbstractEventDispatcher>
    
    #include "Worker.h"
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        QThread* workerThread = new QThread();
        Worker* worker = new Worker();
    
        QObject::connect(workerThread, SIGNAL(started()), worker, SLOT(work()));
        QObject::connect(workerThread, SIGNAL(finished()), worker, SLOT(deleteLater()));
        QObject::connect(workerThread, SIGNAL(destroyed(QObject*)), worker, SLOT(deleteLater()));
        QObject::connect(worker, SIGNAL(finished()), workerThread, SLOT(quit()));
        QObject::connect(worker, SIGNAL(finished()), qApp, SLOT(quit()));
        worker->moveToThread(workerThread);
        workerThread->start();
    
        QTimer::singleShot(2000, qApp, [=](){QCoreApplication::quit();});
    
        int ret = a.exec();
    
        while (qApp->eventDispatcher()->processEvents(QEventLoop::AllEvents))
        {
    
        }
    
        qDebug() << "end with" << ret;
        return ret;
    }
    
    #ifndef WORKER_H
    #define WORKER_H
    
    #include <QObject>
    
    class Worker : public QObject
    {
        Q_OBJECT
    public:
        Worker(QObject* parent = 0);
        ~Worker();
    
    public slots:
        void work();
    
    signals:
        void finished();
    };
    
    #endif // WORKER_H
    
    #include "Worker.h"
    #include <QDebug>
    
    Worker::Worker(QObject* parent)
        : QObject(parent)
    {
    
    }
    
    Worker::~Worker()
    {
        qDebug() << "~Worker()";
    }
    
    void Worker::work()
    {
        static int i = 0;
    
        while (1)
        {
            qDebug() << i++;
            if (i == 2e4)
            {
                break;
            }
        }
        emit finished();
    }
    

  • Lifetime Qt Champion

    Hi,

    You have to wait on your thread to be finished in that case.

    QThread has such a method.



  • Problem solved. Thank you.

        int ret = a.exec();
    
        workerThread->quit();
        workerThread->wait();
    

  • Lifetime Qt Champion

    Great !

    Then please mark the thread as solved using the "Topic Tools" button so that other forum users may know a solution has been found :)

    Note that you may have to first select the "Ask as question" option and then you can mark the thread as solved.


Log in to reply