[Qt-interest] Do QTimer Race Conditions Exist

Andreas Pakulat apaku at gmx.de
Thu Feb 11 19:51:24 CET 2010


On 11.02.10 10:07:23, Will Rutherdale (rutherw) wrote:
> I am wondering about reliability of QTimer if it is used in certain
> ways.  I am not questioning the internal robustness, but whether I have
> to take certain precautions in using it.  I have an application where
> getting it right is critical.  On the other hand I don't want to
> over-engineer if it is not necessary.
> 
> The situation is like this.  Suppose I have a class criticalClass
> derived from QObject with these slots:
> 
>     void slotFoo();
>     void slotTimerResponse();
> 
> Also my class has a timer, used in singleshot mode:
> 
>     QTimer *timer_t_;
> 
> Also, a connect() has been done between timer_t_'s timeout() signal and
> slotTimerResponse().  And suppose somewhere in the code I do this:
> 
>     timer_t_->start();
> 
> Now slotTimerResponse():
> 
> void criticalClass::slotTimerResponse()
> {
>     qCritical() << "Holy smokes what a HORRIBLE thing:  the timer has
> expired.  Blowing up the whole system in despair!!!";
>     // ...
> }
> 
> Now somewhere else in the code, in slotFoo(), while the timer is active,
> some expected event happens and the code does this:
> 
>     timer_t_->stop();
> 
> My question:  is it enough that I called stop() on the timer inside
> slotFoo()?  I can see that the timer will stop running at that point,
> but is it not also possible that, in parallel with that, while that slot
> is active, the timer will emit its signal timeout().

Not unless you run a multi-threaded application with slotFoo executing
in one thread and the eventloop which "executes" the timer in another.
The reason is simply that while a slot is executed the event loop
doesn't run and hence the timer doesn't get its timeout-event. QTimer is
event-based, hence it can only emit its signal once it receives its
QTimerEvent(). That doesn't happen if the event-loop is run. As
non-timer slot execution usually happens due to some kind of event
(user-input etc.) the slot blocks the event loop.

If you want to know for sure: qtimer.cpp in the Qt sources isn't that
complicated and IIRC neither is the function calls it does to actually
create/start a timer.

Andreas

-- 
If you stand on your head, you will get footprints in your hair.



More information about the Qt-interest-old mailing list