本文介绍了跨QThread的QObject :: deleteLater的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种解决方案,以计划在多个线程之间删除对象。关于 deleteLater 行为的文档尚不完全清楚。我可以在不是对象所有者的线程中调用此函数吗?

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?

例如,对象X由线程A拥有,而在线程B中,我希望删除对象X。由于该对象目前可能在事件处理中(在线程A中),因此我无法安全地删除它,直到它返回到消息循环为止。如果我从线程B调用 deleteLater ,文档似乎表明它将在线程B返回消息循环后立即删除。

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.

当前,我采用的方法是在线程A中发出一个信号,该信号附加到调用 deleteLater 的插槽中。我想知道是否可能有一种更简单的方法-如果确实可以从任何线程调用 deleteLater

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.

推荐答案

查看和, deleteLater()仅调用 QCoreApplication :: postEvent()显式声明为线程安全的。因此,直接调用它应该很好。由于事件队列是在对象的所有者线程中处理的,因此删除将在线程A中发生。

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.

仅Qt 5 明确列出 deleteLater()作为线程安全的。如果要完全依赖Qt 4中记录的行为,请使用 postEvent()

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().

这篇关于跨QThread的QObject :: deleteLater的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 17:22
查看更多