[Qt-interest] Is it sensible to call "delete this; " at the end of a QThread's run method?

K. Frank kfrank29.c at gmail.com
Mon May 30 01:18:31 CEST 2011


Hello List!

I have a worker class derived from QThread, and now I want to be able
to clean up its instance programmatically while the application is running,
rather than just when the application terminates.

I'm thinking of using QThread's quit slot to cause it to exit its event
loop, and then having the the run method execute delete(this).

Specifically:

    void run() {
      timer_ = new QTimer(this);
      connect(timer_, SIGNAL(timeout()), this, SLOT(update()));
      timer_->start (updateTime_);
      exec();
      delete (this);    // <-- new line of code; does it make sense?
    }


(Note, just for your information, and with no intention to reopen the
debate:  My QThread object has thread affinity for itself as I call
"moveToThread (this);" in the QThread's constructor.)

The point is that I don't want to delete the QThread from the gui thread
(where it was new'ed) because I don't want to rip it our from under itself
while it might still processing its event loop.

So the idea is my gui thread triggers QThread's quit slot to cause the
QThread's exec() method to return.  (Am I correct that the quit slot causes
the QThread's event loop to exit cleanly and synchronously after any of
my custom event-processing code has completed and returned control
to the event loop?)  After exec() returns, "delete (this)" releases the
QThread object's memory (and hypothetically any other resources it
allocated).  Is this scheme legitimate?  Or would I be setting myself
up for trouble somehow?

(As an aside, is it okay to call QThread's quit() (or exec()) member
function directly from the gui thread, rather than through a signal-slot
connection?  Also, am I right that because the QThread allocates the
QTimer it uses with "timer_ = new QTimer (this);", i.e., setting itself as
the QTimer's parent, the QThread's destructor will delete the QTimer?)

Thanks for any information on this.


K. Frank



More information about the Qt-interest-old mailing list