tags:

views:

128

answers:

6

Here is what I know about concurrency in OS.

In order to run multi-task in an OS, the CPU will allocate a time slot to each task. When doing task A, other task will "sleep" and so on.

Here is my question:

I have a timer program that count for inactivity of keyboard / mouse. If inactivity continues within 15min, a screen saver program will popup.

If the concurrency theory is as I stated above, then the timer will be inaccurate? Because each program running in OS will have some time "sleep", then the timer program also have chance "sleeping", but in the real world the time is not stop.

+1  A: 

You would use services from the OS to provide a timer you would not try to implement yourself. If code had to run simple to count time we would still be in the dark ages as far as computing is concerned.

AnthonyWJones
A: 

This could be language-dependent. In Java, it's not a problem. I suspect that all languages will "do the right thing" here. That's with the caveat that such timers are not extremely accurate anyway, and that usually you can only expect that your timer will sleep at least as long as you specify, but might sleep longer. That is, it might not be the active thread when the time runs out, and would therefore resume processing a little later.

Don Branson
A: 

See for example http://www.opengroup.org/onlinepubs/000095399/functions/sleep.html

The suspension time may be longer than requested due to the scheduling of other activity by the system.

Lieven
+1  A: 

In most operating systems, your task will not only be put to sleep when its time slice has been used but also while it is waiting for I/O (which is much more common for most programs).

Like AnthonyWJones said, use the operating system's concept of the current time.

The OS kernel's time slices are much too short to introduce any noticeable inaccuracy for a screen saver.

hillu
+1  A: 

I think your waiting process can be very simple:

  1. activityTime = time of last last keypress or mouse movement [from OS]
  2. now = current time [from OS]
  3. If now >= 15 mins after activityTime, start screensaver
  4. sleep for a few seconds and return to step 1

Because steps 1 and 2 use the OS and not some kind of running counter, you don't care if you get interrupted anytime during this activity.

Douglas Squirrel
A: 

The time you specify in sleep() is in realtime, not the cpu time your process uses. (As the CPU time is approximately 0 while your program sleeps.)

Georg