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