[Qt-interest] Timer Events Execute in Wrong Thread

Andreas Pakulat apaku at gmx.de
Mon Jul 19 15:39:47 CEST 2010


On 19.07.10 09:10:36, Josiah Bryan wrote:
> Odd problem here - and it might just be me not understanding how to
> use QTimers in a QThread. Anyway, using a QThread here with a QTimer
> to generate signals every 30th of a second. In the "real" program,
> sometimes the processing to generate the signal can take a while
> (upwards of a second or more) - hence putting it in a QThread to not
> freeze the main app event loop, right?
> 
> Well, all good in theory. However, the attached test program shows
> that while the QThread::run() method is indeed executed in a
> separate thread, the slot the timer is connected to on the thread
> object (TestThread::tick(), private slot), executes in the main
> thread (according to QThread::currentThreadId()).

This is expected and normal behaviour. Your TestThread object is created
in the main thread and hence its thread-affinity is the main thread. The
connect() you do in its constructor uses Qt::AutoConnection as
connection-type. If you lookup the documentation for the connection type
you'll see that auto means direct-connection if the thread emitting the
signal and the thread that the target object belongs to are the same. On
the other hand if the target object's thread-affinity is different from
the emitting thread, then a queued-connection is done which makes sure
the slot is executed in the same thread to which the target object
belongs. This comparison is done when emitting the signal, not when
doing the connect.

So you have two options:

a) Move the TestThread object to itself using moveToThread, in which
case a direct-connection will be done
b) explicitly use Qt::DirectConnection and make sure that the tick-slot
is threadsafe.

Andreas

-- 
Perfect day for scrubbing the floor and other exciting things.



More information about the Qt-interest-old mailing list