我用两种方法检查了一下,但似乎没有成功。
在以下情况下将使用两个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";
}案例1使用Parallel::ForkManager的
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两种情况的产出是相同的。在这些情况下,在实际情况下,当第一个程序完成时,第二个程序将运行。没有真正的平行。如果我在子例程中运行它们,那么并行性就实现了,也就是说,您将能够看到“有限为二”和“有限为一”语句交织在一起。
发布于 2015-01-11 09:15:27
您没有看到并行性,因为您的pro_1和pro_2程序几乎不需要时间。
将一个sleep 1;放入它们的循环中,您将看到它们的输出是交错的。您还将看到您可能希望在您的$pm->wait_all_children循环之后执行foreach my $pro,所以您的主程序将继续执行,直到所有的子程序都完成为止。
https://stackoverflow.com/questions/27885473
复制相似问题