What confuses me about QThread and delete from within slot is that, finished() is emited after thread event loop stops(I assume that after this signal it is guaranteed that qthread event loop stops immediately - please read * ). At this point execution of thread ended and there is no pending event's inside QThread (in case presented above, of course there can be some pending user event's that needs to be dealt with ). So I assumed that I can delete that QThread object because there is no pending events (to ensure that this is true I manually disconnect object ).
*Or when finished() is emited event loop, depending on the i.e. CPU load, is still running, but it's event loop is queued to stop, so deleting qthread within finished() slot will actually crash app, because event loop of qthread didn't stooped yet,of course this is if'y situation depending on the various factors like cpu load, app context, etc..
So as far as I understand correct way of deleting qobject, in this case qthread, is to:
void Dialog::slotBtn(void)
{
// MyThread *myt; // declared in the class - on stack
myt = new MyThread;
connect( myt, SIGNAL(finished()), this, SLOT(mytFinishedSlot()));
button->setEnabled(false); //to prevent running again the same thread
myt->start();
}
void Dialog::mytFinishedSlot(){
//retrieve the data from the thread
myt.deleteLater();
button->setEnabled(true); //"turn one" button
}
void Dialog::slotBtn(void)
{
// MyThread *myt; // declared in the class - on stack
myt = new MyThread;
connect( myt, SIGNAL(finished()), this, SLOT(mytFinishedSlot()));
button->setEnabled(false); //to prevent running again the same thread
myt->start();
}
void Dialog::mytFinishedSlot(){
//retrieve the data from the thread
myt.deleteLater();
button->setEnabled(true); //"turn one" button
}
To copy to clipboard, switch view to plain text mode
Bookmarks