-1

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?

EProgrammerNotFound
  • 2,403
  • 4
  • 28
  • 59
  • 2
    Why the downvotes? Sure this question is based on a flawed premise. But it’s a good question nevertheless, especially since that flawed premise is quite widely held. – Konrad Rudolph Dec 13 '13 at 18:14
  • @KonradRudolph Please, explain the flaw in my premise, if there is one, I must stop stating it. – EProgrammerNotFound Dec 13 '13 at 18:29
  • 2
    @KonradRudolph - yeah, I've seen worse questions, even if this sounds a bit like 'I'm gonna crash my car today - is it better to hit a tree or a brick wall?'. – Martin James Dec 13 '13 at 19:31

2 Answers2

3

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.

Guntram Blohm
  • 9,667
  • 2
  • 24
  • 31
2

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.

Martin James
  • 24,453
  • 3
  • 36
  • 60