Why to sleep 1?

125 views Asked by At

I understand that, in a endless loop or somewhere else, you could sleep(0) to leave the OS to perform a context-switching and execute another thread (if there is and it is ready to execute). Now, I saw a bunch of code where people use sleep(1) instead of sleep(0).

Is this optimal?
Where may I found documentation about it?

2

There are 2 answers

2
Guntram Blohm On BEST ANSWER

If you're implementing something like 'check for the existence of a file, repeat until it exists, then continue', it's better to do a sleep(some_small_positive_number), so you don't use up 100% of CPU time.

Polling loops like this are almost always a sign of improper planning when used in a program, but are used often in command line scripts.

0
Martin James On

99.9% of the time, such short loops are a symptom of poor design, inadequate understanding of inter-thread comms or just laziness 'cos polling seems easier.

Most while(true) loops in multithreaded calls need no Sleep() calls at all because they block on some other call, I/O or inter-thread synchro objects.

In those cases where a loop does not block on anything, you still need no sleep() calls if the work being done is making real forward progress. Putting in a sleep() call just slows down real work. If the work has an undesirable impact on the system as a whole, lower the priority of the work threads instead of shoving in sleep() calls.

The evil is looping purely for the purpose of polling flags. This is done so often that sleep() itself is often regarded as intrinsically evil. It is not - it's the misuse of it that should stop.

There is not much, on modern OS, that requires polling. File systems, for example, give notifications upon file creation, eliminating the need to continually check and removing the latency and CPU-waste of sleep() loops.