QThread finished() connected to deletelater of a QObject

admin

Administrator
Staff member
I have thought a lot and read lot of articles before asking this question here. None of the articles gave me a proper answer.
<a href="http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/" rel="nofollow noreferrer">http://mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/</a>
Code:
 QThread* thread = new QThread;
 Worker* worker = new Worker();
 worker-&gt;moveToThread(thread);
 connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
 connect(thread, SIGNAL(started()), worker, SLOT(process()));
 connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
 connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
 connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
 thread-&gt;start();
Worker object has the affinity of the new thread.
<ol>
<li>Worker finished signal will call
Code:
quit()
on the thread. This will end the thread's event loop and initiates the thread finished signal.
</li>
<li>Worker
Code:
finished
signal is connected to the worker
Code:
deleteLater()
. According to
Code:
deleteLater()
documentation
</li>
</ol>
<blockquote>
Schedules this object for deletion.
The object will be deleted when control returns to the event loop.
If the event loop is not running
when this function is called (e.g.
Code:
deleteLater()
is called on an
object before
Code:
QCoreApplication::exec()
), the object will be deleted
once the event loop is started.
Note that entering and leaving a new
event loop (e.g., by opening a modal dialog) will not perform the
deferred deletion; for the object to be deleted, the control must
return to the event loop from which
Code:
deleteLater()
was called.
</blockquote>
<blockquote>
Note: It
is safe to call this function more than once; when the first deferred
deletion event is delivered, any pending events for the object are
removed from the event queue.**
</blockquote>
So when there is no event loop, since the thread is already exiting and it has already raised the finished signal and we will no longer start the same thread again. In this case the
Code:
deleteLater()
will never be handled since the event loop doesn't exist and and worker object will not be deleted at all. Does this not create a memory leak.?
Code:
 connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
 connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
If we think that swapping the two lines will fix the problem, then I have another question. QT clearly states that the order the slots getting called when a signal is emitted is undetermined
There are bunch of comments in the article link mentioned above . Even the author was not able to answer the question completely