| 1 | |||
| 2 | package Thread::Shared::Hash; | ||
| 3 | |||
| 4 | use threads::shared '1.02', qw/ share is_shared /; | ||
| 5 | |||
| 6 | use Thread::Shared; | ||
| 7 | use strict; | ||
| 8 | |||
| 9 | sub TIEHASH | ||
| 10 | { | ||
| 11 | my $class = shift; | ||
| 12 | my $value = shift; | ||
| 13 | my $bless = shift; | ||
| 14 | |||
| 15 | if ( not defined $value or not is_shared $value ) | ||
| 16 | { | ||
| 17 | $value = &share({}); | ||
| 18 | } | ||
| 19 | |||
| 20 | if ( $bless and $bless ne 'HASH' ) | ||
| 21 | { | ||
| 22 | bless $value, $bless; | ||
| 23 | } | ||
| 24 | |||
| 25 | my $self = { | ||
| 26 | hash => $value | ||
| 27 | }; | ||
| 28 | |||
| 29 | bless $self, $class; | ||
| 30 | return $self; | ||
| 31 | } | ||
| 32 | |||
| 33 | sub get_shared_value { return shift->{hash}; } | ||
| 34 | |||
| 35 | sub FETCH | ||
| 36 | { | ||
| 37 | my ($self, $key) = @_; | ||
| 38 | |||
| 39 | my $value = $self->{hash}->{$key}; | ||
| 40 | if ( ref($value) ) | ||
| 41 | { | ||
| 42 | $value = Thread::Shared::wrap($value); | ||
| 43 | } | ||
| 44 | return $value; | ||
| 45 | } | ||
| 46 | |||
| 47 | sub STORE | ||
| 48 | { | ||
| 49 | my ($self, $key, $value) = @_; | ||
| 50 | $self->{hash}->{$key} = Thread::Shared::make_sharable($value); | ||
| 51 | } | ||
| 52 | |||
| 53 | sub DELETE | ||
| 54 | { | ||
| 55 | my ($self, $key) = @_; | ||
| 56 | delete $self->{hash}->{$key}; | ||
| 57 | } | ||
| 58 | |||
| 59 | sub CLEAR | ||
| 60 | { | ||
| 61 | my $self = shift; | ||
| 62 | |||
| 63 | foreach my $key ( keys %{$self->{hash}} ) | ||
| 64 | { | ||
| 65 | delete $self->{hash}->{$key}; | ||
| 66 | } | ||
| 67 | } | ||
| 68 | |||
| 69 | sub EXISTS | ||
| 70 | { | ||
| 71 | my ($self, $key) = shift; | ||
| 72 | return exists $self->{hash}->{$key}; | ||
| 73 | } | ||
| 74 | |||
| 75 | sub FIRSTKEY | ||
| 76 | { | ||
| 77 | my $self = shift; | ||
| 78 | # reset the each() iterator | ||
| 79 | my $a = keys %{$self->{hash}}; | ||
| 80 | return each %{$self->{hash}}; | ||
| 81 | } | ||
| 82 | |||
| 83 | sub NEXTKEY | ||
| 84 | { | ||
| 85 | my $self = shift; | ||
| 86 | return each %{$self->{hash}}; | ||
| 87 | } | ||
| 88 | |||
| 89 | sub SCALAR | ||
| 90 | { | ||
| 91 | my $self = shift; | ||
| 92 | return scalar %{$self->{hash}}; | ||
| 93 | } | ||
| 94 | |||
| 95 | sub UNTIE | ||
| 96 | { | ||
| 97 | my $self = shift; | ||
| 98 | # TODO: me! | ||
| 99 | } | ||
| 100 | |||
| 101 | sub DESTROY | ||
| 102 | { | ||
| 103 | my $self = shift; | ||
| 104 | # TODO: me! | ||
| 105 | } | ||
| 106 | |||
| 107 | 1; | ||
| 108 |