Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;

}

Right now, I have to do something like the above where I have to explicitly create a hash reference for each sub-level hash.

Is there a better way of doing it?

P.S. if I don't create a hash ref then I get an "Invalid value for shared scalar" error since I am trying to use it as a hash.

like image 743
ealeon Avatar asked Feb 17 '15 17:02

ealeon


1 Answers

Autovivification makes

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

behave like

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

For readability, let's make it two lines

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

But like you said, we need a shared hash.

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

You could add the following to make sure you don't accidentally vivify an unshared variable:

no autovivification qw( fetch store exists delete );
like image 172
ikegami Avatar answered Oct 20 '22 18:10

ikegami