http://qs321.pair.com?node_id=963687

dada has asked for the wisdom of the Perl Monks concerning the following question:

howdy!

I observe this strange behaviour with threads::shared (version 1.32, on Ubuntu's Perl 5.12.4 x86_64-linux-gnu-thread-multi):

use strict; use warnings; use threads qw(yield); use threads::shared; use Data::Dumper; sub test { my %h : shared; for (1..3) { threads->new(sub { my($n) = @_; lock(%h); $h{$n} = rand(); threads->yield(); }, $_)->join(); } return %h; } my %k = test(); print Dumper(\%k);

outside of the sub I get the hash keys, but not the values. like they went out of scope, or something. the output is:

$VAR1 = { '1' => undef, '3' => undef, '2' => undef };

this happens only if I declare the shared hash in a sub and return its content. if I move the hash declaration outside of the sub, everything works:

use strict; use warnings; use threads qw(yield); use threads::shared; use Data::Dumper; my %h : shared; sub test { for (1..3) { threads->new(sub { my($n) = @_; lock(%h); $h{$n} = rand(); threads->yield(); }, $_)->join(); } return %h; } my %k = test(); print Dumper(\%k); # output $VAR1 = { '1' => '0.608570207216875', '3' => '0.0436435554447634', '2' => '0.220397240555943' };

also if I return a reference to the shared hash, everything works:

use strict; use warnings; use threads qw(yield); use threads::shared; use Data::Dumper; sub test { my %h : shared; for (1..3) { threads->new(sub { my($n) = @_; lock(%h); $h{$n} = rand(); threads->yield(); }, $_)->join(); } return \%h; } my $k = test(); print Dumper($k); # output $VAR1 = { '1' => '0.653087966217758', '3' => '0.0419468023619665', '2' => '0.199076903824793' };

the same exact thing happens with arrays too.

is this a bug, or the intended behaviour? and if so, why?

cheers,
Aldo

King of Laziness, Wizard of Impatience, Lord of Hubris