Androidicus
Androidicus

Reputation: 1748

Properly delete QThread

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.

Upvotes: 1

Views: 3825

Answers (2)

t3ft3l--i
t3ft3l--i

Reputation: 1412

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

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

Upvotes: 0

UmNyobe
UmNyobe

Reputation: 22920

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.

Upvotes: 1

Related Questions