|Design| BAD smell: empty infinite loop

Some people like to use empty infinite loop to implement the “waiting“.
It is a BAD design because this design will block your CPU !!!
I make a practice to explain this situation.

Examples of empty infinite loop:

while(condition_flap == true){

}
for(;;){
}



My test:


busy.c

int main(){
  for(;;){
  }
}


Compile:

$ gcc busy.c -o busy


Execute:

./busy


CPU usage:

$ ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%cpu | head
  PID  PPID CMD                         %MEM %CPU
13775  8550 ./busy                       0.0 99.0
31292 29618 /snap/code/33/usr/share/cod  5.6  1.7
21935 21893 /snap/code/32/usr/share/cod  0.1  0.6
 7264     1 /usr/lib/firefox/firefox -n  2.7  0.4
29654 29618 /snap/code/33/usr/share/cod  0.4  0.4
31331 31292 /snap/code/33/usr/share/cod  0.1  0.4
 7408  7264 /usr/lib/firefox/firefox -c  1.2  0.3
 1224 31316 /usr/lib/jvm/java-8-openjdk  4.8  0.2
 7426  7264 /usr/lib/firefox/firefox -c  1.1  0.2


Assembly:

$ gcc -S busy.c -o busy.s; more busy.s
	.file	"busy.c"
	.text
	.globl	main
	.type	main, @function
main:
.LFB0:
	.cfi_startproc
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset 6, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register 6
.L2:
	jmp	.L2
	.cfi_endproc
.LFE0:
	.size	main, .-main
	.ident	"GCC: (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0"
	.section	.note.GNU-stack,"",@progbits



Conclusion:

DON’T use empty infinity to be your waiting timer.


Ref.
讓CPU瞎忙的忙碌迴圈
Why does an empty infinite loop use my whole CPU?