在Perl中使用多线程进行并行运算

使用Parallel::ForkManager模块可以很方便得在for、foreach等循环中使用多线程进行并行运算,示例如下:

#!/usr/bin/perl
 
use warnings;
use strict;
use Parallel::ForkManager;
 
my $max_process = 5;
 
my $pm = new Parallel::ForkManager($max_process);
foreach ( 1 .. 9 ) {
$pm-》start and next;
print "$_ start:t";
system "date +%T";
sleep($_);
print "$_ stop:t";
system "date +%T";
$pm-》finish;
}
$pm-》wait_all_children;
print "All finish:t";
system "date +%T";