Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Why deleteLater can be connected with finished signal?
I have saw that many people recommend use the follow code to delete Qthread itself.
I have two question:
- Why this code is right? When the main loop of the main thread try to delete QThread, this thead may not even end since it still emited a signal before a short time. Does finished main I can delete it?
- If this is right, can we just write
if we have deleteRIGHTNOW slot?
twsimpson last edited by
"QObject::deleteLater()":http://qt-project.org/doc/qt-4.8/qobject.html#deleteLater adds an event to the event queue that will, in turn, delete the object. Remember that a QThread is not a thread, it simply represents control of a thread, when a thread is "finished" it has completed and so ended execution.
That does not answer both of the question……
For the first question, does a Qthread finished means its thread terminated? I don't think so.
twsimpson last edited by
The method QThread::run() is what's run in the new thread, once that method returns (when the event-loop ends) the thread ends execution. The thread isn't terminated, but it has ended.
But if the thread really ends, how qt can emit the signal?
The finished signal of a thread is emitted, when the execution ended, so the attached thread is not alive anymore. deleteLater is executed asynchronously in the event loop of the creating thread of the object, which is typically the main thread. Using this technique you can delete a thread object safely.
[quote author="zhou13" date="1346654213"]But if the thread really ends, how qt can emit the signal?[/quote]
Only the worker threadc ends, there is some magic code before and after execution of the thread (see code of QThread) which does the needed stuff.
It isn't convenient for me to see the code of QT.
So QThread uses more than one thread?
is also safe since this connection is not only queued, but also do after finished?
Sorry, I did not get the last question.
why isn't it convenient for you to look at Qt code? It explains all, and it implements all. Run is part opf the thread, there is some setup code before and some clean up code after QThread::run. This code emits the finished signal just before leaving the thread.
QThread does not use threads. QThread is the handler class for exactly one thread, not more, not less.
what do you mean by the connect question?
edit: that code might bring up a crash, as it deletes immediately and not waits for the next run of the event loop. If the connection is a queued connection and the receiving object does not live in the thread, it might work. But why create new things if working things exist? If deleteRIGHTNOW is done via a Queued connection, it could work, if it is done directly, it will crash.