Perl: Threading with shared multi-dimensional hash

后端 未结 1 534
慢半拍i
慢半拍i 2021-01-02 12:55

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

相关标签:
1条回答
  • 2021-01-02 13:06

    Autovivification is your friend most of the time, but you have to be careful about it with shared values. Modify handlethread:

    sub handlethread{
      # ...
      unless (exists $FLUobject2param{$objectID} &&
              exists $FLUobject2param{$objectID}{$paramID})
      {
          $dbh->getObject2Param($objectID,$paramID);
          $FLUobject2param{$objectID} = &share({});
          $FLUobject2param{$objectID}{$paramID} = 1;
      }
    }
    

    This is due do a documented limitation:

    Shared variables can only store scalars, refs of shared variables, or refs of shared data …

    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.

    0 讨论(0)
提交回复
热议问题