Ruby infinite loop causes 100% cpu load

不问归期 提交于 2019-12-08 07:59:41

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/17258408/ruby-infinite-loop-causes-100-cpu-load

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!