QObject::deleteLater across a QThread

前端 未结 3 1209
甜味超标
甜味超标 2020-12-11 04:03

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

相关标签:
3条回答
  • 2020-12-11 04:43

    While deleteLater() is not safe itself, you can invoke it in object's threadA with meta call:

    metaObject()->invokeMethod(object, "deleteLater", Qt::QueuedConnection);
    

    Then, it will be safe.

    0 讨论(0)
  • 2020-12-11 04:44

    deleteLater() only means that the object will be deleted after all signal/slots int the current event loop (i.e. ThreadB) have been treated.

    So, if no other slots need ObjectX in ThreadB, it is equivalent to a plain delete.

    Whether you can delete the object or not and how it will be handled in ThreadA is up to your app logic.

    If ObjectX is the main object of the thread, sending the quit() signal to ThreadA is the way to go.

    0 讨论(0)
  • 2020-12-11 04:47

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

    0 讨论(0)
提交回复
热议问题