QTimer understanding
-
Hi,
Suppose a thread has a timer, which it started. Now it is in the middle of another slot's execution when the timeout occurs. What happens? Will the thread make "context switch" to itself to another slot? As if it were 2 threads? Ie, it will save the state of its working slot and go to timeout slot?
Thank you !
-
@JeniaR
Nope. Without you having separate threads Qt signal/slot execution is synchronous. The timer signal/slot can only be called when Qt execution is back in the main event loop, after finishing any previous slots. Qt signals are not "interrupts".Suppose a thread has a timer
Only just noticed this. If you are using a separate thread for the timer, with its own event loop, then its signals/slots are executed when that thread runs, independent of whatever might be going on in another thread.
-
@JonB The code is like this:
QThread A has a member QTimer *p, which is initialized in the following way:t = new QTimer();
t->moveToThread (this);
t->setSingleShot (true);
connect(t, SIGNAL(timeout ()),this, SLOT (onTimeout()), Qt:Queued connection);
t->start();So, it's guaranteed that if A is executing a slot, it will finish it and then move to timeout slot?
-
@JeniaR said in QTimer understanding:
So, it's guaranteed that if A is executing a slot, it will finish it and then move to timeout slot?
Yes, how should it work otherwise - the event is passed to the receivers event loop and when this event loop can process data, the corresponding slot is executed.
Don't know why a QTimer needs a separate thread though - it just makes things more complicated without a gain. -
@JonB and @Christian-Ehrlicher I don't understand, where is a separate thread? Thread A is one of the threads in an application, there're other threads which communicate with it, it needs to be separate thread. So, there's only thread A in my example, which creates new QTimer()
But what I don't understand is why this moveToThread... I think it does nothing, correct me if I'm wrong? -
-
@JeniaR said in QTimer understanding:
That thread does some working and that's why it's required as a separate thread
This still does not answer why a QTimer in this thread emits a signal which is handled in the main thread - this makes no sense.