1

It was my first attempt to create a thread in qt but unfortunately it isn't stopping. This is how my code look like.

// Worker class

    class Worker : public QObject
    {
        Q_OBJECT
    
    public slots:
        void doWork(const QString &parameter) {
            QString result;
            forever{
                if(QThread::currentThread()->isInterruptionRequested()){
                    printf("true");
                    return;
                }else{
                    if(!QThread::currentThread()->isInterruptionRequested()){
                        cout<<parameter.toStdString();
                    }
                }
            }
            emit resultReady(result);
        }
    
    signals:
        void resultReady(const QString &result);
    };

// Controller class

    class Controller : public QObject
    {
        Q_OBJECT
        QThread workerThread;
    public:
        Controller(QObject *parent = nullptr):QObject(parent) {
            Worker *worker = new Worker;
            worker->moveToThread(&workerThread);
            connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
            connect(this, &Controller::operate, worker, &Worker::doWork);
            workerThread.start();
        }
        ~Controller() {
            workerThread.quit();
            workerThread.wait();
        }
    public slots:
        void stop(){
            workerThread.requestInterruption();
        }
    signals:
        void operate(const QString &);
    };

The forever loop isn't stopping when stop function is called.Have I done anything wrong?

0 Answers0