Dear oshalla,
thank you for your codes, it really helped me to grasp several ideas about threading in Perl. My only addition would be that's in your 1st and 2nd examples you clone the arguments (@array) in the first two cycles, meaning you're creating two threads with the same arguments:
for (1..2) - in the 1st example
and
while ($c) - where $c=2 - in the 2nd example
To fix that I used a new variable to count dispatched threads.
#!/usr/bin/perl
use strict ; use warnings ;
use threads ;
use Thread::Queue ;
my @array = qw(a b c d e f g h);
my @results;
my $finished_queue = new Thread::Queue ;
my $c = 5 ; # Number active at once
my $n = 10 ; # Total number to dispatch
my $m = $n ; # Number to collect
my $d = 0; #count created threads
while ($n) {
while ($m) {
$d++;
my $child = threads->create(\&sub_thread, @array) ;
my $tid;my $childa;
if ($d == $c)
{
$tid = $finished_queue->dequeue() ;
$childa = threads->object($tid) ;
push @results, $childa->join() ;
$d--;
$n--;
}
$m-- ;
}
if (!$m)
{
my $tid = $finished_queue->dequeue() ;
my $childa = threads->object($tid) ;
push @results, $childa->join() ;
$n--;
}
}
sub sub_thread {
my (@temp) = (@_) ;
my $tid = threads->tid() ;
print "child $tid: @temp\n" ;
sleep(rand(2)+2) ;
$finished_queue->enqueue($tid) ;
print "child $tid: finished\n" ;
return "whatever from child $tid" ;
} ;
exit;
It's not elegant, but it works and all I needed was a quick fix.
P.S. It's an old thread, but it was the most useful for me just now, so I'd rather share the solution in this old thread.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.