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 ?
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
.
Busy loop is loop that never blocks and continuously checks some condition. Small sleep is good enough to avoid 100% cpu usage.
The best way to implement busy wait is to not implement it. Instead of it you can use blocking calls or callbacks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With