'qthread: destroyed while thread is still running' on quit

  • Last Update :
  • Techknowledgy :

Edit: to illustrate the two cases, a very crude example to show the two cases

#include <iostream>
#include <QApplication>
#include <QThread>

class Dummy
{
public:
  Dummy();
  void start();
private:
  QThread a;
};

Dummy::Dummy() :
  a()
{
}


void Dummy::start()
{
  a.start();
  QThread *b = new QThread;
  b->start();

  if( a.isRunning() ) {
    std::cout << "Thread a is running" << std::endl;
  }
  if( b->isRunning() ) {
    std::cout << "Thread b is running" << std::endl;
  }
}

int main(int argc, char** argv)
{
  QApplication app(argc,argv);
  Dummy d;
  d.start();
  return app.exec();
}

It should be done like that:

MainWindow::MainWindow(QWidget * parent):
   QMainWindow(parent) {
      ...

      samplingThread = SamplingThread(this);
      samplingThread - > setFrequency(frequency());

      run = new QPushButton("Run", this);
      stop = new QPushButton("Stop", this);
      connect(run, SIGNAL(clicked()), samplingThread, SLOT(start()));
   }

MainWindow::~MainWindow() {
   samplingThread - > waitFor(5000);
}

Suggestion : 2

@SGaist said in Randomly getting "QThread: Destroyed while thread is still running":,@Alvein said in Randomly getting "QThread: Destroyed while thread is still running":, Randomly getting "QThread: Destroyed while thread is still running" ,Using IsRunning() is dangerous as there is no guarantee that the thread remains running even a few milliseconds after the call. Use catch the finished() signal and use deletelater as others have mentioned. Also even start() doesn't guarantee immediate execution. It just adds the thread to the scheduler.

Short code:

void MainWindow::some_slot() {
    int iK;
    // ...
    do
        for(iK=0;iK<TOTAL_WORKERS;iK++)
            if(!thlWorkers.at(iK)->isRunning())
                break;
    while(iK==TOTAL_WORKERS);
    delete thlWorkers.at(iK);
    thlWorkers[iK]=QThread::create([]{/*...*/});
    thlWorkers.at(iK)->start();
}

This is the new code:

#define TOTAL_WORKERS 10
#define TOTAL_ACTIVE   4

void MainWindow::some_slot() {
    int iK;
    // ...
    for(iK=0;iK<TOTAL_WORKERS;iK++) {
        thlWorkers[iK]=QThread::create([]{/*...*/});
        connect(thlWorkers[iK],SIGNAL(finished()),this,SLOT(on_finished()));
    }
    for(iK=0;iK<TOTAL_ACTIVE;iK++)
        thlWorkers.at(iK)->start();
    // ...
}

void MainWindow::on_finished() {
    int iK=getOneFreeWorkerIndex();
    thlWorkers.at(iK)->wait();
    thlWorkers.at(iK)->start();
}

Suggestion : 3

Qt Centre is a community site devoted to programming in C++ using the Qt framework. Over 90 percent of questions asked here gets answered. If you are looking for information about Qt related issue — register and post your question., If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below. ,You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community you will have access to post topics, communicate privately with other members (PM), respond to polls, upload content and access many other special features. Registration is fast, simple and absolutely free so please, join our community today! If you have any problems with the registration process or your account login, please contact us., QThread: Destroyed while thread is still running

1._
Consumer.cppvoid Consumer::run() {
      j = 0;
      while (!flag_stop) {
         usedBytes.acquire();
         write_str += buffer[j % 8096];
         j++;
         freeBytes.release();
         emit disp(); // disp a slot of mainwindow.cpp   }   flag_stop = true;}Producer.cppvoid Producer::run(){	  i=0;	  while(!flag_stop)	  {		  if(flag_read)		  {		     freeBytes.acquire();		     int n = read_str.size();		      buffer[i % 8096] = (*((read_str.toUtf8().constData())+(n-1)));		      i++;	   	      usedBytes.release();	   	      flag_read = false;		 } 	   }	  flag_stop = true;} Mainwindow.cpp...connect(textEdit_1,SIGNAL(textChanged()),this,SLOT(read_send()));	connect(pushButton_14,SIGNAL(clicked()),this,SLOT(Start_Thread()));	connect(pushButton_15,SIGNAL(clicked()),this,SLOT(Stop_Thread()));	consumer = new Consumer();	producer = new Producer();    connect(consumer,SIGNAL(disp()),this,SLOT(receive_write()));...void MainWindowImpl::Start_Thread(){    producer->start();    consumer->start();		}void MainWindowImpl::Stop_Thread(){	flag_stop = true;}void MainWindowImpl::read_send(){	read_str = textEdit_1->toPlainText();	flag_read = true;}void MainWindowImpl::receive_write(){   textEdit_2->setText(write_str);}void MainWindowImpl::closeEvent(QCloseEvent *event){       flag_stop = true;       event->accept();}
2._
Consumer.cppvoid Consumer::run() {
      j = 0;
      while (!flag_stop) {
         usedBytes.acquire();
         write_str += buffer[j % 8096];
         j++;
         freeBytes.release();
         emit disp(); // disp a slot of mainwindow.cpp   }   flag_stop = true;}Producer.cppvoid Producer::run(){	  i=0;	  while(!flag_stop)	  {		  if(flag_read)		  {		     freeBytes.acquire();		     int n = read_str.size();		      buffer[i % 8096] = (*((read_str.toUtf8().constData())+(n-1)));		      i++;	   	      usedBytes.release();	   	      flag_read = false;		 } 	   }	  flag_stop = true;} Mainwindow.cpp...connect(textEdit_1,SIGNAL(textChanged()),this,SLOT(read_send()));	connect(pushButton_14,SIGNAL(clicked()),this,SLOT(Start_Thread()));	connect(pushButton_15,SIGNAL(clicked()),this,SLOT(Stop_Thread()));	consumer = new Consumer();	producer = new Producer();    connect(consumer,SIGNAL(disp()),this,SLOT(receive_write()));...void MainWindowImpl::Start_Thread(){    producer->start();    consumer->start();		}void MainWindowImpl::Stop_Thread(){	flag_stop = true;}void MainWindowImpl::read_send(){	read_str = textEdit_1->toPlainText();	flag_read = true;}void MainWindowImpl::receive_write(){   textEdit_2->setText(write_str);}void MainWindowImpl::closeEvent(QCloseEvent *event){       flag_stop = true;       event->accept();}
Consumer.cpp
void Consumer::run() {
   j = 0;
   while (!flag_stop) {
      usedBytes.acquire();
      write_str += buffer[j % 8096];
      j++;
      freeBytes.release();
      emit disp(); // disp a slot of mainwindow.cpp
   }
   flag_stop = true;
}
Producer.cpp
void Producer::run() {
   i = 0;
   while (!flag_stop) {
      if (flag_read) {
         freeBytes.acquire();
         int n = read_str.size();
         buffer[i % 8096] = ( * ((read_str.toUtf8().constData()) + (n - 1)));
         i++;
         usedBytes.release();
         flag_read = false;
      }

   }
   flag_stop = true;
}

Mainwindow.cpp
   ...
   connect(textEdit_1, SIGNAL(textChanged()), this, SLOT(read_send()));
connect(pushButton_14, SIGNAL(clicked()), this, SLOT(Start_Thread()));
connect(pushButton_15, SIGNAL(clicked()), this, SLOT(Stop_Thread()));
consumer = new Consumer();
producer = new Producer();
connect(consumer, SIGNAL(disp()), this, SLOT(receive_write()));
...
void MainWindowImpl::Start_Thread() {
   producer - > start();
   consumer - > start();
}
void MainWindowImpl::Stop_Thread() {
   flag_stop = true;
}
void MainWindowImpl::read_send() {
   read_str = textEdit_1 - > toPlainText();
   flag_read = true;
}
void MainWindowImpl::receive_write() {
   textEdit_2 - > setText(write_str);
}
void MainWindowImpl::closeEvent(QCloseEvent * event) {
   flag_stop = true;
   event - > accept();
}
1._
void MainWindowImpl::Stop_Thread() {
   flag_stop = true;
   producer - > release();
   consumer - > release();
   producer - > wait();
   consumer - > wait();
}
void Producer::run() {
   i = 0;
   while (!flag_stop) {
      if (flag_read) {
         freeBytes.acquire();
         if (flag_stop) return;
         int n = read_str.size();
         buffer[i % 8096] = ( * ((read_str.toUtf8().constData()) + (n - 1)));
         i++;
         usedBytes.release();
         flag_read = false;
      }
   }
   flag_stop = true;
}
void Consumer::run() {
      j = 0;
      while (!flag_stop) {
         usedBytes.acquire();
         if (flag_stop) return;
         write_str += buffer[j % 8096];
         j++;
         freeBytes.release();
         emit disp(); // disp a slot of mainwindow.cpp   }   flag_stop = true;}
2._
void MainWindowImpl::Stop_Thread() {
   flag_stop = true;
   producer - > release();
   consumer - > release();
   producer - > wait();
   consumer - > wait();
}
void Producer::run() {
   i = 0;
   while (!flag_stop) {
      if (flag_read) {
         freeBytes.acquire();
         if (flag_stop) return;
         int n = read_str.size();
         buffer[i % 8096] = ( * ((read_str.toUtf8().constData()) + (n - 1)));
         i++;
         usedBytes.release();
         flag_read = false;
      }
   }
   flag_stop = true;
}
void Consumer::run() {
      j = 0;
      while (!flag_stop) {
         usedBytes.acquire();
         if (flag_stop) return;
         write_str += buffer[j % 8096];
         j++;
         freeBytes.release();
         emit disp(); // disp a slot of mainwindow.cpp   }   flag_stop = true;}
void MainWindowImpl::Stop_Thread() {
   flag_stop = true;
   producer - > release();
   consumer - > release();
   producer - > wait();
   consumer - > wait();
}

void Producer::run() {
   i = 0;
   while (!flag_stop) {
      if (flag_read) {
         freeBytes.acquire();
         if (flag_stop) return;
         int n = read_str.size();
         buffer[i % 8096] = ( * ((read_str.toUtf8().constData()) + (n - 1)));
         i++;
         usedBytes.release();
         flag_read = false;
      }

   }
   flag_stop = true;
}

void Consumer::run() {
   j = 0;
   while (!flag_stop) {
      usedBytes.acquire();
      if (flag_stop) return;
      write_str += buffer[j % 8096];
      j++;
      freeBytes.release();
      emit disp(); // disp a slot of mainwindow.cpp
   }
   flag_stop = true;
}
1._
void MainWindowImpl::Stop_Thread() {
      flag_stop = true;
      freeBytes.release(); //QSemaphore freeBytes;	usedBytes.release();  //QSemaphore usedBytes;	producer->wait();  	consumer->wait();}
2._
void MainWindowImpl::Stop_Thread() {
      flag_stop = true;
      freeBytes.release(); //QSemaphore freeBytes;	usedBytes.release();  //QSemaphore usedBytes;	producer->wait();  	consumer->wait();}
void MainWindowImpl::Stop_Thread() {
   flag_stop = true;
   freeBytes.release(); //QSemaphore freeBytes;
   usedBytes.release(); //QSemaphore usedBytes;
   producer - > wait();
   consumer - > wait();
}

Suggestion : 4

 March 23, 2022     pyside, pyside6, python, zeromq     No comments   

The problem is as soon as I close that dialog, I get the following

QThread: Destroyed
while thread is still running

Process finished with exit code - 1073740791(0xC0000409)

Here is my code:

class ZMQThread(QThread):
   msg_received = Signal()

def __init__(self):
   super(ZMQThread, self).__init__()
self.context = zmq.Context()
self.socket = self.context.socket(zmq.REP)
self.socket.bind("tcp://*:3344")

def run(self):
   while True:
   message = self.socket.recv()
self.msg_received.emit()

class MyWindow(QtWidgets.QDialog):
   def __init__(self):
   super(MyWindow, self).__init__()
self.ui = Ui_MyDialog()
self.ui.setupUi(self)
self.ui.ButtonOK.clicked.connect(self.ok)

def ok(self):
   self.accept()

class App:
   def __init__(self):
   self.qtapp = QtWidgets.QApplication([])
self.my_window = MyWindow()
self.zmq_thread = ZMQThread()
self.zmq_thread.msg_received.connect(self.show_my_window)
self.zmq_thread.start()

def show_my_window(self):
   self.my_window.show()

if __name__ == '__main__':
   my_gui = App()
sys.exit(my_gui.qtapp.exec())

By default, Qt ends the eventloop when the last open window is closed, and when the eventloop ends, the QThread does not close correctly. The solution is to disable this feature using the quitOnLastWindowClosed property:

self.qtapp = QtWidgets.QApplication([])
self.qtapp.setQuitOnLastWindowClosed(False)

Suggestion : 5

I am trying to run ZeroMQ in a QThread. What anycodings_zeromq I do is when a message arrives I emit the anycodings_zeromq msg_received signal. In the App class the anycodings_zeromq show_my_window method is connected to it so anycodings_zeromq it will display a simple dialog.,The problem is as soon as I close that anycodings_zeromq dialog, I get the following,How to get result using registerForActivityResult from within ktor's Routing call running in a non-activity class?,I don't have a main window here, wondering anycodings_zeromq if that could be a problem? I don't want a anycodings_zeromq main window, this app will run on the tray anycodings_zeromq but first I want to implement this part. I anycodings_zeromq have checked some very similar questions but anycodings_zeromq after checking those solutions they did not anycodings_zeromq work. What could be the issue here?

The problem is as soon as I close that anycodings_zeromq dialog, I get the following

QThread: Destroyed
while thread is still running

Process finished with exit code - 1073740791(0xC0000409)

Here is my code:

class ZMQThread(QThread):
   msg_received = Signal()

def __init__(self):
   super(ZMQThread, self).__init__()
self.context = zmq.Context()
self.socket = self.context.socket(zmq.REP)
self.socket.bind("tcp://*:3344")

def run(self):
   while True:
   message = self.socket.recv()
self.msg_received.emit()

class MyWindow(QtWidgets.QDialog):
   def __init__(self):
   super(MyWindow, self).__init__()
self.ui = Ui_MyDialog()
self.ui.setupUi(self)
self.ui.ButtonOK.clicked.connect(self.ok)

def ok(self):
   self.accept()

class App:
   def __init__(self):
   self.qtapp = QtWidgets.QApplication([])
self.my_window = MyWindow()
self.zmq_thread = ZMQThread()
self.zmq_thread.msg_received.connect(self.show_my_window)
self.zmq_thread.start()

def show_my_window(self):
   self.my_window.show()

if __name__ == '__main__':
   my_gui = App()
sys.exit(my_gui.qtapp.exec())

By default, Qt ends the eventloop when anycodings_pyside the last open window is closed, and when anycodings_pyside the eventloop ends, the QThread does not anycodings_pyside close correctly. The solution is to anycodings_pyside disable this feature using the anycodings_pyside quitOnLastWindowClosed property:

self.qtapp = QtWidgets.QApplication([])
self.qtapp.setQuitOnLastWindowClosed(False)

Suggestion : 6

Pyqt Qthread Destroyed While Thread Is Still Running, 6 days ago 技术标签: pyqt. qthread destroyed while thread is still running. 然后报错(windows下):QThread: Destroyed while thread is still running,程序直接崩溃. 解决办法: … , 2 days ago Jul 22, 2020  · JonB 24 Jul 2020, 08:00 @Yok0. @Yok0 said in PYQT5 QThread: Destroyed while thread is still running: QProcess / Qthread destroyed while. You get this when you … , 1 week ago QThread: Destroyed while thread is still running ? 技术标签: QT5 qt. 原因: 线程没有正常销毁。. 考虑你的QThread是不是在另一个线程中没有存在栈上,即没有 new QThread?. 改 …


QThread: Destroyed
while thread is still running

def stopLightsThread(self): print('stop lightsThread') self.lightsWorker.stop() self.lightsThread.quit() self.lightsThread.wait()
thread = QThread()
thread = QThread(parent = self)