deletion and cleanup of worker thread in Qt crashes

431 views Asked by At

I've followed up this link for creating a worker thread (using almost the same code).

I face an error right at the end of the code where cleanup is performed after the worker is done and the finished signal is emitted .

If I declare the thread and worker as pointers there is no problem (just like the link). But if I declare them like the following my program will crash after the destructor is called!!

QThread thread1;
MyWorker mywork1;
mywork1.moveToThread(&thread1);

QObject::connect(&thread1, SIGNAL(started()), &mywork1, SLOT(process()) );
QObject::connect(&mywork1, SIGNAL(finished()), &thread1, SLOT(quit()));
QObject::connect(&mywork1, SIGNAL(finished()), &mywork1, SLOT(deleteLater()));//****
QObject::connect(&thread1, SIGNAL(finished()), &thread1, SLOT(deleteLater()));//****

the problem is caused by lines marked //**** the error message reported follows: The inferior stopped because it received a signal from the Operating System. Signal name : SIGABRT Signal meaning : Aborted

Of course If i comment the lines my workers destructor will not be called and no error is reported. What is the reason behind the error and how can I cleanup the worker without getting an error?

1

There are 1 answers

0
TheDarkKnight On BEST ANSWER
QThread thread1;
MyWorker mywork1;

These are created on the stack and will be deleted when they go out of scope. You need to be dynamically creating them (with new), if you're going to delete them later on

QThread* thread1 = new QThread;
MyWorker* mywork1 = new MyWorker;