thread does not work



  • I do not know what the problem is?

    mythread.h

    #ifndef MYTHREAD_H
    #define MYTHREAD_H
    
    #include <QThread>
    
    class MyThread : public QThread
    {
        Q_OBJECT
    public:
        explicit MyThread(QObject *parent = 0);
        void run();
        bool Stop;
    
    signals:
        void NumberChanged(int);
    
    public slots:
    
    };
    
    #endif // MYTHREAD_H
    
    

    mythread.cpp

    #include "mythread.h"
    #include <QtCore>
    
    MyThread::MyThread(QObject *parent) : QThread(parent)
    {
    
    }
    
    void MyThread::run()
    {
        for(int i = 0; i < 10000; i++)
        {
            QMutex mutex;
            mutex.lock();
            if(this->Stop) break;
            mutex.unlock();
            emit NumberChanged(i);
        }
    }
    
    

    mainwindow.cpp

    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::Window |  Qt::WindowMinimizeButtonHint | Qt::WindowCloseButtonHint);
        ui->setupUi(this);
        mThread = new MyThread(this);
        connect(mThread,SIGNAL(NumberChanged(int)),this,SLOT(onNumberChanged(int)));
    }
    void MainWindow::onNumberChanged(int Number)
    {
        ui->txt1->insertPlainText(QString::number(Number));
    
    }
    void MainWindow::on_pushButton_clicked()
    {
        mThread->start();
    
    }
    

    output: QMutex: destroying locked mutex


  • Moderators

    @MrErfan You're using a local mutex! Put it in your class as member variable and unlock it before break. All threads executing this code must use same mutex else there is no synchronisation! It is better to use QMutexLocker.
    Actually there is no need for this mutex at all in this case...



  • Re: thread does not work

    Thank you for your reply, but unfortunately Thread does not work.
    By clicking on the Start button, the program will hang ،
    If I use the QLabel, the program works properly, but I want to use QPlaintextedit

    void MainWindow::onNumberChanged(int Number)
    {
        ui->label->setText(QString::number(Number));
    }
    


  • @MrErfan try it with void QPlainTextEdit::appendPlainText(const QString &text) your TextEdit might not have a valid curse to use insert upon



  • @MrErfan
    This does not address your problem, but would your code be a lot nicer if you used QWaitCondition?



  • @JNBarchan For that what the code does, so far as shown to us, it would be more usefull to use QtConcurrent::run



  • @J.Hilk His run seems to be waiting for something to set this->Stop over a period of time, that seems to be just what QWaitCondition is for, but I am a beginner so bow to superior knowledge. I just discovered QWaitCondition an hour ago :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.