1
votes

I'm new to QT and I'm trying to create and destroy a QThread upon button click (potentially multiple times). I've read through a lot of posts but my Thread either didn't get destroyed or caused a untraceable heap exception within the QMain.dll.

I create my Thread like this:

thread = new QThread;
reader = new Reader(); //a QObject subclass
reader->moveToThread(thread);
connect(thread, SIGNAL(started()), reader, SLOT(read()));
connect(reader, SIGNAL(timeout()), this, SLOT(threadTimeout()));

connect(reader, SIGNAL(finished()), reader, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), this, SLOT(threadFinished()));

The Thread then runs in a loop and sends data. The read() function looks like this:

void Reader::read() { 
  while(!stop) {
    //... do something ...
  }
  emit finished();
}

On Button click I call

reader->setStop(true);

which breaks the Thread's while-loop. The finished signal is emitted but then a memory exception is triggered. If I remove the two deleteLater() slots no exception is raised but the thread is (obviously) not deleted.

Am I doing something wrong here? Thanks in advance.

2
Have a look at QThread in Qt docs. The worker is not connected to deleteLater, and the worker resultReady, which I assume is the same as your Reader::finished, is connected to the slot handleResults, which I assume is the same as your threadFinished. Have a look there and adjust consequently. - Miki
I've tried that but this doesn't delete my thread. In this example thread->quit() and thread->wait() is called within the destructor of main class. I cannot do that because I want to open and close the thread multiple times without ever calling the destructor of the main class. - Androidicus

2 Answers

1
votes

The main issue is that you are deleting the thread object (ie the QThread) while the thread of execution is running. In your threadFinished(), which is actually task finished, you need to do :

 thread->quit();
 thread->wait();
 thread->deleteLater();
 reader->deleteLater();

and remove the finished -> deleteLater connections.

0
votes

Try to add connection like this one for leaving thread event loop.

connect(reader, SIGNAL(finished()), thread, SLOT(quit()));