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