2

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
baldrs
  • 2,132
  • 25
  • 34
  • 3
    Why wouldn't it use 100% of the CPU? There is no reason for it not to try - what if this was actually doing some *really important work*? To avoid eating the CPU, ["sleep"](http://apidock.com/ruby/Kernel/sleep) the thread. A simple `sleep(0)` suffices. – user2246674 Jun 23 '13 at 06:59
  • There's already `sleep 1` as part of the loop logic inside thread – baldrs Jun 23 '13 at 07:05
  • 2
    There is likely a busy loop somewhere (e.g. in one of the spawned threads) that isn't playing nice .. – user2246674 Jun 23 '13 at 07:08
  • I added `strace` output - could it be Curses.getch in main loop? – baldrs Jun 23 '13 at 07:15

1 Answers1

0

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

baldrs
  • 2,132
  • 25
  • 34