This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #50946] modified hints for Darwin x86 64bit
[perl5.git] / lib / Thread / Queue.pm
CommitLineData
d21067e0 1package Thread::Queue;
28b605d8 2
83272a45 3use threads::shared;
3d1f1caf 4use strict;
28b605d8 5
83272a45 6our $VERSION = '2.00';
9c6f8578 7
d516a115
JH
8=head1 NAME
9
83272a45 10Thread::Queue - thread-safe queues
d516a115
JH
11
12=head1 SYNOPSIS
13
14 use Thread::Queue;
15 my $q = new Thread::Queue;
16 $q->enqueue("foo", "bar");
a99072da 17 my $foo = $q->dequeue; # The "bar" is still in the queue.
83272a45 18 my $foo = $q->dequeue_nb; # returns "bar", or undef if the queue was empty
a99072da 19 my $left = $q->pending; # returns the number of items still in the queue
d516a115 20
a99072da
HM
21=head1 DESCRIPTION
22
83272a45
JH
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).
a99072da
HM
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.
83272a45 40The queue will grow as needed to accommodate the list.
a99072da
HM
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
83272a45 57The C<pending> method returns the number of items still in the queue.
a99072da
HM
58
59=back
60
61=head1 SEE ALSO
62
83272a45 63L<threads>, L<threads::shared>
bbc7dcd2 64
d516a115
JH
65=cut
66
83272a45 67sub new {
d21067e0 68 my $class = shift;
83272a45
JH
69 my @q : shared = @_;
70 return bless \@q, $class;
d21067e0
MB
71}
72
83272a45 73sub dequeue {
d21067e0 74 my $q = shift;
83272a45
JH
75 lock(@$q);
76 cond_wait @$q until @$q;
77 cond_signal @$q if @$q > 1;
d21067e0
MB
78 return shift @$q;
79}
80
83272a45
JH
81sub dequeue_nb {
82 my $q = shift;
83 lock(@$q);
a99072da 84 return shift @$q;
a99072da
HM
85}
86
83272a45 87sub enqueue {
d21067e0 88 my $q = shift;
83272a45
JH
89 lock(@$q);
90 push @$q, @_ and cond_signal @$q;
d21067e0
MB
91}
92
83272a45
JH
93sub pending {
94 my $q = shift;
95 lock(@$q);
96 return scalar(@$q);
a99072da
HM
97}
98
d21067e0 991;
83272a45
JH
100
101