How can Perl share global variables in parallel processing?

fork, parallel-processing, perl

Solution

If the program wasn't starting parallel processes, then the problem would be with the second

my $a = 0;

line.

However, because you are starting parallel processes, each `$a` will be in it's memory space. That means each `$a` is a copy of the first `$a`. And the last first `$a` will never change, because of that.

Getting a value from one process to another process takes a bit of interprocess communication. This can be done with sockets or IPC, or some other mechanism.

Problem

``` use Parallel::ForkManager; use LWP::Simple; my $pm=new Parallel::ForkManager(10); our $a =0; @LINK=( 10,203, 20, 20 ,20 ,10 ,101 ,01 ,10 ) ; for my $link (@LINK) { $pm->start and next; my $lo = ($link * 120.22 )*12121.2121212121212121*( 12121212.1212121+ $link); $a = $a+ $lo ; print $a."\n" ; $pm->finish; }; print $a ; ``` I was trying to access the global variable on parallel process using parallel fork manager module. At the end of the program the global variable is still unchanged. How to do it correctly?

Original source