rajj.nmt4 has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am running below given program and it gets hang after printing array reference if i remove exit keyword. if there are more than one array in queue then it gets hang for last element. but when i put exit then it prints well but i cant access second element from queue in this case,so plz anyone help me y it is happening?

use strict;
use warnings;
use threads;
use Thread::Queue;
use threads::shared;
my @ary :shared =('a','b','c');
my $q = Thread::Queue->new();
$q->enqueue(\@ary);
while(my $ar1 = $q->dequeue()){
print"\narray reference : $ar1\n@$ar1\t";
exit;
}

Replies are listed 'Best First'.
Re: problem in queue implementation
by ikegami (Patriarch) on Oct 14, 2009 at 14:15 UTC

    It's waiting for more stuff to be added to the queue.

    If the queue is preloaded and doesn't change, you could use dequeue_nb.

    use strict; use warnings; use threads; use threads::shared; use Thread::Queue; my @ary :shared = qw( a b c ); my $q = Thread::Queue->new(); $q->enqueue(\@ary); while (my $ar1 = $q->dequeue_nb()) { print "array reference : $ar1\n@$ar1\n"; }

    If data will be added to the queue once the threads have started, use a special value to indicate there is no more data forthcoming. undef would work fine if your queue otherwise contains arrays.

    use strict; use warnings; use threads; use threads::shared; use Thread::Queue; my @ary :shared = qw( a b c ); my $q = Thread::Queue->new(); $q->enqueue(\@ary); $q->enqueue(undef); # One for each consumer. while (my $ar1 = $q->dequeue()) { print "array reference : $ar1\n@$ar1\n"; }
      thanks a lot ikegami....your suggestion worked beautifully..!!

      I am just new to perl so facing all such kind of problems.

      In addition of above similar problem one more doubt i want u to clear...

          if I want to enqueue arrays executed by $sth->fetchrow in a queue for the usage of same queue to later purpose then what should i do means how to get reference of executed rows from result set ??

        Did you want each row to be a different queue item?

        while (my $row = $sth->fetch()) { # Must copy since fetch reuses array. $row = [ @$row ]; $q->enqueue(share($row)); }

        You will be using threads right? Otherwise a queue is simply:

        my @queue; # Put stuff in while (...) { push @queue, ...; } # Take stuff out while (@queue) { my $item = shift(@queue); ... }