When I create a
QTimer
object in Qt 5, and start it using thestart()
member function, is a separate thread created that keeps track of the time and calls thetimeout()
function at regular intervals?
For example,
QTimer *timer = new QTimer; timer->start(10); connect(timer,SIGNAL(timeout()),someObject,SLOT(someFunction()));
Here, how does the program know when timeout()
occurs? I think it would have to run in a separate thread, as I don't see how a sequential program could keep track of the time and continue its execution simultaneously. However, I have been unable to find any information regarding this either in the Qt documentation or anywhere else to confirm this.
I have read the official documentation, and certain questions on StackOverflow such as this and this seem very related, but I could not get my answer through them.
Could anyone explain the mechanism through which a QTimer
object works?
On searching further, I found that as per this answer by Bill, it is mentioned that
Events are delivered asynchronously by the OS, which is why it appears that there's something else going on. There is, but not in your program.
Does it mean that timeout()
is handled by the OS? Is there some hardware that keeps track of the time and send interrupts at appropriate intervals? But if this is the case, as many timers can run simultaneously and independently, how can each timer be separately tracked?
What is the mechanism?
Thank you.
Most of its non-GUI subclasses such as QTimer, QTcpSocket, QUdpSocket, QFtp, and QProcess, are also conditionally thread safe, making it possible to use these classes from multiple threads simultaneously.
The QTimer class provides a high-level programming interface for timers. To use it, create a QTimer, connect its timeout() signal to the appropriate slots, and call start(). From then on, it will emit the timeout() signal at constant intervals.
qTimer can be install via the [Python Package Index](http://pypi.python.org/pypi/qTimer) or via setup.py. qTimer depends upon [SQLAlchemy](http://pypi.python.org/pypi/SQLAlchemy) and [Alembic](http://pypi.python.org/pypi/alembic) to run. You should take the time to configure qTimer before running it for the first time.
Most platforms support a resolution of 1 millisecond, though the accuracy of the timer will not equal this resolution in many real-world situations. The accuracy also depends on the timer type. For Qt::PreciseTimer, QTimer will try to keep the accuracy at 1 millisecond.
When I create a QTimer object in Qt 5, and start it using the start() member function, is a separate thread created that keeps track of the time and calls the timeout() function at regular intervals?
No; creating a separate thread would be expensive and it isn't necessary, so that isn't how QTimer is implemented.
Here, how does the program know when timeout() occurs?
The QTimer::start() method can call a system time function (e.g. gettimeofday() or similar) to find out (to within a few milliseconds) what the time was that start() was called. It can then add ten milliseconds (or whatever value you specified) to that time and now it has a record indicating when the timeout() signal is supposed to be emitted next.
So having that information, what does it then do to make sure that happens?
The key fact to know is that QTimer timeout-signal-emission only works if/when your Qt program is executing inside Qt's event loop. Just about every Qt program will have something like this, usually near the bottom its main() function:
QApplication app(argc, argv); [...] app.exec();
Note that in a typical application, almost all of the application's time will be spent inside that exec() call; that is to say, the app.exec() call will not return until it's time for the application to exit.
So what is going on inside that exec() call while your program is running? With a big complex library like Qt it's necessarily complicated, but it's not too much of a simplification to say that it's running an event loop that looks conceptually something like this:
while(1) { SleepUntilThereIsSomethingToDo(); // not a real function name! DoTheThingsThatNeedDoingNow(); // this is also a name I made up if (timeToQuit) break; }
So when your app is idle, the process will be put to sleep inside the SleepUntilThereIsSomethingToDo() call, but as soon as an event arrives that needs handling (e.g. the user moves the mouse, or presses a key, or data arrives on a socket, or etc), SleepUntilThereIsSomethingToDo() will return and then the code to respond to that event will be executed, resulting in the appropriate action such as the widgets updating or the timeout() signal being called.
So how does SleepUntilThereIsSomethingToDo() know when it is time to wake up and return? This will vary greatly depending on what OS you are running on, since different OS's have different APIs for handling this sort of thing, but a classic UNIX-y way to implement such a function would be with the POSIX select() call:
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
Note that select() takes three different fd_set arguments, each of which can specify a number of file descriptors; by passing in the appropriate fd_set objects to those arguments you can cause select() to wake up the instant an I/O operations becomes possible on any one of a set of file descriptors you care to monitor, so that your program can then handle the I/O without delay. However, the interesting part for us is the final argument, which is a timeout-argument. In particular, you can pass in a struct timeval
object here that says to select(): "If no I/O events have occurred after (this many) microseconds, then you should just give up and return anyway".
That turns out to be very useful, because by using that parameter, the SleepUntilThereIsSomethingToDo() function can do something like this (pseudocode):
void SleepUntilThereIsSomethingToDo() { struct timeval now = gettimeofday(); // get the current time struct timeval nextQTimerTime = [...]; // time at which we want to emit a timeout() signal, as was calculated earlier inside QTimer::start() struct timeval maxSleepTimeInterval = (nextQTimerTime-now); select([...], &maxSleepTimeInterval); // sleep until the appointed time (or until I/O arrives, whichever comes first) } void DoTheThingsThatNeedDoingNow() { // Is it time to emit the timeout() signal yet? struct timeval now = gettimeofday(); if (now >= nextQTimerTime) emit timeout(); [... do any other stuff that might need doing as well ...] }
Hopefully that makes sense, and you can see how the event loop uses select()'s timeout argument to allow it to wake up and emit the timeout() signal at (approximately) the time that it had previously calculated when you called start().
Btw if the app has more than one QTimer active simultaneously, that's no problem; in that case, SleepUntilThereIsSomethingToDo() just needs to iterate over all of the active QTimers to find the one with the smallest next-timeout-time stamp, and use only that minimum timestamp for its calculation of the maximum time-interval that select() should be allowed to sleep for. Then after select() returns, DoTheThingsThatNeedDoingNow() also iterates over the active timers and emits a timeout signal only for those whose next-timeout-time stamp is not greater than the current time. The event-loop repeats (as quickly or as slowly as necessary) to give a semblance of multithreaded behavior without actually requiring multiple threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With