Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to implement busy loop?

Tags:

c

linux

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 ?
like image 932
Whoami Avatar asked Oct 01 '11 12:10

Whoami


2 Answers

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.

like image 155
rodrigo Avatar answered Sep 30 '22 05:09

rodrigo


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.

like image 32
Matvey Aksenov Avatar answered Sep 30 '22 07:09

Matvey Aksenov