7 use Thread qw(cond_wait cond_broadcast);
11 if ($Config{useithreads}) {
12 require 'threads/shared/queue.pm';
13 for my $meth (qw(new enqueue dequeue dequeue_nb pending)) {
15 *{"Thread::Queue::$meth"} = \&{"threads::shared::queue::$meth"};
17 } elsif ($Config{use5005threads}) {
18 for my $meth (qw(new enqueue dequeue dequeue_nb pending)) {
20 *{"Thread::Queue::$meth"} = \&{"Thread::Queue::${meth}_othread"};
24 Carp::croak("This Perl has neither ithreads nor 5005threads");
31 Thread::Queue - thread-safe queues (for old code only)
35 For new code the use of the C<Thread::Queue> module is discouraged and
36 the direct use of the C<threads>, C<threads::shared> and
37 C<threads::shared::queue> modules is encouraged instead.
39 For the whole story about the development of threads in Perl, and why you
40 should B<not> be using this module unless you know what you're doing, see the
41 CAVEAT of the C<Thread> module.
46 my $q = new Thread::Queue;
47 $q->enqueue("foo", "bar");
48 my $foo = $q->dequeue; # The "bar" is still in the queue.
49 my $foo = $q->dequeue_nb; # returns "bar", or undef if the queue was
51 my $left = $q->pending; # returns the number of items still in the queue
55 A queue, as implemented by C<Thread::Queue> is a thread-safe data structure
56 much like a list. Any number of threads can safely add elements to the end
57 of the list, or remove elements from the head of the list. (Queues don't
58 permit adding or removing elements from the middle of the list)
60 =head1 FUNCTIONS AND METHODS
66 The C<new> function creates a new empty queue.
70 The C<enqueue> method adds a list of scalars on to the end of the queue.
71 The queue will grow as needed to accomodate the list.
75 The C<dequeue> method removes a scalar from the head of the queue and
76 returns it. If the queue is currently empty, C<dequeue> will block the
77 thread until another thread C<enqueue>s a scalar.
81 The C<dequeue_nb> method, like the C<dequeue> method, removes a scalar from
82 the head of the queue and returns it. Unlike C<dequeue>, though,
83 C<dequeue_nb> won't block if the queue is empty, instead returning
88 The C<pending> method returns the number of items still in the queue. (If
89 there can be multiple readers on the queue it's best to lock the queue
90 before checking to make sure that it stays in a consistent state)
102 return bless [@_], $class;
105 sub dequeue_othread : locked : method {
107 cond_wait $q until @$q;
111 sub dequeue_nb_othread : locked : method {
120 sub enqueue_othread : locked : method {
122 push(@$q, @_) and cond_broadcast $q;
125 sub pending_othread : locked : method {
126 return scalar(@{(shift)});