Subject: | locking a value from a hash |
I am trying to have a shared hash, with multiple threads accessing it,
I seems that I a can lock the hash itself but none of its contents
my %hash :shared;
my $a = 'key';
$hash{$a} = 1;
lock %hash; # work !
print '$hash{$a} is ', is_shared($hash{$a})?'shared':'NOT SHARED',"\n";
lock $hash{$a}; # runtime error !
1;
is there a work arround this ?
Thanks
+Michel
(see attached code for a more complete exemple)
Subject: | mt.pl |
#!perl
use threads;
use threads::shared;
my %seen :shared = ();
my %hash :shared;
my $a = 'key';
$hash{$a} = 1;
lock %hash; # work !
print '$hash{$a} is ', is_shared($hash{$a})?'shared':'NOT SHARED',"\n";
lock $hash{$a}; # runtime error !
exit;
for $t (0 .. 9) {
my $th = threads->create(\&count);
}
sleep 1;
for my $th (threads->list(0)) {
printf 'th:%2d : found %d duplicates'."\n", $th->tid,$th->join;
}
use YAML;
printf "seen: %s.\n",YAML::Dump(\%seen);
sub count {
my $total = 0;
for (0 .. 99) {
my $a = int rand(200);
if (exists $seen{$a}) {
lock $seen{$a}; # <--- ERROR : lock can only be used on shared values
$seen{$a}++;
threads->yield() if (rand (1) > 0.5);
$total++;
} else {
lock %seen;
threads->yield() if (rand (1) > 0.5);
$seen{$a} = 1;
}
}
return $total;
}