Perl:具有共享多维哈希的线程
我正在尝试在多个线程上共享多维哈希。 这个哈希保存了2个连接的密钥对,我需要知道它们是否已经连接,如果没有,我需要连接它们,如果没有,则不需要去数据库。
use threads;
use threads::shared;
my %FLUobject2param : shared = ();
#Start a new thread for every available processor
for (my $i=0;$i<$PROCESSORS;$i++) {
threads->new(\&handlethread);
}
#Catch if these threads end
foreach my $onthr (threads->list()) {
$onthr->join();
}
sub handlethread{
...
if(not defined $FLUobject2param{$objectID}{$paramID}){
$dbh->getObject2Param($objectID,$paramID);
$FLUobject2param{$objectID}{$paramID} = 1;
}
}
我不断收到错误 共享标量无效值
if(not Defined $FLUobject2param{$objectID}{$paramID}){
这显然与perl 的threads::shared 只允许您共享单个级别的共享结构有关。
我仍然如何检查该组合是否已在多个线程上使用?
I am trying to share a multi-dimensional hash over multiple threads.
This hash holds 2 connected key-pairs, I need to know if they are already connected, if they are not, I need to connect them, if not, there is no need to go to the database.
use threads;
use threads::shared;
my %FLUobject2param : shared = ();
#Start a new thread for every available processor
for (my $i=0;$i<$PROCESSORS;$i++) {
threads->new(\&handlethread);
}
#Catch if these threads end
foreach my $onthr (threads->list()) {
$onthr->join();
}
sub handlethread{
...
if(not defined $FLUobject2param{$objectID}{$paramID}){
$dbh->getObject2Param($objectID,$paramID);
$FLUobject2param{$objectID}{$paramID} = 1;
}
}
I keep getting the error Invalid value for shared scalar
on the lineif(not defined $FLUobject2param{$objectID}{$paramID}){
This apparently has to do with perl's threads::shared only allowing you to share a single level of shared structure.
How would I still be able to check if this combination is already used over multiple threads ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
大多数时候,自动生存是你的朋友,但你必须以共同的价值观来小心它。修改
handlethread
:这是由于记录的限制< /a>:
上面的代码单独检查哈希键以避免自动生存,这将在
$FLUobject2param{$objectID} 如果尚不存在。
在条件语句中,我们首先构建适当的脚手架,然后分配值。同样,自动生存通常会为您处理这个问题,但共享迫使我们更加深思熟虑。
Autovivification is your friend most of the time, but you have to be careful about it with shared values. Modify
handlethread
:This is due do a documented limitation:
The code above checks the hash keys separately to avoid autovivification, which will plant an unshared empty hash reference in
$FLUobject2param{$objectID}
if it doesn't exist yet.Inside the conditional, we first build the appropriate scaffolding and then assign the value. Again, autovivification ordinarily handles this for you, but sharing forces us to be more deliberate.