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开发者_Python百科 ,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 ?
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
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.
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..
精彩评论