-
timers implemantation
Lets say you have some programs that use a timer. Lets say that every X seconds the program sends a signal that is handled by a signal handler. Thus by a timer handler. The time is checked etc etc.
My point is how will the program know how much time has passed? It could:
1) Check every some milliseconds, which isn't efficient
2) The system might send a signal to the program every X seconds. But that goes back to 1) in a way.
You get the idea. How does the OS handle the "send a signal in X seconds" thing in an efficient way?
-
I should preface this by stating that it may not be as inefficient as you think. If you have a thread that specifcally signals in set intervals, then you can simply have it keep records of all the time signalled threads and send a signal accordingly.
Usually a system's most accurate clock is waaaaaaaay more accurate than 1ms. Yet, usually +-1ms is about as accurate as you can really trust your clock. Why? Because of the reasons you just mentioned here.
-
Timers are generally implemented within the OS as a queue which is sorted on "closest to expiring". The timer tick handler then processes the list by looking at the first element, if it's expired, it will set the owning process up to run next, with a "make a signal" step added to what the process should do when it "wakes up".
Most of the time, there is no expired timers, so the check is done quite quickly, and we go on with other work in the timer tick (such as processing the "which process has done how much work" admin tasks), and finally a check for "is any process over their quanta, if so, call the scheduler".
--
Mats
-
There may not even be periodic checks. Because of the queue, the one pending event could be delegated to an external chip which causes a high-priority hardware interrupt at the expired time. There would be no additional overhead to the main processor.