Search code examples
c++multithreadingqtqthread

What is the way to stop the thread (when I directly inherit from QThread)?


.h

#include <QThread>
#include <QDebug>

class MainWindow : public QThread
{
    Q_OBJECT

protected:
    void run()
    {
        while (1)
        {
            qDebug() << "\nsdfdsf";
        }
    }

public:
    MainWindow(QThread *parent = 0);
    ~MainWindow();
};

.cpp

#include "mainwindow.h"

MainWindow::MainWindow(QThread *parent)
    : QThread(parent)
{
    start();
}

MainWindow::~MainWindow()
{

}

Now, this is an old way of working with threads, I know. I want to know what is the way to stop the thread when working with method?

Please show the example.


Solution

  • In Qt5, there is interrupt request (QThread::requestInterruption) that can be handled by the thread, so there is an elegant and unified way to let the threads stop.

    See also this answer.