Perl threads::shared 嵌套数据结构

Perl threads::shared for nested data structure

# thread::shared only allws a single level of shared structure
# needs a explicit hash creation for nested data structures
my %counts     : shared = ();

foreach my $state (%known_states) {
    # COUNTS
    unless (exists $counts{build}) {
        my %cb : shared;
        $counts{build} = \%cb;
    }
    $counts{build}{$state} = 0;

}

现在,我必须像上面那样做一些事情,我必须为每个子级哈希显式创建一个哈希引用。

有更好的方法吗?

P.S。如果我不创建哈希引用,则会收到 "Invalid value for shared scalar" 错误,因为我试图将其用作哈希。

Autovivification 使

$counts{build}{$state} = 0;

表现得像

( $counts{build} //= {} )->{$state} = 0;

为了便于阅读,我们将其分为两行

$counts{build} //= {};
$counts{build}{$state} = 0;

但是就像你说的,我们需要一个共享哈希。

$counts{build} //= &share({});
$counts{build}{$state} = 0;

您可以添加以下内容以确保您不会意外激活未共享的变量:

no autovivification qw( fetch store exists delete );