in reply to Re^3: perl threads causing high cpu usage
in thread perl threads causing high cpu usage

tish15:

When you're using a while(1) loop, be sure to have a sleep in there when your loop has nothing to do--your thread (as you noticed) can chew up quite a bit of CPU while repeatedly looking for work. You should figure out the maximum rate of checking you want, and sleep accordingly. For example, if the source of work is human input, then you might sleep a second at a time. If you're waiting on a disk drive, you might wait 100ms, etc.

I frequently structure task loops something like this:

while (1) { if ($task_1_ready) { do_task_1(...); } elsif ($task_2_ready) { do_task_2(...); } else { sleep($doze_time); } }

This way, the loop does exactly one task per iteration, and sleep only when there are no tasks ready.

...roboticus