I am a newbie to perl, so please excuse my ignorance. (I'm using windows 7)
I have borrowed echicken's threads example script and wanted to use it as a basis for a script to make a number of system calls, but I have run into an issue which is beyond my understanding. To illustrate the issue I am seeing, I am doing a simple ping command in the example code below.
$nb_processis the number or simultaneous running threads allowed.$nb_computeas the number of times we want to run the sub routine (i.e the total number of time we will issue the ping command).
When I set $nb_compute and $nb_process to be same value as each other, it works perfectly.
However when I reduce $nb_process (to restrict the number of running threads at any one time), it seems to lock once the number of threads defined in $nb_process have started.
It works fine if I remove the system call (ping command).
I see the same behaviour for other system calls (it'd not just ping).
Please could someone help? I have provided the script below.
#!/opt/local/bin/perl -w
use threads;
use strict;
use warnings;
my @a = ();
my @b = ();
sub sleeping_sub ( $ $ $ );
print "Starting main program\n";
my $nb_process = 3;
my $nb_compute = 6;
my $i=0;
my @running = ();
my @Threads;
while (scalar @Threads < $nb_compute) {
@running = threads->list(threads::running);
print "LOOP $i\n";
print " - BEGIN LOOP >> NB running threads = ".(scalar @running)."\n";
if (scalar @running < $nb_process) {
my $thread = threads->new( sub { sleeping_sub($i, \@a, \@b) });
push (@Threads, $thread);
my $tid = $thread->tid;
print " - starting thread $tid\n";
}
@running = threads->list(threads::running);
print " - AFTER STARTING >> NB running Threads = ".(scalar @running)."\n";
foreach my $thr (@Threads) {
if ($thr->is_running()) {
my $tid = $thr->tid;
print " - Thread $tid running\n";
}
elsif ($thr->is_joinable()) {
my $tid = $thr->tid;
$thr->join;
print " - Results for thread $tid:\n";
print " - Thread $tid has been joined\n";
}
}
@running = threads->list(threads::running);
print " - END LOOP >> NB Threads = ".(scalar @running)."\n";
$i++;
}
print "\nJOINING pending threads\n";
while (scalar @running != 0) {
foreach my $thr (@Threads) {
$thr->join if ($thr->is_joinable());
}
@running = threads->list(threads::running);
}
print "NB started threads = ".(scalar @Threads)."\n";
print "End of main program\n";
sub sleeping_sub ( $ $ $ ) {
my @res2 = `ping 136.13.221.34`;
print "\n@res2";
sleep(3);
}