我是perl的新手,所以请原谅我的无知。(我使用的是 Windows 7)
我借用了 echicken 的线程示例脚本,并想用它作为脚本的基础来进行许多系统调用,但我遇到了一个超出我理解的问题。为了说明我看到的问题,我在下面的示例代码中执行了一个简单的 ping 命令。
$nb_process
是允许的数量或同时运行的线程。$nb_compute
作为我们想要运行子例程的次数(即我们将发出 ping 命令的总次数)。
当我将$nb_compute
和设置$nb_process
为彼此相同的值时,它可以完美运行。
但是,当我减少$nb_process
(以限制任何时候运行的线程数)时,一旦定义的线程数$nb_process
开始,它似乎就会锁定。
如果我删除系统调用(ping 命令),它工作正常。
我看到其他系统调用的行为相同(它不仅仅是 ping)。
请问有人可以帮忙吗?我提供了下面的脚本。
#!/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);
}