blib/lib/EV/Future.pm

filter: Statementstmt 100% 26 / 26 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 8 / 8 Podpod n/a totaltotal 100% 34 / 34 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Future.xs ↑ Summary
1 package EV::Future;
2  
3 14 ▶use 5.014000;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 14 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 14 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 14 our $VERSION = '0.08';
8  
9 14 ▶use EV ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 14 ▶use base 'Exporter';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 14 our @EXPORT = qw(parallel parallel_limit series race
12 parallel_map parallel_map_limit series_map);
13  
14 14 require XSLoader;
15 14 XSLoader::load('EV::Future', $VERSION);
16  
17 {
18 # The handle class is implemented entirely in Future.xs; this stanza gives
19 # it a Perl-side home so it can be indexed, versioned and documented.
20 package EV::Future::Handle;
21  
22 14 our $VERSION = $EV::Future::VERSION;
23  
24 # A handle wraps an internal C pointer to a refcounted cell using
25 # PERL_MAGIC_ext. Duplicating the Perl object via thread cloning yields
26 # undef (CLONE_SKIP), while Storable and Clone produce inert dead handles
27 # without duplicating the underlying C cell.
28 1 ▶ sub CLONE_SKIP { 1 }
Subroutine CLONE_SKIP: called CC=1 SCAR=0.0
29  
30 1 ▶ sub STORABLE_freeze { return '' }
Subroutine STORABLE_freeze: called CC=1 SCAR=0.0
31 1 ▶ sub STORABLE_thaw { ${ $_[0] } = 0; return }
Subroutine STORABLE_thaw: called CC=1 SCAR=0.0
32 }
33  
34 =head1 NAME
35  
36 EV::Future - Minimalist high-performance async control flow for EV
37  
38 =head1 SYNOPSIS
39  
40 use EV;
41 use EV::Future;
42  
43 my @w;
44 parallel([
45 sub { my $done = shift; push @w, EV::timer 0.1, 0, sub { $done->() } },
46 sub { my $done = shift; push @w, EV::timer 0.2, 0, sub { $done->() } },
47 ], sub { print "all done\n" });
48  
49 parallel_map([qw(a b c)], sub {
50 my ($item, $done) = @_;
51 push @w, EV::timer 0.1, 0, sub { $done->() };
52 }, sub { print "all mapped\n" });
53  
54 parallel_limit([
55 sub { my $done = shift; push @w, EV::timer 0.1, 0, sub { $done->() } },
56 sub { my $done = shift; push @w, EV::timer 0.2, 0, sub { $done->() } },
57 sub { my $done = shift; push @w, EV::timer 0.1, 0, sub { $done->() } },
58 ], 2, sub { print "all done (max 2 in-flight)\n" });
59  
60 series([
61 sub { my $done = shift; $done->() },
62 sub { my $done = shift; $done->() },
63 ], sub { print "all done in order\n" });
64  
65 race([
66 sub { my $done = shift; push @w, EV::timer 0.1, 0, sub { $done->("a") } },
67 sub { my $done = shift; push @w, EV::timer 0.2, 0, sub { $done->("b") } },
68 ], sub { my $winner = shift; print "winner: $winner\n" });
69  
70 # In non-void context you get a handle; in void context, nothing is allocated
71 my $h = parallel_map(\@items, \&worker, sub { print "done\n" });
72 printf "%d in flight, %d to go\n", $h->active, $h->pending;
73 $h->cancel; # stop dispatching; final_cb will not fire
74  
75 EV::run;
76  
77 =head1 DESCRIPTION
78  
79 Control-flow primitives (C<parallel>, C<parallel_map>, C<parallel_limit>,
80 C<parallel_map_limit>, C<series>, C<series_map>, C<race>), implemented in XS
81 for minimal overhead. All are exported by default.
82  
83 Each primitive follows one of two conventions. In the task form, C<\@tasks>
84 holds the work directly: each element is a coderef that receives a single
85 C<done> callback as its only argument, and must invoke C<done> exactly once
86 to mark completion. In the map form (C<parallel_map>, C<parallel_map_limit>,
87 C<series_map>), C<\@items> holds plain data, and a separate C<\&worker> is
88 dispatched once per element as C<($item, $done)>.
89  
90 If the list is empty, C<final_cb> fires immediately in either form. See each
91 function's entry below for its exact contract.
92  
93 =head2 Silent traps
94  
95 Four things this module does quietly rather than loudly. None of them warns, so
96 each is worth knowing before it bites.
97  
98 A non-coderef element of C<\@tasks> is treated as a no-op task that completes
99 instantly. The test is for a genuine code reference, so an object with a C<&{}>
100 overload is skipped rather than invoked. The map form inverts this: elements
101 there are data, and are handed to the worker whatever their type.
102  
103 C<\@tasks> must be a plain array. Elements of a tied or otherwise magical array
104 are never fetched, so none of them looks like a code reference and the whole
105 list is treated as no-ops: nothing runs and C<final_cb> fires immediately. Copy
106 into a plain array first. The map form is unaffected, because the worker reads
107 the element it is handed and that performs the fetch.
108  
109 C<final_cb> is never validated. A value that is not a code reference, including
110 C<undef>, is accepted and simply never called, so a mistyped callback fails in
111 total silence. The map-form C<\&worker> is stricter: a non-coderef worker croaks
112 before any dispatch.
113  
114 Handing C<done> itself to an EV watcher cancels a series, because EV calls back
115 with the truthy watcher as the first argument. Always wrap it as
116 C<< sub { $done->() } >>; the C<series> entry below has the detail.
117  
118 =head2 Safe vs unsafe mode
119  
120 Each function takes an optional trailing C<$unsafe> flag. In safe mode (the
121 default), each dispatch is wrapped in C<G_EVAL>, every task gets its own
122 C<done> CV, and double-calls are silently dropped. Unsafe mode skips
123 C<G_EVAL> and reuses a single shared CV, roughly doubling throughput at the
124 cost of:
125  
126 =over 4
127  
128 =item *
129  
130 An exception from a task propagates out uncaught and abandons the whole
131 operation: no further task is dispatched, C<final_cb> never fires, and a
132 C<done> called later by an already-running task is ignored. Safe mode reaches
133 the same outcome by tearing the operation down and re-throwing; unsafe mode
134 cannot run that cleanup, so it leaks the internal context instead.
135  
136 Where the exception surfaces depends on when the task ran. A task dispatched
137 synchronously, while the C<parallel> or C<series> call is still on the stack,
138 throws to that caller. A task dispatched later from an event-loop callback
139 throws into C<EV>, which by default reports it as C<"EV: error in callback
140 (ignoring)"> and keeps the loop running.
141  
142 An abandoned operation is frozen rather than finished, and a handle held over
143 it (see L</CANCELLATION>) shows that. C<pending> and C<active> go on reporting
144 the counts they had when the exception escaped, permanently, because nothing
145 will ever advance them; each is still literally true, but a non-zero C<pending>
146 no longer means the operation is going to make progress. Calling
147 C<$h-E<gt>cancel> on an abandoned handle runs the cleanup the unwind could not:
148 it detaches every outstanding C<done>, frees the leaked context and zeroes both
149 counters. That is the intended way to recover an abandoned operation's memory,
150 and the only one. C<$h-E<gt>cancel(1)> does the same and additionally calls
151 C<final_cb>, which is the single exception to "C<final_cb> never fires" above.
152  
153 =item *
154  
155 Double-calling C<done> corrupts the completion counter, which may invoke
156 C<final_cb> before all tasks have actually finished.
157  
158 =back
159  
160 Use unsafe mode only when tasks are well-behaved and performance is
161 critical.
162  
163 =head1 FUNCTIONS
164  
165 Every function below returns an C<EV::Future::Handle> when called in non-void
166 context; called in void context, no handle is allocated and nothing is
167 returned. See L</CANCELLATION>.
168  
169 =head2 parallel(\@tasks, \&final_cb, [$unsafe])
170  
171 Dispatch every task immediately; call C<final_cb> once each task has invoked
172 its C<done> callback.
173  
174 =head2 parallel_map(\@items, \&worker, \&final_cb, [$unsafe])
175  
176 Dispatch C<\&worker> once per element of C<\@items>, passing
177 C<($item, $done)>; call C<final_cb> once every worker has invoked its C<done>.
178  
179 parallel_map(\@urls, sub {
180 my ($url, $done) = @_;
181 $client->request($url, sub { ...; $done->() });
182 }, sub { print "all fetched\n" });
183  
184 Unlike the task form, elements are data: a non-coderef element is dispatched to
185 the worker like any other value, not treated as a task that completes
186 instantly. Holes in C<\@items> arrive as C<undef>. A non-coderef C<\&worker>
187 is a fatal error, raised before any dispatch.
188  
189 The item is passed without copying, so modifying C<$_[0]> modifies the array
190 element, as with Perl's own C<for> and C<map>.
191  
192 =head2 parallel_limit(\@tasks, $limit, \&final_cb, [$unsafe])
193  
194 Dispatch tasks with at most C<$limit> in flight at any time. C<$limit> is
195 clamped to C<1..scalar(@tasks)>: C<$limit == 1> degenerates to C<series>,
196 C<$limit E<gt>= @tasks> degenerates to C<parallel>.
197  
198 The truthy-C<done> cancellation supported by C<series> does not apply here; see
199 L</CANCELLATION> to stop dispatch from outside via the returned handle.
200  
201 =head2 parallel_map_limit(\@items, \&worker, $limit, \&final_cb, [$unsafe])
202  
203 As C<parallel_map>, with at most C<$limit> workers in flight at any time.
204 C<$limit> is clamped to C<1..scalar(@items)>.
205  
206 parallel_map_limit(\@urls, sub {
207 my ($url, $done) = @_;
208 $client->request($url, sub { ...; $done->() });
209 }, 4, sub { print "all fetched\n" });
210  
211 The item conventions of C<parallel_map> apply unchanged.
212  
213 =head2 series(\@tasks, \&final_cb, [$unsafe])
214  
215 Run tasks sequentially; each task starts only after the previous calls its
216 C<done>. To cancel the series and skip remaining tasks, pass a true value
217 to C<done>:
218  
219 series([
220 sub { my $d = shift; $d->(1) }, # cancel here
221 sub { die "never reached" },
222 ], sub { print "finished early\n" });
223  
224 Cancellation works in both safe and unsafe modes.
225  
226 Beware: EV invokes watcher callbacks as C<$cb-E<gt>($watcher, $revents)>, and
227 C<$watcher> is truthy, so handing C<done> itself to EV silently cancels the
228 series. The broken form:
229  
230 sub { my $done = shift; push @w, EV::timer 0.01, 0, $done }
231  
232 runs the first task, skips every remaining one, and still fires C<final_cb>
233 as if all went well, because the timer calls C<done> with the truthy watcher.
234 Always wrap C<done> in a closure:
235  
236 sub { my $done = shift; push @w, EV::timer 0.01, 0, sub { $done->() } }
237  
238 =head2 series_map(\@items, \&worker, \&final_cb, [$unsafe])
239  
240 As C<parallel_map>, but sequential: the worker is called for the next item only
241 after the previous call has invoked its C<done>. Passing a true value to
242 C<done> cancels the remaining items, exactly as in C<series>, and the same
243 bare-C<done> trap applies: never hand C<$done> itself to an EV watcher,
244 whose callback receives the truthy watcher and cancels the rest; wrap it
245 as C<< sub { $done->() } >>.
246  
247 series_map(\@steps, sub {
248 my ($step, $done) = @_;
249 $etcd->put($step->{key}, $step->{val}, sub { ...; $done->() });
250 }, sub { print "all steps applied\n" });
251  
252 The item conventions of C<parallel_map> apply unchanged.
253  
254 =head2 race(\@tasks, \&final_cb, [$unsafe])
255  
256 Dispatch every task; call C<final_cb> with the arguments passed to the
257 first C<done> invocation. Subsequent C<done> calls (whether from the
258 winning task or losers) are silently ignored.
259  
260 Losing tasks continue to run; C<EV::Future> does not cancel their EV
261 watchers (it didn't create them). To tear losers down, hold their
262 watchers in a shared lvalue and clear it from C<final_cb>:
263  
264 my @w;
265 race([
266 sub { my $d = shift; push @w, EV::timer 0.1, 0, sub { $d->("a") } },
267 sub { my $d = shift; push @w, EV::timer 0.2, 0, sub { $d->("b") } },
268 ], sub { my $winner = shift; @w = () });
269  
270 Non-coderef elements in C<\@tasks> count as instantly-completed winners
271 (with no arguments) and short-circuit dispatch.
272  
273 =head1 CANCELLATION
274  
275 Called in non-void context, every function returns an C<EV::Future::Handle>.
276 Called in void context, no handle is allocated and nothing is returned, so
277 existing call sites are unaffected.
278  
279 my $h = parallel_limit(\@tasks, 4, sub { print "done\n" });
280 $h->cancel; # stop dispatching; final_cb never fires
281 $h->cancel(1); # stop dispatching; final_cb fires once, with no arguments
282  
283 Cancellation stops further dispatch. It cannot interrupt a task already in
284 flight, because that is your code sitting in an C<EV> callback; such a task
285 runs to completion, and the C<done> it eventually calls is ignored.
286  
287 C<cancel> is idempotent and is a no-op once the operation has finished. It may
288 be called from inside a task, in which case the remaining tasks are not
289 dispatched, and from C<final_cb>, where it does nothing.
290  
291 For C<series> this complements the truthy-C<done> form: pass a true value
292 to C<done> to cancel from inside a task, or use the handle to cancel from
293 outside one. They are not interchangeable, and a task that reads the handle
294 right after cancelling itself sees the difference. A truthy C<done> ends the
295 series through its ordinary completion path, so C<final_cb> still fires and the
296 task you are standing in is still counted: C<pending> reads 1 until that task
297 returns. C<$h-E<gt>cancel> tears the series down on the spot, so C<final_cb>
298 does not fire and C<pending> reads 0 straight away.
299  
300 The handle also reports progress:
301  
302 my $h = parallel_limit(\@tasks, 4, sub { });
303 printf "%d in flight, %d to go\n", $h->active, $h->pending;
304  
305 =head1 EV::Future::Handle
306  
307 The object every primitive returns in non-void context. It is a lightweight
308 reference to the operation and owns nothing: destroying the handle does not
309 cancel the operation, and the operation ending does not invalidate the handle.
310 Every method below is safe to call at any time, including on a handle whose
311 operation is already over, where C<cancel> does nothing and both counters read
312 0.
313  
314 The object wraps an internal C pointer to a refcounted cell using
315 C<PERL_MAGIC_ext>. Duplicating the handle via thread cloning yields C<undef>
316 (C<EV::Future::Handle> sets C<CLONE_SKIP>), while cloning via C<Storable> or
317 C<Clone::clone> yields an inert dead handle without duplicating the underlying C
318 cell.
319  
320 =head2 cancel([$fire])
321  
322 Stop dispatching. With no argument, or a false one, C<final_cb> never fires;
323 with a true C<$fire> it fires exactly once, with no arguments, before C<cancel>
324 returns. Idempotent, and a no-op once the operation is over. See L</CANCELLATION>
325 above for what cancellation can and cannot reach.
326  
327 =head2 pending
328  
329 Tasks that have not yet completed, counting both those in flight and those not
330 yet dispatched.
331  
332 =head2 active
333  
334 Tasks currently in flight. C<parallel> and C<race> report the same value here as
335 for C<pending>, because they dispatch every task before returning; C<series>
336 always reports 1 while it is running.
337  
338 =head2 What the counters guarantee
339  
340 Both read 0 once the operation is over, so C<pending == 0> means it has finished
341 or been cancelled. The one exception is an operation abandoned by an escaping
342 unsafe-mode exception, whose counters freeze instead; see
343 L</"Safe vs unsafe mode">.
344  
345 In unsafe mode, double-calling C<done> corrupts the completion counter, so
346 C<pending> under-reports for C<parallel> and C<parallel_limit> for the same
347 reason C<final_cb> can fire early. The same double-call can drive the in-flight
348 count below zero; C<active> is floored at 0 rather than reporting a negative.
349  
350 =head1 BENCHMARKS
351  
352 1000 synchronous tasks, 5000 iterations (C<bench/comparison.pl>). The script
353 covers the task form only, so C<race> and the three map primitives have no
354 figures here; see L</"Task form versus map form"> below for those. Measured
355 with EV 4.37, AnyEvent 7.17, Future::XS 0.15, Promise::XS 0.21 and
356 Future::Utils 0.52.
357  
358 --- PARALLEL (iterations/sec) ---
359 EV::Future (unsafe) 9,259
360 EV::Future (safe) 4,098
361 AnyEvent::cv (begin/end) 1,563
362 Future::XS::wait_all 1,563
363 Promise::XS::all 1,323
364  
365 --- PARALLEL LIMIT 10 (iterations/sec) ---
366 EV::Future (unsafe) 7,692
367 EV::Future (safe) 4,032
368 Future::Utils::fmap_void 624
369  
370 --- SERIES (iterations/sec) ---
371 EV::Future (unsafe) 7,692
372 AnyEvent::cv (stack-safe) 4,717
373 EV::Future (safe) 3,968
374 Future::XS (chain) 1,241
375 Promise::XS (chain) 1,157
376  
377 =head2 Task form versus map form
378  
379 C<bench/map_vs_task.pl>, 100 elements, unsafe mode, as cachegrind instruction
380 counts per call, which are deterministic where wall-clock timings on a loaded
381 machine are not:
382  
383 parallel, task list reused 150,376
384 parallel_map, worker reused 186,106 +24%
385 parallel, task list per call 264,389
386 parallel_map, worker per call 186,193 -30%
387  
388 Per element the map form is the more expensive of the two: it pushes the item
389 as well as C<done>, which costs around 360 instructions per element that the
390 task form does not pay.
391  
392 It still wins in practice, because a task closure has to capture its own
393 element, so the task form has to rebuild the whole list on every call: about
394 1,140 instructions per element, roughly three times what the extra push costs.
395 The map form has nothing per-element to rebuild, which is why its two rows above
396 are within 0.05% of each other; hoisting the worker out of the call buys
397 nothing.
398  
399 So the map form is about 30% cheaper in the usual case, where the list is built
400 at the call site, and about 24% dearer in the case where you can hoist a fixed
401 task list and reuse it across calls. Reach for the map form for its ergonomics,
402 and expect the performance to follow in the common case rather than always.
403  
404 =head1 SEE ALSO
405  
406 L<EV>, L<Future::XS>, L<Promise::XS>
407  
408 =head1 AUTHOR
409  
410 vividsnow
411  
412 =head1 LICENSE
413  
414 This library is free software; you can redistribute it and/or modify
415 it under the same terms as Perl itself.
416  
417 =cut
418  
419 14 1;
« Future.xs ↑ Summary