Skip to content

Commit

Permalink
Merge pull request miyagawa#1 from chansen/master
Browse files Browse the repository at this point in the history
Thread safety
  • Loading branch information
miyagawa committed Jun 15, 2011
2 parents 0a3863e + b7c690d commit 35aa1b8
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/Hash/MultiValue.pm
Expand Up @@ -9,6 +9,23 @@ use Scalar::Util qw(refaddr);

my %keys;
my %values;
my %registry;

BEGIN {
require Config;
my $needs_registry = ($^O eq 'Win32' || $Config::Config{useithreads});
if ($needs_registry) {
*CLONE = sub {
foreach my $oldaddr (keys %registry) {
my $this = refaddr $registry{$oldaddr};
$keys{$this} = delete $keys{$oldaddr};
$values{$this} = delete $values{$oldaddr};
Scalar::Util::weaken($registry{$this} = delete $registry{$oldaddr});
}
};
}
*NEEDS_REGISTRY = sub () { $needs_registry };
}

if (defined &UNIVERSAL::ref::import) {
UNIVERSAL::ref->import;
Expand All @@ -22,6 +39,9 @@ sub create {
my $this = refaddr $self;
$keys{$this} = [];
$values{$this} = [];
if (NEEDS_REGISTRY) {
Scalar::Util::weaken($registry{$this} = $self);
}
$self;
}

Expand All @@ -43,6 +63,9 @@ sub DESTROY {
my $this = refaddr shift;
delete $keys{$this};
delete $values{$this};
if (NEEDS_REGISTRY) {
delete $registry{$this};
}
}

sub get {
Expand Down
25 changes: 25 additions & 0 deletions t/threads.t
@@ -0,0 +1,25 @@
use strict;
use Config;
use Test::More;
use Hash::MultiValue;

BEGIN {
plan skip_all => "perl interpreter is not compiled with ithreads"
unless $Config{useithreads};

require threads;
}

plan tests => 2;

my $h = Hash::MultiValue->new(foo => 'bar');
my @exp = ('bar');

is_deeply([$h->get_all('foo')], \@exp, 'got expected results');

my @got = threads->create(sub {
$h->get_all('foo');
})->join;

is_deeply(\@got, \@exp, 'got expected results in cloned interpreter');

0 comments on commit 35aa1b8

Please sign in to comment.