views:

510

answers:

3
  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 . end of the program the global variable still remaining same .. how to achieve this ? whether its is possible ?

+1  A: 

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.

Peter Stuifzand
sorry I have edited again
joe
@joe, your edit doesn't change anything. The scope of $a is still the same. Regardless of my or our, the IPC problem remains. Your forked processes are doing their work without saving results anywhere that can be saved after they finish.
EmFi
Your change doesn't matter, because you're forking, all variables are in different processes.
Peter Stuifzand
how to achieve that .. can you help me on it ?
joe
http://perldoc.perl.org/perlipc.html
innaM
thanks Manni :-)
joe
+4  A: 

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

mpeters
A: 

Trick I used - save every variable inside the fork process into separate txt file, than at the end (after fork) just go trough all files and collect them (you can erase files if do not needed..

Vladimir