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