waterd
waterd

Reputation: 651

Mechanism of QTimer

Suppose that timer is a object of QTimer, the timer's interval is iInterval and timer's timeout signal is connected to a slot sltTimeout().

I was just thinking what would happen if iInterval is smaller than the time it takes for sltTimeout() to run. Will multiple threads run sltTimeout() as a result? If so, it seems that could cause problems with unsynchronized access to an object.

Can anyone clarify it?

Upvotes: 0

Views: 341

Answers (2)

László Papp
László Papp

Reputation: 53165

Will multiple threads run sltTimeout() as a result?

It will not run automagically so, no. You will need to make sure it is done like that if desired, e.g. if it is doing some computation.

If so, it seems that could cause problems with unsynchronized access to an object.

Yes and no.

It is nothing special in this case, just general thread programming. You would need to use thread sync'ing primitives, like QMutex, QMutexLocker, QSemaphore, and so on.

Another trick you could do is to stop the timer invokation when the slot is processed, but that has the compromise you may not wish to take.

Do not forget that the event would be queued by default, so if you do not depend on the previous run of your sltTimeout in the next run, you could even ignore threading "if you have enough time" to get it done. If there is dependency between subsequent invocations, then yeah, you need to become smart in code.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 993303

A QTimer runs on the thread from which it was started. Since it only runs on one thread, it is not possible for it to emit its timeout() signal more than once before the previous slot function has returned.

From the QTimer documentation:

Qt uses the timer's thread affinity to determine which thread will emit the timeout() signal.

Upvotes: 6

Related Questions