Reputation: 159
The question is, i have one array and one hash which i need to pass to a subroutine called in a new thread, how to do that as it seems that references passed in the arguments are somehow not working!
here is an example code snippet:
while(1){
&funct1;
foreach my $thr (threads->list(threads::joinable)){
print "joinable: $thr->tid()\n";
handle threads ...
}
}
sub funct1{
@array= ... #create new array;
%hash= ... #create new hash;
my $t=threads->create(\&funct2,\@array,\%hash);
}
sub funct2{
($arrayRef,$hashref)=@_;
operate on @$arrayref;
operate on %$hashref;
}
In the above code snippet, "funct2" is not getting the references or not creating separate copies of the hash or array. I tried to copy the array/hash to new ones in funct2, didn't work! i can't use shared because funct1 creates new hash/array in every iteration of the loop.
Any suggestion?
Upvotes: 0
Views: 804
Reputation: 159
Figured out a bug in my code, somehow got missed.
Anyways the best way is to "use Thread::Queue". So the modified code snippet will be like this.
my $thrq = Thread::Queue->new();
while(1){
&funct1;
foreach my $thr (threads->list(threads::joinable)){
print "joinable: $thr->tid()\n";
handle threads ...
}
}
sub funct1{
@array= ... #create new array;
%hash= ... #create new hash;
$thrq->enqueue(\@array,\%hash);
my $t=threads->create(\&funct2);
}
sub funct2{
($arrayRef,$hashref)=$thrq->dequeue(2);
operate on @$arrayref;
operate on %$hashref;
}
Upvotes: 2
Reputation: 63
You need to pass the hash and an array as arguments to the function func2
funct2(\@array,\%hash);
Upvotes: 1