Rashmi Dibyajyoti
Rashmi Dibyajyoti

Reputation: 31

How to run two or more Perl programs in parallel -- i.e. with two or more .pl files

I checked with two approaches but non seems to have succeeded.

Two Perl files to be used in the below cases,

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";
}

Case 1 using 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
  }

Output:

$ 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

There is no interleave between the print statements from two different programs.

Case 2 using Perl threads

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 @_");
}

Output:

$ 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

Output for both cases were same. With these cases, in actual when the 1st program finishes the second is run. No real parallelism. If I run them in subroutine, then parallelism is achieved i.e. you would be able to see "finite for two" and "finite for one" statements are interleaved.

Upvotes: 1

Views: 129

Answers (1)

ysth
ysth

Reputation: 98398

You aren't seeing parallelism because your pro_1 and pro_2 programs take almost no time.

Place a sleep 1; into their loops and you will see that their output is interleaved. You will also see that you may want to do $pm->wait_all_children after your foreach my $pro loop so your main program continues until all the children are done.

Upvotes: 4

Related Questions