On Fri, 3 Sep 2004, PerlDiscuss - Perl Newsgroups and mailing lists wrote:
> If the pool is empty the threads stay waiting for new files.
Why not use dequeue(), which is blocking?
> I'm trying to do something like this script below, but the threads can't
> see the queue list.
Do you mean that the worker threads see $DataQueue as perpetually empty, or
what?
At any rate, your example seems to work for me with the following significant
changes, under 5.8.0 (old!):
- 'threads' instead of 'Thread'
threads->create(\&threadWorker); # instead of new Thread ...
- omit threads::shared
my $DataQueue = Thread::Queue->new; # automatically shared
Modified code:
--------------------
#!/usr/bin/perl
use threads;
use Thread::Queue;
my $DataQueue = Thread::Queue->new;
# start threads
threads->create(\&threadWorker, $_) for 1 .. 4;
while (1) {
$DataQueue->enqueue( my $item = time() );
print "[producer] Added: $item / Total: ", $DataQueue->pending, "\n";
sleep 1;
}
sub threadWorker {
my $WorkerID = shift;
sleep 5;
while (1) {
if ( my $DataElement = $DataQueue->dequeue_nb ) {
print "[consumer $WorkerID] popped $DataElement\n";
} else {
print "[consumer $WorkerID] queue empty [", $DataQueue->pending, "]\n";
}
sleep 1;
}
return 1;
}
--------------------
Regards,
Mike