我有一些代码,我希望输出为 1 和 6,但它却输出 1 ad infinitum。
use v5.10;
use Parallel::Prefork;
use List::MoreUtils qw( natatime );
use POSIX qw( ceil );
my $forks = 2;
my @numbers = (1..10);
my $chunk_size = ceil((scalar @numbers) / $forks);
my $game_iterator = natatime $chunk_size, @numbers;
my $fm = Parallel::Prefork->new({ max_workers => $forks });
while ($fm->signal_received ne 'TERM') {
while( my @numbers_chunk = $game_iterator->() ) {
$fm->start(sub {
say $numbers_chunk[0];
});
}
}
$fm->wait_all_children;
# bash-4.2$ perl test.pl
# 1
# 1
# 1
# 1
# 1
# etc
上面的脚本将一个包含 10 个数字的数组拆分为 $fork 个数组 (2),并且应该将每个数组传递给它们自己的 fork 进行处理。
如果您替换$fm->start(sub {say $numbers_chunk[0];});
为仅say $numbers_chunk[0];
显示正确的结果。Parallel::ForkManager 还输出正确的结果(按照概要),所以我不知道我做错了什么,或者这是否是模块中的错误。
输出预期结果的 ForkManager 脚本:
use v5.10;
use Parallel::ForkManager;
use List::MoreUtils qw( natatime );
use POSIX qw( ceil );
my $forks = 2;
my @numbers = (1..10);
my $chunk_size = ceil((scalar @numbers) / $forks);
my $game_iterator = natatime $chunk_size, @numbers;
my $fm = Parallel::ForkManager->new($forks );
while( my @numbers_chunk = $game_iterator->() ) {
$fm->start and next;
say $numbers_chunk[0];
$fm->finish;
}
$fm->wait_all_children;
# bash-4.2$ perl test.pl
# 1
# 6