【发布时间】:2013-08-18 13:11:23
【问题描述】:
我是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);
}
【问题讨论】:
-
我已经运行了你的脚本,我看到“LOOP 1”由于某种原因永远不会被打印出来。我还没弄清楚为什么 atm :(
标签: multithreading perl system-calls