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

[SOLVED] QThread - Stopping a workerThread gracefully



  • Hey guys,

    I would like to be able to stop/resume a QThread from the Gui Thread. The QThread is just a busy loop that process data and send back some data with signal to the main Gui Thread:

    @ while(1 && !bStopProcessNow) {
    qDebug() << "CompuTrainer Tread running... processing data";
    ///emit signals connected to Main Gui.
    QThread::msleep(1500);
    }@

    Now I made a signal to stop this QThread from inside my Gui.

    @connect(this, SIGNAL(signal_stopProcessNow()), computrainer, SLOT(stopProcessNow()) );
    // used to stop main execution of thread
    void stopProcessNow() {
    qDebug() << "STOPPED PROCESS CT NOW";
    bStopProcessNow = true;
    }
    @

    The problem is when the QThread is in the busy loop, the slot to change the stop flag never get triggered, so the QThread never stop. If the QThread is not in the busy loop, all works fine.
    Any idea on best practice to stop my QThread? The QThread coding is made with "this style":http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/ (custom QObject moved to a plain QThread, I communicate with QThread only with signals/slots).

    Thanks!


  • Lifetime Qt Champion

    Hi,

    Who's emitting that signal ?



  • Hey Sgaist,

    The Main thread is emiting the signal to stop the QThread.
    But the way the QThread is designed (busy loop) the QThread ignore the signals because it is busy.

    Maybe the QThread should be redesigned, it is code that was made long ago I suspect (orignal code was subclassing QThread and using .run(), I modified it to use the new approach of subclass QObject and moving the object to a QThread instead)
    Source :
    "https://github.com/GoldenCheetah/GoldenCheetah/blob/master/src/Computrainer.h":https://github.com/GoldenCheetah/GoldenCheetah/blob/master/src/Computrainer.h

    Edit:
    Not sure the busy loop can changed, the QThread just scan data at specific interval on a Com port, if the data has changed, the QThread emit a signals.
    This is good to receive data from the QThread, but i'm having problem controlling the QThread from outside since it's always busy.


  • Lifetime Qt Champion

    Looks like you could use a timer rather than a busy loop for that



  • Good point, i'll modify the while loop and use a QTimer that fire each 100ms for example. Thanks!


Log in to reply