1package Thread::Queue; 2use Thread qw(cond_wait cond_broadcast); 3 4use vars qw($VERSION); 5$VERSION = '1.00'; 6 7=head1 NAME 8 9Thread::Queue - thread-safe queues (5.005-threads) 10 11=head1 CAVEAT 12 13This Perl installation is using the old unsupported "5.005 threads". 14Use of the old threads model is discouraged. 15 16For the whole story about the development of threads in Perl, and why 17you should B<not> be using "old threads" unless you know what you're 18doing, see the CAVEAT of the C<Thread> module. 19 20=head1 SYNOPSIS 21 22 use Thread::Queue; 23 my $q = new Thread::Queue; 24 $q->enqueue("foo", "bar"); 25 my $foo = $q->dequeue; # The "bar" is still in the queue. 26 my $foo = $q->dequeue_nb; # returns "bar", or undef if the queue was 27 # empty 28 my $left = $q->pending; # returns the number of items still in the queue 29 30=head1 DESCRIPTION 31 32A queue, as implemented by C<Thread::Queue> is a thread-safe data structure 33much like a list. Any number of threads can safely add elements to the end 34of the list, or remove elements from the head of the list. (Queues don't 35permit adding or removing elements from the middle of the list) 36 37=head1 FUNCTIONS AND METHODS 38 39=over 8 40 41=item new 42 43The C<new> function creates a new empty queue. 44 45=item enqueue LIST 46 47The C<enqueue> method adds a list of scalars on to the end of the queue. 48The queue will grow as needed to accomodate the list. 49 50=item dequeue 51 52The C<dequeue> method removes a scalar from the head of the queue and 53returns it. If the queue is currently empty, C<dequeue> will block the 54thread until another thread C<enqueue>s a scalar. 55 56=item dequeue_nb 57 58The C<dequeue_nb> method, like the C<dequeue> method, removes a scalar from 59the head of the queue and returns it. Unlike C<dequeue>, though, 60C<dequeue_nb> won't block if the queue is empty, instead returning 61C<undef>. 62 63=item pending 64 65The C<pending> method returns the number of items still in the queue. (If 66there can be multiple readers on the queue it's best to lock the queue 67before checking to make sure that it stays in a consistent state) 68 69=back 70 71=head1 SEE ALSO 72 73L<Thread> 74 75=cut 76 77sub new { 78 my $class = shift; 79 return bless [@_], $class; 80} 81 82sub dequeue : locked : method { 83 my $q = shift; 84 cond_wait $q until @$q; 85 return shift @$q; 86} 87 88sub dequeue_nb : locked : method { 89 my $q = shift; 90 if (@$q) { 91 return shift @$q; 92 } else { 93 return undef; 94 } 95} 96 97sub enqueue : locked : method { 98 my $q = shift; 99 push(@$q, @_) and cond_broadcast $q; 100} 101 102sub pending : locked : method { 103 my $q = shift; 104 return scalar(@$q); 105} 106 1071; 108