Reputation: 715
I want to keep the hash with array reference in the thread. I'm getting the following error.
The following code is executable as it is. You will see the error message like
Invalid value for shared scalar at ./thread1.pl line 25.
#!/usr/bin/env perl
use v5.18;
use strict;
use warnings;
use Data::Dumper;
use threads;
use threads::shared;
my %myhash :shared;
my $stop_myfunc :shared = 0;
my $count = 0;
my $listref;
my @a = ('1','2');
@$listref = @a;
%myhash = (
rootdir => "<path>/junk/perl",
listref => $listref,
);
sub my2ndfunc {
print "I am in the thread\n";
$count++;
$myhash{$count} = 0;
}
sub myfunc {
while ($stop_myfunc == 0) {
sleep(1);
my2ndfunc();
}
}
my $my_thread = 0;
$stop_myfunc = 0;
$my_thread = threads->create('myfunc');
$myhash{'test'} = 0;
sleep(3);
print Dumper \%myhash;
$stop_myfunc = 1;
$my_thread->join();
1;
I tried array ref declared as :shared
, but not helped.
Is there something I am missing here. I am not able to think of any other alternative here. Any help is appreciated.
Upvotes: 2
Views: 135
Reputation: 1832
From threads:shared:
Shared variables can only store scalars, refs of shared variables, or refs of shared data
You have to use shared_clone
to use any other data type.
my @a = ('1','2');
my $listref = shared_clone(\@a);
%myhash = (
rootdir => "<path>/junk/perl",
listref => $listref,
);
Since you presumably won't need the original copy of the data structure you're sharing, it's better to just define it within a shared_clone
statement in the first place.
my %myhash :shared = (
rootdir => "<path>/junk/perl",
listref => shared_clone( ['1', '2'] ),
inventory => shared_clone( { additional => [qw/pylons doritos mountain_dew/] ),
);
Upvotes: 3