[Interest] Thread guarantee on slots+timers

André Somers andre at familiesomers.nl
Mon Apr 14 13:04:47 CEST 2014


Sensei schreef op 14-4-2014 12:54:
> On 4/11/14, 10:26am, André Somers wrote:
>> Not quite, and it is not such a simple question at all. It depends on
>> which thread actually triggers the slot, and how. If you were to trigger
>> the slot, either by a direct method call or using a direct connection,
>> from two different threads, there are no guarantees of it being run
>> consequtively. It may run twice at the same time from two different
>> threads, or interleaved, or... There is just no telling.
> Thanks André, your point is clear.
>
>
>> If your slot is exclusively ran in a single thread, either because it is
>> only triggered from that thread or because you use queued connections
>> from other threads to trigger it, it will be ran consecutively for each
>> invocation. However, invocations that find their source in the event
>> queue (timers, but also queued connections) may be triggered later than
>> those that result from direct method calls or direct (or automatic,
>> within the same thread) connections. This is because the event  queue is
>> only processed again if you return to it. Before that, timer events or
>> queued signals are not processed and thus don't trigger the slots.
>
> Ok, so I need to enforce exclusivity if I need that. Actually the slot
> is called by two means:
> - thread itself via QTimer
> - main GUI thread via signal/slot
>
> Do you see a potential threat to the GUI (responsiveness) if I use a
> QMutex to serialize execution by force?
No, then you misunderstood the above. If you use an auto connection (the 
default) or a queued connection to hook up your GUI thread to the slot, 
you have fulfilled the criteria for the slot to be only triggered from 
within the same thread, and thus stricktly consecutively*. So if you can 
fulfil this simple condition, you would *not* need to use a mutex to 
make sure your slot does not get called twice at the same time.

André

*) barring recursion or a processEvents() call, of course. Then all bets 
are off again.




More information about the Interest mailing list