我一直在花最后几个小时试图解决这个问题,现在我真的很困惑。
这是我的任务大纲。我应该编写一个Perl子例程,该例程获取对哈希哈希的引用。
我还有另一个子(helper
),它获得一个内部哈希,并进行一些处理,包括添加键。
sub helper {
$href = shift;
$href->{NEW_KEY}=1;
}
由于每个内部散列都独立于其他内部散列,因此我想使用多线程调用
helper
。我使用的
Thread::Pool::Simple
几乎没有任何文档。我的Perl版本不支持 Thread::Pool
。所以我有这样的事情:
sub my_sub {
$hohref = shift;
# create thread pool
my $pool = Thread::Pool::Simple->new(
do => [ \&helper ]
);
# submit jobs
foreach my $hashref ( values %{$hohref} ) {
$pool->add( $hashref );
}
# wait for all threads to end
$pool->join();
}
关键是我希望散列的主要散列能够反射(reflect)对内部散列所做的所有更改。
my_sub
获取对$hohref
的未共享引用,因此我尝试在my_sub
主体中创建共享副本:my $shared_hohref = shared_clone $hohref;
使用它并返回它,但是内部哈希没有更新。
当我使用完全相同的代码,而只是用一个简单的循环替换所有线程池块时
foreach my $hashref ( values %{$hohref} ) {
helper( $hashref );
}
然后一切正常。
您的帮助将不胜感激。
更新
请参见以下可运行示例:
use strict;
use warnings;
use threads;
use threads::shared;
use Thread::Pool::Simple;
use 5.010;
use Data::Dumper;
sub helper {
say "helper starts";
my $href = shift;
say "href is $href";
$href->{NEW_KEY} = 1;
say "helper ends with $href";
}
sub my_sub {
my $hohref = shift;
my $shared_hohref = shared_clone $hohref;
my $pool = Thread::Pool::Simple->new( do => [\&helper] );
# submit jobs
foreach my $hashref ( values %{$shared_hohref} ) {
say "adding to pool: $hashref";
$pool->add($hashref);
}
# wait for all threads to end
$pool->join();
return $shared_hohref;
}
my $hoh = {
A => { NAME => "a" },
B => { NAME => "bb" }
};
say "1\t", Dumper $hoh;
my $updated_hoh = my_sub($hoh);
say "2\t", Dumper $updated_hoh;
“帮助程序启动”,仅此而已...发生了什么事?
最佳答案
关于multithreading - 在Perl中使用多线程时,应如何更新哈希哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3749194/