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
Aldo
King of Laziness, Wizard of Impatience, Lord of Hubris
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: bug in threads::shared or is it just me?
by kennethk (Abbot) on Apr 05, 2012 at 14:51 UTC | |
Re: bug in threads::shared or is it just me?
by ikegami (Patriarch) on Apr 05, 2012 at 20:58 UTC | |
by dada (Chaplain) on Apr 10, 2012 at 15:53 UTC | |
Re: bug in threads::shared or is it just me?
by BrowserUk (Patriarch) on Apr 05, 2012 at 16:13 UTC | |
Re: bug in threads::shared or is it just me?
by dave_the_m (Monsignor) on Apr 06, 2012 at 10:33 UTC | |
Re: bug in threads::shared or is it just me?
by choroba (Cardinal) on Apr 05, 2012 at 15:50 UTC | |
Re: bug in threads::shared or is it just me?
by zentara (Archbishop) on Apr 05, 2012 at 16:46 UTC | |
by dada (Chaplain) on Apr 10, 2012 at 15:36 UTC |
Back to
Seekers of Perl Wisdom