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