Technically, you cannot set a thread limit with semaphores this way. It does work in practice, but there's no real guarantee that a thread, or all threads, aren't preempted right after the $sem->up().

Second point, do not detach a thread if you need to wait upon it. Grab its end result (return value) with a join(), instead.

You may not want to create too many threads (especially with fine-grained jobs). An alternative that might be suitable is to arrange for a conveyor belt with N workers. Use Thread::Queue for that. Here's a simple, if overly recursive, example:

use threads; use Thread::Queue; my $WQ = Thread::Queue->new('unit001' .. 'unit123'); sub qrun { map { $_ ? (worker($_), qrun()) : () } $WQ->dequeue_nb; } sub worker { warn "Work $_"; select(undef, undef, undef, rand 3); # sleep some return "$_!"; } print for map { $_->join } map { threads->new(\&qrun) } 1 .. 15;


In reply to Re: Threading and join/termination question by oiskuu
in thread Threading and join/termination question by cormanaz

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.