首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何并行运行两个或多个Perl程序??即使用两个或多个.pl文件。

如何并行运行两个或多个Perl程序??即使用两个或多个.pl文件。
EN

Stack Overflow用户
提问于 2015-01-11 09:01:17
回答 1查看 102关注 0票数 1

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

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

pro_1.pl

代码语言:javascript
复制
use strict;

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

pro_2.pl

代码语言:javascript
复制
use strict;

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

案例1使用Parallel::ForkManager

代码语言:javascript
复制
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
  }

输出:

代码语言:javascript
复制
$ 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

代码语言:javascript
复制
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 @_");
}

输出:

代码语言:javascript
复制
$ 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

两种情况的产出是相同的。在这些情况下,在实际情况下,当第一个程序完成时,第二个程序将运行。没有真正的平行。如果我在子例程中运行它们,那么并行性就实现了,也就是说,您将能够看到“有限为二”和“有限为一”语句交织在一起。

EN

回答 1

Stack Overflow用户

发布于 2015-01-11 09:15:27

您没有看到并行性,因为您的pro_1和pro_2程序几乎不需要时间。

将一个sleep 1;放入它们的循环中,您将看到它们的输出是交错的。您还将看到您可能希望在您的$pm->wait_all_children循环之后执行foreach my $pro,所以您的主程序将继续执行,直到所有的子程序都完成为止。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27885473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档