Skip to content
Advertisement

Best way to implement busy loop?

What is the best way to implement the busy loop ? correct me if i am wrong ?

while (1); // obviously eats CPU. 
while (1) { sleep(100); } // Not sure if it is the correct way ?

Advertisement

Answer

To do an infinite wait, for a signal (what else) there is the pause() system call. You’ll have to put it in a loop, as it returns (always with -1 and errno set to EINTR) every time a signal is delivered:

while (1)
    pause();

As a curious note, this is, AFAIK the only POSIX function documented to always fail.

UPDATE: Thanks to dmckee, in the comments below, sigsuspend() also fails always. It does just the same as pause(), but it is more signal-friendly. The difference is that it has parameters, so it can fail with EFAULT in addition to EINTR.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement