multithreading - 在Perl中使用多线程时,应如何更新哈希哈希?

标签 multithreading perl hash threadpool

我一直在花最后几个小时试图解决这个问题,现在我真的很困惑。

这是我的任务大纲。我应该编写一个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/

相关文章:

hash - 如何按出现的顺序获取哈希键

java - HashMap哈希函数-二元运算符

c++ - vector.push_back()在推送线程时(在编译过程中)产生已删除的函数错误

java - Java 类中的同步方法不遵守互斥量

linux - mkdir() 怎么会成功却设置了错误的权限呢?

regex - 正则表达式中的模式匹配 (Perl)

perl - 无法将 perl 哈希返回到模板工具包文件中

perl - 可以在 https 上的 WWW::Mechanize 中使用超时吗?

java - 尽管可读,选择器仍不活动

c++ - 专门的哈希表c++