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