0

I have a QT C++ application that has multiple threads running, and the threads use the QCoreApplication::postEvent mechanism to transmit information to each other. The QCoreApplication::postEvent documentation explicitly states the the event must be allocated on the heap, and that it is not safe to access the event after it has been posted.

http://doc.qt.io/qt-5/qcoreapplication.html#postEvent

When one thread in my application recieves an event (via QObject::event) that was sent to it by another thread, it will often "forward" the event to a different thread via the postEvent method. Is this safe? Should I instead create a brand-new event that is a copy of the original? My application hasn't crashed at all....but that doesn't mean the risk isn't there. When is a QT event considered "posted"?

bool MyQObjectDerivedClass::event(QEvent* evnt)
{
    // When  is QEvent considered posted?
    if(evnt->type() == MY_EVENT_TYPE)
    {
        // Forward the event..
        // Is this safe?  Or should I create a copy of the event?
        QCoreApplication::postEvent(myOtherQObjectClassPtr,evnt);
        return true;
    }
    else
    {
        return QObject::event(evnt);
    }
}
IAS_LLC
  • 135
  • 11
  • 1
    I can't directly answer your question, but I can point out that cross-thread/queued signals rely on the event queue. Using signals and slots is a safer methodology (and you don't have to check the event type, since you can just connect to a specific slot for each event/signal). – jonspaceharper Mar 04 '17 at 21:58

1 Answers1

1

When you post an event, as opposed to using sendEvent, the ownership of the event pointer is transferred to the receiver object's event loop.

It will delete the event after it has delivered it to the object, i.e. after the object's event() method has returned.

So if you need to pass information on asynchronously, you will need to copy it before returning from your event() implementation

Kevin Krammer
  • 5,159
  • 2
  • 9
  • 22