mrd has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I'm having some trouble with Thread::Queue::Any. I managed to reduce the problem to the following :

############# code starts here ############# use strict; use threads; use threads::shared; use Thread::Queue::Any; our $| = 1; my $QUEUE : shared; my $TERMINATE : shared = 0; my $THREAD; sub TimeThread { while (!$TERMINATE) { sleep 1; $QUEUE->enqueue(scalar(localtime())); } } $SIG{TERM} = sub { $TERMINATE=1; $THREAD->join; exit; }; $QUEUE=Thread::Queue::Any->new; $THREAD=threads->new(\&TimeThread); while (1) { sleep 1; if ($QUEUE->pending) { ######## This is really weird! ######## my $time = $QUEUE->dequeue; print $time; ### NOT OK #print $QUEUE->dequeue; ### OK. } } ############# code ends here ##################
If I run the code as is, the output reads:

1111 ...

and so on.

Now if I replace line no. 37 with:

print $QUEUE->dequeue;
I get the expected result, namely nicely formatted localtime()s.

What am I doing wrong ?

Thank you,

R.

PS: My environment is : WinXP Home Edition; ActivePerl 5.8.3 Build 809; Thread::Queue::Any 0.06

Replies are listed 'Best First'.
Re: Thread::Queue::Any->dequeue trouble
by chromatic (Archbishop) on Aug 25, 2005 at 21:49 UTC

    Call $QUEUE->dequeue() in list context:

    my ($time) = $QUEUE->dequeue()
      Thanks. That works.

      But then the docs are misleading. Quote from perldoc Thread::Queue::Any:

      dequeue
      ($string,$scalar,$listref,$hashref) = $queue->dequeue;

      The "dequeue" method removes a reference from the head of the queue, dereferences it and returns the resulting values. If the queue is currently empty, "dequeue" will block the thread until another thread "enqueue"s.

      If I enqueue() a scalar I expect to dequeue() a scalar and not a list.
Re: Thread::Queue::Any->dequeue trouble
by NetWallah (Canon) on Aug 26, 2005 at 03:50 UTC
    You may want to model your Thread code based on some working code I wrote last year.

         "Man cannot live by bread alone...
             He'd better have some goat cheese and wine to go with it!"