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

How to end a QThread correct in main.cpp?



  • Hello,
    I have a problem with ending a QThread.

    In my main.cpp I connect the "aboutToQuit" signal to call the destructor of the used class. Its destructor emits a "finished" signal which then tells the corresponding thread to quit.
    Now I need to wait until the thread quits before the application quits.
    Here is my problem. I have no clue how to do that.

    How can I properly end my thread and my application?

    Thanks

    Used MyClass slot:

    public slots:
        void quit(){delete this;} //Calls destructor which emits “finished” signal
    

    Main.cpp:

    #include <QApplication>
    #include <QQmlApplicationEngine>
    #include <QThread>
    #include "myclass.h"
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
        MyClass* myClass = new MyClass();
    
        QThread myClassThread;
        QObject::connect(&app, &QApplication::aboutToQuit, myClass, &MyClass::quit);
        QObject::connect(myClass, &MyClass::finished,  &myClassThread, &QThread::quit);
        myClass->moveToThread(&myClassThread);
        myClassThread.start();
    
        QQmlApplicationEngine engine;
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                         &app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
        engine.load(url);
    
        return app.exec();
    }
    

  • Lifetime Qt Champion



  • @jsulm said in How to end a QThread correct in main.cpp?:

    @robro Call https://doc.qt.io/qt-5/qthread.html#quit and then https://doc.qt.io/qt-5/qthread.html#wait

    Thanks, but how?
    Calling wait after "return app.exec();" would not work and I have no clue to call wait using the signal slot mechanism.


  • Moderators

    @robro said in How to end a QThread correct in main.cpp?:

    Calling wait after "return app.exec();" would not work

    Return after waiting:

    int exitCode = app.exec();
    myClassThread.wait();
    return exitCode;
    
    void quit(){delete this;} //Calls destructor which emits “finished” signal
    

    Beware: In general, deleting a QObject in a slot is dangerous. It could cause your program to crash if other signals arrive.

    You don't need MyClass::quit() -- just connect QApplication::aboutToQuit() to MyClass::deleteLater().


Log in to reply