【发布时间】:2013-06-03 13:05:03
【问题描述】:
以下代码运行 2 个孩子,他们将等待 10 秒并终止。父级坐在一个循环中,等待子级终止:
#!/usr/bin/perl
use strict;
use warnings;
use POSIX ":sys_wait_h";
sub func
# {{{
{
my $i = shift;
print "$i started\n";
$| = 1;
sleep(10);
print "$i finished\n";
}
# }}}
my $n = 2;
my @children_pids;
for (my $i = 0; $i < $n; $i++) {
if ((my $pid = fork()) == 0) {
func($i);
exit(0);
} else {
$children_pids[$i] = $pid;
}
}
my $stillWaiting;
do {
$stillWaiting = 0;
for (my $i = 0; $i < $n; ++$i) {
if ($children_pids[$i] > 0)
{
if (waitpid($children_pids[$i], WNOHANG) != 0) {
# Child is done
print "child done\n";
$children_pids[$i] = 0;
} else {
# Still waiting on this child
#print "waiting\n";
$stillWaiting = 1;
}
}
#Give up timeslice and prevent hard loop: this may not work on all flavors of Unix
sleep(0);
}
} while ($stillWaiting);
print "parent finished\n";
代码基于此答案:Multiple fork() Concurrency
它工作正常,但父循环正在占用处理器时间。 top 命令给出了这个:
Here 答案是:
作为额外的奖励,循环将在
waitpid而阻塞 孩子们正在运行,因此您在等待时不需要繁忙的循环。
但对我来说它不会阻塞。怎么了?
【问题讨论】:
标签: perl optimization waitpid