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


In reply to Re^4: perl threads causing high cpu usage by roboticus
in thread perl threads causing high cpu usage by tish15

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.