PDA

View Full Version : safe to delete object in other thread?



iraytrace
21st October 2011, 22:29
Is it safe to delete an object that is in a thread other than the current thread? For example:



MyObject *m = new MyObject();
// connect signal/slots, etc.
m->moveToThread(otherThread);

// much later in same thread:

delete m;


The question is: Does the "otherThread" know the object is deleted? If not, this could this cause a problem with event handling in otherThread. This would not seem to be solved by "deleteLater" because there are two different threads of execution. Is it necessary to have a "selfDestruct()" method on the "MyObject" which calls deleteLater? If the thread uses a QPointer or QSharedPointer internally this would probably be OK.

amleto
21st October 2011, 22:33
there are multiple factors to consider here. if you do 'new', and dont parent the QObject, then you are responsible for 'delete'ing it. You dont need to worry about signals slots when you delete a QObject, because they are disconnected automatically.

Using deleteLater() should be ok.

wysota
21st October 2011, 23:12
Is it safe to delete an object that is in a thread other than the current thread?
No.


The question is: Does the "otherThread" know the object is deleted?
If you are unfortunate enough to delete the object while one of its methods is running, it will surely realize that when the OS kills the process :)


This would not seem to be solved by "deleteLater" because there are two different threads of execution.
Using deleteLater() should be safe, at least if you call it as a slot.