0

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?

1
  • 1
    Include use strict; and use warnings; in EVERY perl script. This is the #1 thing you can do and should to do to make non-buggy programs. Commented Aug 12, 2014 at 21:00

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to pass the hash and an array as arguments to the function func2

funct2(\@array,\%hash);

1 Comment

yes, this will also work, so does my code snippet. i was doing a stupid mistake in passing the ref. But best way is to use thread queue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.