in reply to Re: how to share array of hashes among several threads?
in thread how to share array of hashes among several threads?
You don't need to individually shared the hash elements. You only need to ensure that the hashes are shared before you assign anything to them.
Here's a quick demo:
#! perl -slw use strict; use threads; use threads::shared; sub test { my $href = shift; for( 1 .. 10000 ) { for my $ref ( values %$href ) { for my $value ( values %{ $ref } ) { $value++; } } } } my %hash : shared = map{ my %hash2 : shared = map{ $_ => 0 } 'a' .. 'd'; $_ => \%hash2; } 'A' .. 'D'; threads->create( \&test, \%hash )->detach;; for( 1 .. 5 ) { lock %hash; print "$_ => [ @{[ %{ $hash{ $_ } } ]} ]" for keys %hash; sleep 1; } __END__ P:\test>thr-hash.pl A => [ c 0 a 0 b 0 d 0 ] B => [ c 0 a 0 b 0 d 0 ] C => [ c 0 a 0 b 0 d 0 ] D => [ c 0 a 0 b 0 d 0 ] A => [ c 3447 a 3447 b 3447 d 3447 ] B => [ c 3447 a 3447 b 3447 d 3447 ] C => [ c 3446 a 3446 b 3446 d 3446 ] D => [ c 3446 a 3446 b 3446 d 3446 ] A => [ c 6903 a 6903 b 6903 d 6903 ] B => [ c 6902 a 6902 b 6902 d 6902 ] C => [ c 6902 a 6902 b 6902 d 6902 ] D => [ c 6902 a 6902 b 6902 d 6902 ] A => [ c 10000 a 10000 b 10000 d 10000 ] B => [ c 10000 a 10000 b 10000 d 10000 ] C => [ c 10000 a 10000 b 10000 d 10000 ] D => [ c 10000 a 10000 b 10000 d 10000 ] A => [ c 10000 a 10000 b 10000 d 10000 ] B => [ c 10000 a 10000 b 10000 d 10000 ] C => [ c 10000 a 10000 b 10000 d 10000 ] D => [ c 10000 a 10000 b 10000 d 10000 ]
Far from ideal I agree, but there are other parts that are much more broken than this.
|
|---|