thread does not work
Solved
General and Desktop
-
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
-
@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... -
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 QPlaintexteditvoid MainWindow::onNumberChanged(int Number) { ui->label->setText(QString::number(Number)); }
-