Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QObject::deleteLater across a QThread

Tags:

c++

qt

I'm looking for a solution to schedule the deletion of an object across threads. The docs about how deleteLater behave are not entirely clear. Can I call this function in a thread which is not the object's owner?

For example, Object X is owned by Thread A, and in Thread B I would like to have Object X deleted. As the object may be inside event processing at the moment (in Thread A) I can't safely delete it until it gets back to the message loop. If I call deleteLater from Thread B however the docs seem to indicate it will delete as soon as Thread B gets back to the message loop.

Currently I take the approach of having a signal emitted in Thread A which is attached to a slot which calls deleteLater. I'm wondering if there is perhaps an easier way to do this -- if indeed I can just call deleteLater from any thread.

like image 227
edA-qa mort-ora-y Avatar asked Mar 09 '12 11:03

edA-qa mort-ora-y


Video Answer


1 Answers

Looking at the Qt 4 code and Qt 5 code, deleteLater() just invokes QCoreApplication::postEvent() which is explicitly declared thread-safe. So, it should be fine to just call it directly. As the event queue is processed in the object's owner thread, deletion will happen in thread A.

Only Qt 5 QObject documentation explicitly lists deleteLater() as thread safe. If you want to completely rely on documented behaviour in Qt 4, use postEvent().

like image 66
Tilman Vogel Avatar answered Sep 29 '22 20:09

Tilman Vogel