如何并行运行两个或多个Perl程序 - 即使用两个或更多.pl文件

时间:2015-01-11 09:01:17

标签: perl

我检查了两种方法,但似乎没有成功。

在以下情况下使用两个Perl文件,

pro_1.pl

use strict;

for (1..10) {
    print "finite for one\n";
}

pro_2.pl

use strict;

for (1..10){
    print "finite for two\n";
}
使用Parallel::ForkManager

案例1

use strict;
use warnings;

use Parallel::ForkManager;

my $pm = new Parallel::ForkManager(2);
my @all_pro = ("pro_1.pl", "pro_2.pl");

foreach my $pro (@all_pro) {
    # Forks and returns the pid for the child:
    my $pid = $pm->start and next; 
    system ("perl $pro");

    $pm->finish; # Terminates the child process
  }

输出:

$ finite for one
finite for one
finite for one
finite for one
finite for one
finite for one
finite for one
finite for one
finite for one
finite for one
finite for two
finite for two
finite for two
finite for two
finite for two
finite for two
finite for two
finite for two
finite for two
finite for two

来自两个不同程序的打印语句之间没有交错。

使用Perl线程

案例2

use threads;

my $child_thread = threads->new(\&my_function1, "pro_1.pl");
my $child_thread2 = threads->new(\&my_function2, "pro_2.pl");
# ...

my $this_thread = threads->self;
print "Main thread: $this_thread\n";
my $tid = $this_thread->tid;
print "TID of current thread: $tid\n";

my @threads = threads->list;
print "All threads: @threads\n";

foreach my $thr (@threads) {
    my $thr_pid = $thr->tid;
    print "Child Thread PID: $thr_pid\n";
    $thr->join;
}

sub my_function1 {
    system ("perl @_");
}

sub my_function2 {
    system ("perl @_");
}

输出:

$ finite for one
finite for one
finite for one
finite for one
finite for one
finite for one
finite for one
finite for one
finite for one
finite for one
finite for two
finite for two
finite for two
finite for two
finite for two
finite for two
finite for two
finite for two
finite for two
finite for two

两种情况的输出相同。在这些情况下,实际上当第一个程序完成时,第二个程序运行。没有真正的并行性。如果我在子程序中运行它们,那么就可以实现并行性,即你可以看到"有限的两个"并且"有限的一个"语句是交错的。

1 个答案:

答案 0 :(得分:4)

您没有看到并行性,因为您的pro_1和pro_2计划几乎没有时间。

sleep 1;放入其循环中,您将看到它们的输出是交错的。 您还会看到在$pm->wait_all_children循环后您可能想要foreach my $pro,所以您的主程序会一直持续到所有孩子都完成为止。