简体   繁体   中英

Pass an array and a hash to a subroutine for multiple threads in Perl

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?

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;
}

您需要将哈希和数组作为参数传递给函数func2

funct2(\@array,\%hash);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM