sashoalm
sashoalm

Reputation: 79467

Does deleteLater() wait for all pending signals to be delivered?

I was thinking about writing this code:

emit finished();
deleteLater();

But it made me wonder if finished() would always be delivered before the object is deleted. I'm pretty certain it will be delivered for Qt::DirectConnection, but I'm not sure about Qt::QueuedConnection, or if the slot is in another thread.

Upvotes: 2

Views: 718

Answers (1)

TheDarkKnight
TheDarkKnight

Reputation: 27611

When you emit a signal, it is placed in the event queue of the thread of the receiving object for processing. Calling deleteLater also adds an event to the queue, so they will be performed sequentially if the receiving object and the object being deleted have the same thread affinity, regardless of the thread type.

If the sender and receiver have different thread affinity (running in different threads) then I would expect it is possible for deleteLater to be called before the emit is finished, if the receiver's event loop starts processing before the sender's event loop.

If you want to guarantee that finished is executed first, you can connect the sender and receiver with a blocking connection, which will halt the sender's thread until the message has been delivered.

connect(sender, SIGNAL(finished()), receiver, SLOT(handleFinished(), Qt::BlockingQueuedConnection);

Note that if using Qt::BlockingQueuedConnection and the sender and receiver have the same thread affinity, the application will be dead-locked.

Upvotes: 2

Related Questions