I implemented some code, which runs in a loop:
loop do
..
end
In that loop, I handle keypresses with Curses library. If I press N and entered something, I start a new Thread, which counts time( loop do .. end
again)
The question is, why loop
or while true
causes 100% cpu load on one of the cpu cores? Is the problem actaully in loop?
Is there a way to do infinite loop with lower cpu consumption in ruby?
The full sources available here
UPD - Strace
$ strace -c -p 5480
Process 5480 attached - interrupt to quit
^CProcess 5480 detached
% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
51.52 0.002188 0 142842 ioctl
24.21 0.001028 0 71421 select
14.22 0.000604 0 47614 gettimeofday
10.05 0.000427 0 47614 rt_sigaction
0.00 0.000000 0 25 write
0.00 0.000000 0 16 futex
------ ----------- ----------- --------- --------- ----------------
100.00 0.004247 309532 total
After some thinking and suggestions from user2246674 I managed to resolve the issue. It was not inside the threads, it was the main loop.
I had such code inside the main loop:
c = Curses.getch
unless c.nil?
# input handling
After adding sleep 1 to else
problem was resolved. It does nothing when there's no input from Curses, then checks again in one second, and this stops it from actively polling STDIN
and generating high CPU load