Sleep does not sleep for a specified period

I recently described how you can create your own usleep method when there isn’t one to use. one thing that people however tend to forget is that the sleep methods (sleep, usleep, nanosleep) only guarantees that the calling thread will be suspended for at least the given time. There is absolutely no guarantee that the thread will resume its execution immediately after that time. On most platforms you don’t really see the difference but there are exceptions. HPUX for example, even on an otherwise almost idle system I typically experience a delay of a few milliseconds even though I sleep for only a single microsecond.

So if you want your thread to sleep for an exact amount of time you have use a different approach than sleep. Even if you use some sort of synchronize mechanism (an event) and a timer (to trigger the event) there is no guarantee that the blocked thread will execute immediately when the event is triggered. This approach is more likely to work as expected than the use of sleep, but it is not fool proof since you never know what other processes execute on the system affecting your process’ execution.

The closest thing you can come to exact sleep times is also the ugliest solution. You can always have a busy loop checking if enough time has passed over and over again. This will however change the behavior of the sleep into a busy loop which is rarely a good solution to a problem.

Since only a minimum time can ever be guaranteed with a sleep method, regardless of implementation you should not write your code so that it depends on an exact sleep method. I think you’re actually addressing the wrong problem if you try getting an exact sleep. Instead try figuring out why you need an exact sleep and remove that reason because you’ll never be able to get it to work exactly right. Maybe good enough for now but you never know what will happen in the future so it’s just a bad design choice.

Comments (0)