1package Thread::Queue; 2 3use threads::shared; 4use strict; 5 6our $VERSION = '2.00'; 7 8=head1 NAME 9 10Thread::Queue - thread-safe queues 11 12=head1 SYNOPSIS 13 14 use Thread::Queue; 15 my $q = new Thread::Queue; 16 $q->enqueue("foo", "bar"); 17 my $foo = $q->dequeue; # The "bar" is still in the queue. 18 my $foo = $q->dequeue_nb; # returns "bar", or undef if the queue was empty 19 my $left = $q->pending; # returns the number of items still in the queue 20 21=head1 DESCRIPTION 22 23A queue, as implemented by C<Thread::Queue> is a thread-safe 24data structure much like a list. Any number of threads can safely 25add elements to the end of the list, or remove elements from the head 26of the list. (Queues don't permit adding or removing elements from 27the middle of the list). 28 29=head1 FUNCTIONS AND METHODS 30 31=over 8 32 33=item new 34 35The C<new> function creates a new empty queue. 36 37=item enqueue LIST 38 39The C<enqueue> method adds a list of scalars on to the end of the queue. 40The queue will grow as needed to accommodate the list. 41 42=item dequeue 43 44The C<dequeue> method removes a scalar from the head of the queue and 45returns it. If the queue is currently empty, C<dequeue> will block the 46thread until another thread C<enqueue>s a scalar. 47 48=item dequeue_nb 49 50The C<dequeue_nb> method, like the C<dequeue> method, removes a scalar from 51the head of the queue and returns it. Unlike C<dequeue>, though, 52C<dequeue_nb> won't block if the queue is empty, instead returning 53C<undef>. 54 55=item pending 56 57The C<pending> method returns the number of items still in the queue. 58 59=back 60 61=head1 SEE ALSO 62 63L<threads>, L<threads::shared> 64 65=cut 66 67sub new { 68 my $class = shift; 69 my @q : shared = @_; 70 return bless \@q, $class; 71} 72 73sub dequeue { 74 my $q = shift; 75 lock(@$q); 76 cond_wait @$q until @$q; 77 cond_signal @$q if @$q > 1; 78 return shift @$q; 79} 80 81sub dequeue_nb { 82 my $q = shift; 83 lock(@$q); 84 return shift @$q; 85} 86 87sub enqueue { 88 my $q = shift; 89 lock(@$q); 90 push @$q, @_ and cond_signal @$q; 91} 92 93sub pending { 94 my $q = shift; 95 lock(@$q); 96 return scalar(@$q); 97} 98 991; 100 101 102