use strict ; use warnings ;
use threads ;
my @array = qw(a b c d e f g h);
my @children;
my @results;
for (1..5) {
for (1..2) {
push @children, threads->create(\&sub_thread, @array) ;
} ;
while (@children) {
my $child = shift(@children) ;
push @results, $child->join() ;
} ;
} ;
sub sub_thread {
my (@temp) = (@_) ;
my $tid = threads->tid() ;
print "child $tid: @temp\n" ;
sleep (2) ;
return 'whatever' ;
} ;
####
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 = 2 ; # Number active at once
my $n = 10 ; # Total number to dispatch
my $m = $n ; # Number to collect
while ($m) {
while ($n && $c) {
my $child = threads->create(\&sub_thread, @array) ;
$n-- ;
$c-- ;
} ;
my $tid = $finished_queue->dequeue() ;
my $child = threads->object($tid) ;
push @results, $child->join() ;
$m-- ;
$c++ ;
} ;
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" ;
} ;
####
use strict ; use warnings ;
use threads ;
use Thread::Queue ;
my @array = qw(a b c d e f g h);
my @results;
my $param_queue = new Thread::Queue ;
my $result_queue = new Thread::Queue ;
my $c = 2 ; # concurrent threads
my $n = 10 ; # amount of work
my @children ;
for (1..$c) { # Start the threads
push @children, threads->create(\&sub_thread) ;
} ;
for (1..$n) { # Dispatch the work
$param_queue->enqueue([@array]) ;
} ;
for (1..$n) { # Collect the results
push @results, $result_queue->dequeue() ;
} ;
$param_queue->enqueue((undef) x $c) ; # Signal the threads to stop
foreach (@children) { # Collect the terminated threads
$_->join() ;
} ;
sub sub_thread {
my $task = 0 ;
my $tid = threads->tid() ;
print "child $tid: started" ;
while (my $p = $param_queue->dequeue()) {
$task++ ;
my @temp = @$p ;
print "child $tid/$task: @temp\n" ;
sleep(rand(2)+2) ;
$result_queue->enqueue("whatever from child $tid/$task") ;
print "child $tid/$task: done\n" ;
} ;
print "child $tid: terminated\n" ;
} ;