5 use Thread qw(cond_wait cond_broadcast);
9 Thread::Queue - thread-safe queues
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
19 my $left = $q->pending; # returns the number of items still in the queue
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)
28 =head1 FUNCTIONS AND METHODS
34 The C<new> function creates a new empty queue.
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.
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.
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
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)
70 return bless [@_], $class;
73 sub dequeue : locked : method {
75 cond_wait $q until @$q;
79 sub dequeue_nb : locked : method {
88 sub enqueue : locked : method {
90 push(@$q, @_) and cond_broadcast $q;
93 sub pending : locked : method {