[ Index ] |
PHP Cross Reference of Unnamed Project |
[Summary view] [Print] [Text view]
1 package Thread::Queue; 2 3 use threads::shared; 4 use strict; 5 6 our $VERSION = '2.00'; 7 8 =head1 NAME 9 10 Thread::Queue - thread-safe queues 11 12 =head1 SYNOPSIS 13 14 use Thread::Queue; 15 my $q = new Thread::Queue; 16 $q->enqueue("foo", "bar"); 17 my $foo = $q->dequeue; # The "bar" is still in the queue. 18 my $foo = $q->dequeue_nb; # returns "bar", or undef if the queue was 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 24 data structure much like a list. Any number of threads can safely 25 add elements to the end of the list, or remove elements from the head 26 of the list. (Queues don't permit adding or removing elements from 27 the middle of the list). 28 29 =head1 FUNCTIONS AND METHODS 30 31 =over 8 32 33 =item new 34 35 The C<new> function creates a new empty queue. 36 37 =item enqueue LIST 38 39 The C<enqueue> method adds a list of scalars on to the end of the queue. 40 The queue will grow as needed to accommodate the list. 41 42 =item dequeue 43 44 The C<dequeue> method removes a scalar from the head of the queue and 45 returns it. If the queue is currently empty, C<dequeue> will block the 46 thread until another thread C<enqueue>s a scalar. 47 48 =item dequeue_nb 49 50 The C<dequeue_nb> method, like the C<dequeue> method, removes a scalar from 51 the head of the queue and returns it. Unlike C<dequeue>, though, 52 C<dequeue_nb> won't block if the queue is empty, instead returning 53 C<undef>. 54 55 =item pending 56 57 The C<pending> method returns the number of items still in the queue. 58 59 =back 60 61 =head1 SEE ALSO 62 63 L<threads>, L<threads::shared> 64 65 =cut 66 67 sub new { 68 my $class = shift; 69 my @q : shared = @_; 70 return bless \@q, $class; 71 } 72 73 sub dequeue { 74 my $q = shift; 75 lock(@$q); 76 cond_wait @$q until @$q; 77 cond_signal @$q if @$q > 1; 78 return shift @$q; 79 } 80 81 sub dequeue_nb { 82 my $q = shift; 83 lock(@$q); 84 return shift @$q; 85 } 86 87 sub enqueue { 88 my $q = shift; 89 lock(@$q); 90 push @$q, @_ and cond_signal @$q; 91 } 92 93 sub pending { 94 my $q = shift; 95 lock(@$q); 96 return scalar(@$q); 97 } 98 99 1; 100 101
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated: Tue Mar 17 22:47:18 2015 | Cross-referenced by PHPXref 0.7.1 |