How can Perl share global variables in parallel processing?

北慕城南 提交于 2019-12-22 10:17:41

问题


  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:


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.




回答2:


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




回答3:


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..



来源:https://stackoverflow.com/questions/1564959/how-can-perl-share-global-variables-in-parallel-processing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!