[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
Tue May 31 05:13:30 CEST 2011


Hello Thiago and Chris!

On Mon, May 30, 2011 at 2:58 AM, Thiago Macieira <thiago at kde.org> wrote:
> On Sunday, 29 de May de 2011 21:28:33 K. Frank wrote:
>> I take it you're saying that "delete this" (within run()) is wrong and
>> potentially
>> dangerous, irrespective of the thread-affinity issue.  Is this right?
>
> Yes. It's very wrong. Like you guessed yourself, the function that called
> run() does some clean up before actually exiting the thread.

Based on your advice, I did not use the "delete this" scheme.  It does
sound like it would have been asking for trouble.

What I am doing now is calling my QThread's quit() method directly from my
main gui thread (i.e., I am not calling it through a signal-slot connection).
(Although I didn't see anything explicit about this in the documentation, my
analysis suggests that the quit() method should be thread-safe in this context.)

The QThread's finished() signal is connected to a custom slot in my main gui
object, and this slot calls "delete pointerToThread;".  The assumption is that
the finished signal will not fire until the QThread is well and truly done with
everything it feels the need to do, and is safe for deletion.

As far as I can tell (testing, but not really stress testing), this is
working just
the way I expect.

> ...
> Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
>  Senior Product Manager - Nokia, Qt Development Frameworks

Thanks for your help and explanations.


K. Frank



More information about the Qt-interest-old mailing list