[Interest] QMetaObject::invokeMethod thread safety

Thiago Macieira thiago.macieira at intel.com
Fri May 17 19:47:17 CEST 2019


On Friday, 17 May 2019 10:25:15 PDT Matthew Woehlke wrote:
> IOW, I have some shared object owner by Thread 1 which is eventually
> deleted. In Thread 2, I want to queue a call to a slot on that object.

Thread-safety does not apply while the object in question is being destroyed.

> Historically I have used a shared pointer to pass the object between
> threads, because I *know* that is safe (the call will be queued before
> the object can possibly be deleted; if it gets deleted before the queued
> call dispatches, that's okay; I just care that the program doesn't crash
> / corrupt memory / eat kittens). If, OTOH, I were to use a bare pointer,
> I *know* that is unsafe, because I have no guarantee the object still
> exists (or, worse, that the pointer now refers to some other object)
> when I go to queue the call.

Right.

> What's less clear (without trying to dig through the guts of Qt's event
> queuing at least) is; in something like the above, is invokeMethod is
> guaranteed to be able to queue the call successfully if another thread
> deletes the target object some time between the start of the call to
> invokeMethod and when the event is fully created on Foo's thread's event
> queue (at which point it is "safe")?

It's not safe. Let me simplify further. The last thing that 
QMetaMethod::invoke does when queuing a call is:

        QCoreApplication::postEvent(object, new QMetaCallEvent(...));

But postEvent() still needs to inspect the receiver to find out which thread 
it is associated with, so it can add the event to that thread's posted event 
queue. So your code must guarantee that the object in question is still a 
valid QObject while postEvent() runs.

So, no, you can't race against the object's destruction. Ensure that the 
destructor has not begun running when you post an event or make a metacall or 
basically anything else.

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel System Software Products






More information about the Interest mailing list