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);
}
}
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