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