Perl 如何在并行处理中共享全局变量?
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 ;
我试图使用并行分叉管理器模块访问并行进程上的全局变量。 程序结束时全局变量仍然没有改变。 怎样做才正确呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这不是范围的问题,而是不同流程的问题。 Parallel::ForkManager 使用 fork()(因此得名)。这意味着并行运行的每个版本实际上是一个单独的进程(perl 解释器的单独调用),因此是单独的内存。每个进程中的变量将具有相同的名称,但它们不会指向内存中的同一位置。
如果您想在并行工作线程之间共享变量,那么您需要考虑使用线程(我不推荐)或使用某种 IPC(进程间通信),例如 IPC::Shareable
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
如果程序没有启动并行进程,那么问题将出在第二
行。
但是,由于您正在启动并行进程,因此每个
$a
将位于其内存空间中。这意味着每个$a
都是第一个$a
的副本。因此,最后一个$a
永远不会改变。从一个进程向另一个进程获取值需要一些进程间通信。这可以通过套接字或IPC或其他一些机制来完成。
If the program wasn't starting parallel processes, then the problem would be with the second
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.
我使用的技巧 - 将 fork 进程内的每个变量保存到单独的 txt 文件中,然后在最后(fork 之后)只需遍历所有文件并收集它们(如果不需要,您可以删除文件..
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..