blib/lib/Async/Queue.pm

filter: Statementstmt 100% 88 / 88 Branchbran 100% 36 / 36 Conditioncond 100% 27 / 27 MC/DCmcdc 100% 16 / 16 Subroutinesub 100% 15 / 15 Podpod 100% 5 / 5 totaltotal 100% 187 / 187 CC 29 SCAR 17.2
CC
29
Cov
100%
_shift_run
10.0
__ANON__
7.0
__ANON__
6.0
CRAP 5.6
↑ Summary
1 package Async::Queue;
2  
3 6 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 6 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use Scalar::Util qw(looks_like_number);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 71 ▶sub new {
Subroutine new: called CC=2 SCAR=6.9
Pod documented
11 71 my ($class, %options) = @_;
12 71 my $self = bless {
13 concurrency => 1,
14 worker => undef,
15 drain => undef,
16 empty => undef,
17 saturated => undef,
18 task_queue => [],
19 running => 0,
20 }, $class;
21 71 $self->$_($options{$_}) foreach qw(concurrency worker drain empty saturated);
22 48 return $self;
23 }
24  
25 24 ▶sub _define_hook_accessors {
Subroutine _define_hook_accessors: called CC=1 SCAR=0.0
26 24 my ($name, %options) = @_;
27 24 my $class = __PACKAGE__;
28 24 my $fullname = "${class}::$name";
29 6 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
30 24 ▶ *{$fullname} = sub {
Subroutine __ANON__: called CC=7 SCAR=19.5
31 2844 my ($self, $v) = @_;
32 2844 ▶ if(@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 303 2541 2844
33 303 ▶ croak "$name must not be undef." if !defined($v) && !$options{allow_undef};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v or $options{"allow_undef"} 3 300 303
Condition100%3/3
defined $v or $options{"allow_undef"}
l!l&&r!l&&!r
1531473
MC/DC100%2/2
defined $v or $options{"allow_undef"}
defined $v $options{"allow_undef"}
Truth table100%3/3
A or B
A= defined $vB= $options{"allow_undef"}
ABresult
1X1
011
000
34 300 ▶ croak "$name must be a coderef" if defined($v) && ref($v) ne 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if defined $v and ref $v ne "CODE" 40 260 300
Condition100%3/3
defined $v and ref $v ne "CODE"
!ll&&!rl&&r
14711340
MC/DC100%2/2
defined $v and ref $v ne "CODE"
defined $v ref $v ne "CODE"
Truth table100%3/3
A and B
A= defined $vB= ref $v ne "CODE"
ABresult
0X0
100
111
35 260 ▶ croak "You cannot set $name while there is a running task." if $self->running > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $self->running > 0 12 248 260
36 248 $self->{$name} = $v;
37 }
38 2789 return $self->{$name};
39 24 };
40 }
41  
42 7339 ▶sub running {
Subroutine running: called CC=1 SCAR=0.0
Pod documented
43 7339 my ($self) = @_;
44 7339 return $self->{running};
45 }
46  
47 11267 ▶sub concurrency {
Subroutine concurrency: called CC=5 SCAR=16.1
Pod documented
48 11267 my ($self, $conc) = @_;
49 11267 ▶ if(@_ > 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ > 1) 91 11176 11267
50 91 ▶ croak "You cannot set concurrency while there is a running task" if $self->running > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $self->running > 0 3 88 91
51 88 ▶ $conc = 1 if not defined($conc);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $conc 60 28 88
52 88 ▶ croak "concurrency must be a number" if !looks_like_number($conc);
Branch: 1 branch
BranchTrueFalseTotal
unless &looks_like_number($conc) 2 86 88
53 86 $self->{concurrency} = int($conc);
54 }
55 11262 return $self->{concurrency};
56 }
57  
58 946 ▶sub length {
Subroutine length: called CC=1 SCAR=0.0
Pod documented
59 946 my ($self) = @_;
60 946 return int(@{$self->{task_queue}});
61 }
62  
63 6 *waiting = \&length;
64  
65 6 _define_hook_accessors 'worker';
66 6 _define_hook_accessors $_, allow_undef => 1 foreach qw(drain empty saturated);
67  
68 2155 ▶sub push {
Subroutine push: called CC=4 SCAR=13.9
Pod documented
69 2155 my ($self, $task, $cb) = @_;
70 2155 ▶ if(@_ < 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ < 2) 1 2154 2155
71 1 croak("You must specify something to push.");
72 }
73 2154 ▶ if(defined($cb) && ref($cb) ne 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $cb and ref $cb ne "CODE") 5 2149 2154
Condition100%3/3
defined $cb and ref $cb ne "CODE"
!ll&&!rl&&r
101511345
MC/DC100%2/2
defined $cb and ref $cb ne "CODE"
defined $cb ref $cb ne "CODE"
Truth table100%3/3
A and B
A= defined $cbB= ref $cb ne "CODE"
ABresult
0X0
100
111
74 5 croak("callback for a task must be a coderef");
75 }
76 2149 push(@{$self->{task_queue}}, [$task, $cb]);
77 2149 $self->_shift_run(1);
78 2145 return $self;
79 }
80  
81 4280 ▶sub _shift_run {
Subroutine _shift_run: called CC=10 SCAR=23.0
82 4280 my ($self, $from_push) = @_;
83 4280 ▶ return if $self->concurrency > 0 && $self->running >= $self->concurrency;
Branch: 1 branch
BranchTrueFalseTotal
if $self->concurrency > 0 and $self->running >= $self->concurrency 2042 2238 4280
Condition100%3/3
$self->concurrency > 0 and $self->running >= $self->concurrency
!ll&&!rl&&r
8021582042
MC/DC100%2/2
$self->concurrency > 0 and $self->running >= $self->concurrency
$self->concurrency > 0 $self->running >= $self->concurrency
Truth table100%3/3
A and B
A= $self->concurrency > 0B= $self->running >= $self->concurrency
ABresult
0X0
100
111
84 2238 my $args_ref = shift(@{$self->{task_queue}});
85 2238 ▶ return if !defined($args_ref);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args_ref 94 2144 2238
86 2144 my ($task, $cb) = @$args_ref;
87 2144 $self->{running} += 1;
88 2144 ▶ if($self->running == $self->concurrency && $from_push && defined($self->saturated)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->running == $self->concurrency and $from_push and defined $self->saturated) 26 2118 2144
Condition100%6/6
$self->running == $self->concurrency and $from_push and defined $self->saturated
!ll&&!rl&&r
21011726
$self->running == $self->concurrency and $from_push
!ll&&!rl&&r
64203743
MC/DC100%3/3
$self->running == $self->concurrency and $from_push and defined $self->saturated
$self->running == $self->concurrency $from_push defined $self->saturated
Truth table100%4/4
A and B and C
A= $self->running == $self->concurrencyB= $from_pushC= defined $self->saturated
ABCresult
0XX0
10X0
1100
1111
89 26 $self->saturated->($self);
90 }
91 2143 ▶ if(@{$self->{task_queue}} == 0 && defined($self->empty)) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"task_queue"};} == 0 and defined $self->empty) 114 2029 2143
Condition100%3/3
@{$self->{"task_queue"};} == 0 and defined $self->empty
!ll&&!rl&&r
201118114
MC/DC100%2/2
@{$self->{"task_queue"};} == 0 and defined $self->empty
@{$self->{"task_queue"};} == 0 defined $self->empty
Truth table100%3/3
A and B
A= @{$self->{"task_queue"};} == 0B= defined $self->empty
ABresult
0X0
100
111
92 114 $self->empty->($self);
93 }
94 2142 my $sync = 1;
95 2142 my $sync_completed = 0;
96 2132 ▶ $self->worker->($task, sub {
Subroutine __ANON__: called CC=6 SCAR=17.9
97 2132 my (@worker_results) = @_;
98 2132 ▶ $cb->(@worker_results) if defined($cb);
Branch: 1 branch
BranchTrueFalseTotal
if defined $cb 1125 1007 2132
99 2132 $self->{running} -= 1;
100 2132 ▶ if(@{$self->{task_queue}} == 0 && $self->running == 0 && defined($self->drain)) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"task_queue"};} == 0 and $self->running == 0 and defined $self->drain) 32 2100 2132
Condition100%6/6
@{$self->{"task_queue"};} == 0 and $self->running == 0 and defined $self->drain
!ll&&!rl&&r
2091932
@{$self->{"task_queue"};} == 0 and $self->running == 0
!ll&&!rl&&r
20375441
MC/DC100%3/3
@{$self->{"task_queue"};} == 0 and $self->running == 0 and defined $self->drain
@{$self->{"task_queue"};} == 0 $self->running == 0 defined $self->drain
Truth table100%4/4
A and B and C
A= @{$self->{"task_queue"};} == 0B= $self->running == 0C= defined $self->drain
ABCresult
0XX0
10X0
1100
1111
101 32 $self->drain->($self);
102 }
103 2131 ▶ if($sync) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sync) { } 2104 27 2131
104 2104 $sync_completed = 1;
105 }else {
106 27 @_ = ($self);
107 27 goto &_shift_run;
108 }
109 2142 }, $self);
110 2140 $sync = 0;
111 2140 ▶ if($sync_completed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($sync_completed) 2104 36 2140
112 2104 @_ = ($self);
113 2104 goto &_shift_run;
114 }
115 }
116  
117  
118 =head1 NAME
119  
120 Async::Queue - control concurrency of asynchronous tasks
121  
122 =head1 VERSION
123  
124 Version 0.021
125  
126 =cut
127  
128 6 our $VERSION = '0.021';
129  
130  
131 =head1 SYNOPSIS
132  
133  
134 use Async::Queue;
135
136 ## create a queue object with concurrency 2
137 my $q = Async::Queue->new(
138 concurrency => 2, worker => sub {
139 my ($task, $callback) = @_;
140 print "hello $task->{name}\n";
141 $callback->();
142 }
143 );
144
145 ## assign a callback
146 $q->drain(sub {
147 print "all items have been processed\n";
148 });
149
150 ## add some items to the queue
151 $q->push({name => 'foo'}, sub {
152 print "finished processing foo\n";
153 });
154 $q->push({name => 'bar'}, sub {
155 print "finished processing bar\n";
156 });
157  
158  
159 =head1 DESCRIPTION
160  
161 L<Async::Queue> is used to process tasks with the specified concurrency.
162 The tasks given to L<Async::Queue> are processed in parallel with its worker routine up to the concurrency level.
163 If more tasks arrive at the L<Async::Queue> object, those tasks will wait for currently running tasks to finish.
164 When a task is finished, one of the waiting tasks starts to be processed in first-in-first-out (FIFO) order.
165  
166 In short, L<Async::Queue> is a Perl port of the C<queue> object of async.js (L<https://github.com/caolan/async#queue>).
167  
168 The basic usage of L<Async::Queue> is as follows:
169  
170 =over
171  
172 =item 1.
173  
174 Create L<Async::Queue> object with C<worker> attribute and optional C<concurrency> attribute.
175 C<worker> is a subroutine reference that processes tasks. C<concurrency> is the concurrency level.
176  
177 =item 2.
178  
179 Push tasks to the L<Async::Queue> object via C<push()> method with optional callback functions.
180  
181 The tasks will be processed in FIFO order by the C<worker> subroutine.
182 When a task is finished, the callback function, if any, is called with the results.
183  
184  
185 =back
186  
187  
188 =head1 CLASS METHODS
189  
190 =head2 $queue = Async::Queue->new(%attributes);
191  
192 Creates an L<Async::Queue> object.
193  
194 It takes named arguments to initialize attributes of the L<Async::Queue> object.
195 See L</ATTRIBUTES> for the list of the attributes.
196  
197 C<worker> attribute is mandatory.
198  
199  
200 =head1 ATTRIBUTES
201  
202 An L<Async::Queue> object has the following attributes.
203  
204 You can initialize the attributes in C<new()> method.
205 You can get and set the attributes of an L<Async::Queue> object via their accessor methods (See L</"OBJECT METHODS">).
206  
207 Note that you cannot set any attribute listed here while there is a task running in the L<Async::Queue> object.
208 This is because changing the attributes during task execution is very confusing and leads to unpredictable behavior.
209 So if you want to set an attribute, make sure there is no task running (C<running()> method can be useful).
210  
211 =head2 worker (CODE($task, $callback, $queue), mandatory)
212  
213 C<worker> attribute is a subroutine reference that processes a task. It must not be C<undef>.
214  
215 C<worker> subroutine reference takes three arguments, C<$task>, C<$callback> and C<$queue>.
216  
217 C<$task> is the task object the C<worker> is supposed to process.
218  
219 C<$callback> is a callback subroutine reference that C<worker> must call when the task is finished.
220 C<$callback> can take any list of arguments, which will be passed to the C<$finish_callback> given to the C<push()> method
221 (See L</"OBJECT METHODS">).
222  
223 C<$queue> is the L<Async::Queue> object that holds the worker.
224  
225 So the C<worker> attribute is something like:
226  
227 my $q = Async::Queue->new(worker => sub {
228 my ($task, $callback, $queue) = @_;
229 my @results = some_processing($task);
230 $callback->(@results);
231 });
232  
233 You can do asynchonous processing by deferring the call to C<$callback>:
234  
235 my $q = Async::Queue->new(worker => sub {
236 my ($task, $callback, $queue) = @_;
237 some_async_processing($task, on_finish => sub {
238 my @results = @_;
239 $callback->(@results);
240 });
241 });
242  
243  
244 =head2 concurrency (INT, optional, default = 1)
245  
246 C<concurrency> attribute is the maximum number of tasks that can be processed at the same time.
247 It must be an integer number.
248  
249 If C<concurrency> is set to 0 or any negative number, the concurrency level becomes infinite,
250 i.e. pushed tasks are immediately processed no matter how many are already running.
251  
252 If C<concurrency> is set to C<undef> (or omitted in C<new()> method), it will be 1.
253  
254  
255 =head2 saturated (CODE($queue), optional, default = undef)
256  
257 C<saturated> attribute is a subroutine reference that is called when the number of running tasks hits C<concurrency>.
258 This means further tasks will wait in the queue.
259  
260 C<saturated> subroutine reference takes one argument (C<$queue>), which is the L<Async::Queue> object holding it.
261  
262  
263 =head2 empty (CODE($queue), optional, default = undef)
264  
265 C<empty> attribute is a subroutine reference that is called when the last task from the queue is given to the worker.
266 This means there is no task waiting in the L<Async::Queue> object.
267  
268 If the L<Async::Queue> object is not saturated, C<empty> subroutine is called every time a task is pushed.
269 This is because every pushed task goes into the queue first even if the L<Async::Queue> object can process the task immediately.
270  
271 C<empty> subroutine reference takes one argument (C<$queue>), which is the L<Async::Queue> object holding it.
272  
273 =head2 drain (CODE($queue), optional, default = undef)
274  
275 C<drain> attribute is a subroutine reference that is called when the last task in the L<Async::Queue> object has finished.
276 This means there is no task running or waiting in the L<Async::Queue> object.
277  
278 C<drain> subroutine reference takes one argument (C<$queue>), which is the C<Async::Queue> object holding it.
279  
280 =head1 OBJECT METHODS
281  
282 =head2 $queue->push($task, [$finish_callback->(@results)] );
283  
284 Pushes a task into the L<Async::Queue> object.
285 The argument C<$task> is mandatory, while C<$finish_callback> is optional.
286  
287 C<$task> is a task that the worker will process. It will be given as the C<$task> argument to the C<worker> subroutine.
288  
289 C<$finish_callback> is a subroutine reference that will be called when the worker finishes processing the task.
290 The arguments for C<$finish_callback> (C<@results>) are the arguments for the C<$callback> subroutine reference in the C<worker> subroutine.
291  
292 C<push()> method returns the L<Async::Queue> object.
293  
294 =head2 $running_num = $queue->running();
295  
296 Returns the number of currently running tasks in the L<Async::Queue> object.
297  
298 =head2 $waiting_num = $queue->waiting();
299  
300 Returns the number of waiting tasks in the L<Async::Queue> object.
301  
302 =head2 $waiting_num = $queue->length();
303  
304 Alias for C<waiting()> method. It returns the number of waiting tasks in the L<Async::Queue> object.
305  
306 =head2 $worker = $queue->worker([$new_worker]);
307  
308 Accessor for the C<worker> attribute.
309  
310 =head2 $concurrency = $queue->concurrency([$new_concurrency]);
311  
312 Accessor for the C<concurrency> attribute.
313  
314 =head2 $saturated = $queue->saturated([$new_saturated]);
315  
316 Accessor for the C<saturated> attribute.
317  
318 =head2 $empty = $queue->empty([$new_empty]);
319  
320 Accessor for the C<empty> attribute.
321  
322 =head2 $drain = $queue->drain([$new_drain]);
323  
324 Accessor for the C<drain> attribute.
325  
326 =head1 EXAMPLE
327  
328 =head2 Concurrent HTTP downloader
329  
330 use strict;
331 use warnings;
332 use AnyEvent;
333 use AnyEvent::HTTP;
334 use Async::Queue;
335
336 my $q = Async::Queue->new(concurrency => 3, worker => sub {
337 my ($url, $callback) = @_;
338 print STDERR "Start $url\n";
339 http_get $url, sub {
340 my ($data, $headers) = @_;
341 print STDERR "End $url\n";
342 $callback->($data);
343 };
344 });
345
346 my @urls = (
347 'http://www.debian.org/',
348 'http://www.ubuntu.com/',
349 'http://fedoraproject.org/',
350 'http://www.opensuse.org/',
351 'http://www.centos.org/',
352 'http://www.slackware.com/',
353 'http://www.gentoo.org/',
354 'http://www.archlinux.org/',
355 'http://trisquel.info/',
356 );
357
358 my %results = ();
359 my $cv = AnyEvent->condvar;
360 foreach my $url (@urls) {
361 $cv->begin();
362 $q->push($url, sub {
363 my ($data) = @_;
364 $results{$url} = $data;
365 $cv->end();
366 });
367 }
368 $cv->recv;
369
370 foreach my $key (keys %results) {
371 print STDERR "$key: " . length($results{$key}) . "bytes\n";
372 }
373  
374 This example uses L<AnyEvent::HTTP> to send HTTP GET requests for multiple URLs simultaneously.
375 While simultaneous requests dramatically improve efficiency, it may overload the client host
376 and/or the network.
377  
378 This is where L<Async::Queue> comes in handy. With L<Async::Queue> you can control the concurrency level
379 of the HTTP sessions (in this case, up to three).
380  
381  
382  
383 =head1 SEE ALSO
384  
385 =over
386  
387 =item L<AnyEvent::FIFO>
388  
389 The goal of L<AnyEvent::FIFO> is the same as that of L<Async::Queue>: to control concurrency level of asynchronous tasks.
390 The big difference is that L<AnyEvent::FIFO> is a queue of subroutines while L<Async::Queue> is a queue of tasks (data).
391 In L<Async::Queue>, worker subroutine is registered with the object in advance.
392 In L<AnyEvent::FIFO>, it is workers that are pushed to the queue.
393  
394 You can emulate L<AnyEvent::FIFO> with L<Async::Queue> by pushing subroutine references to it as tasks.
395  
396 =back
397  
398  
399 =head1 AUTHOR
400  
401 Toshio Ito, C<< <debug.ito at gmail.com> >>
402  
403 =head1 REPOSITORY
404  
405 L<https://github.com/debug-ito/Async-Queue>
406  
407 =head1 BUGS
408  
409 Please report any bugs or feature requests to C<bug-async-queue at rt.cpan.org>, or through
410 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Async-Queue>. I will be notified, and then you'll
411 automatically be notified of progress on your bug as I make changes.
412  
413  
414  
415 =head1 SUPPORT
416  
417 You can find documentation for this module with the perldoc command.
418  
419 perldoc Async::Queue
420  
421  
422 You can also look for information at:
423  
424 =over 4
425  
426 =item * RT: CPAN's request tracker (report bugs here)
427  
428 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Async-Queue>
429  
430 =item * AnnoCPAN: Annotated CPAN documentation
431  
432 L<http://annocpan.org/dist/Async-Queue>
433  
434 =item * CPAN Ratings
435  
436 L<http://cpanratings.perl.org/d/Async-Queue>
437  
438 =item * Search CPAN
439  
440 L<http://search.cpan.org/dist/Async-Queue/>
441  
442 =back
443  
444  
445 =head1 LICENSE AND COPYRIGHT
446  
447 Copyright 2012 Toshio Ito.
448  
449 This program is free software; you can redistribute it and/or modify it
450 under the terms of either: the GNU General Public License as published
451 by the Free Software Foundation; or the Artistic License.
452  
453 See http://dev.perl.org/licenses/ for more information.
454  
455  
456 =cut
457  
458 6 1; # End of Async::Queue
↑ Summary