Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Perl share global variables in parallel processing?

  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?

like image 802
joe Avatar asked Dec 03 '25 00:12

joe


1 Answers

It's not a matter of scoping, it's a matter of different processes. Parallel::ForkManager uses fork() (hence the name). This means that each version running in parallel is actually a separate process (a separate invocation of the perl interpreter) and thus separate memory. The variables will have the same name in each process, but they won't point to the same place in memory.

If you want to share variables across parallel workers, then you'll need to look at either using threads (which I wouldn't recommend) or using some sort of IPC (inter-process communication) like IPC::Shareable

like image 199
mpeters Avatar answered Dec 05 '25 15:12

mpeters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!