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