1AnyEvent(3) User Contributed Perl Documentation AnyEvent(3)
2
3
4
6 AnyEvent - the DBI of event loop programming
7
8 EV, Event, Glib, Tk, UV, Perl, Event::Lib, Irssi, rxvt-unicode,
9 IO::Async, Qt, FLTK and POE are various supported event
10 loops/environments.
11
13 use AnyEvent;
14
15 # if you prefer function calls, look at the AE manpage for
16 # an alternative API.
17
18 # file handle or descriptor readable
19 my $w = AnyEvent->io (fh => $fh, poll => "r", cb => sub { ... });
20
21 # one-shot or repeating timers
22 my $w = AnyEvent->timer (after => $seconds, cb => sub { ... });
23 my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ...);
24
25 print AnyEvent->now; # prints current event loop time
26 print AnyEvent->time; # think Time::HiRes::time or simply CORE::time.
27
28 # POSIX signal
29 my $w = AnyEvent->signal (signal => "TERM", cb => sub { ... });
30
31 # child process exit
32 my $w = AnyEvent->child (pid => $pid, cb => sub {
33 my ($pid, $status) = @_;
34 ...
35 });
36
37 # called when event loop idle (if applicable)
38 my $w = AnyEvent->idle (cb => sub { ... });
39
40 my $w = AnyEvent->condvar; # stores whether a condition was flagged
41 $w->send; # wake up current and all future recv's
42 $w->recv; # enters "main loop" till $condvar gets ->send
43 # use a condvar in callback mode:
44 $w->cb (sub { $_[0]->recv });
45
47 This manpage is mainly a reference manual. If you are interested in a
48 tutorial or some gentle introduction, have a look at the
49 AnyEvent::Intro manpage.
50
52 An FAQ document is available as AnyEvent::FAQ.
53
54 There also is a mailinglist for discussing all things AnyEvent, and an
55 IRC channel, too.
56
57 See the AnyEvent project page at the Schmorpforge Ta-Sa Software
58 Repository, at <http://anyevent.schmorp.de>, for more info.
59
61 Glib, POE, IO::Async, Event... CPAN offers event models by the dozen
62 nowadays. So what is different about AnyEvent?
63
64 Executive Summary: AnyEvent is compatible, AnyEvent is free of policy
65 and AnyEvent is small and efficient.
66
67 First and foremost, AnyEvent is not an event model itself, it only
68 interfaces to whatever event model the main program happens to use, in
69 a pragmatic way. For event models and certain classes of immortals
70 alike, the statement "there can only be one" is a bitter reality: In
71 general, only one event loop can be active at the same time in a
72 process. AnyEvent cannot change this, but it can hide the differences
73 between those event loops.
74
75 The goal of AnyEvent is to offer module authors the ability to do event
76 programming (waiting for I/O or timer events) without subscribing to a
77 religion, a way of living, and most importantly: without forcing your
78 module users into the same thing by forcing them to use the same event
79 model you use.
80
81 For modules like POE or IO::Async (which is a total misnomer as it is
82 actually doing all I/O synchronously...), using them in your module is
83 like joining a cult: After you join, you are dependent on them and you
84 cannot use anything else, as they are simply incompatible to everything
85 that isn't them. What's worse, all the potential users of your module
86 are also forced to use the same event loop you use.
87
88 AnyEvent is different: AnyEvent + POE works fine. AnyEvent + Glib works
89 fine. AnyEvent + Tk works fine etc. etc. but none of these work
90 together with the rest: POE + EV? No go. Tk + Event? No go. Again: if
91 your module uses one of those, every user of your module has to use it,
92 too. But if your module uses AnyEvent, it works transparently with all
93 event models it supports (including stuff like IO::Async, as long as
94 those use one of the supported event loops. It is easy to add new event
95 loops to AnyEvent, too, so it is future-proof).
96
97 In addition to being free of having to use the one and only true event
98 model, AnyEvent also is free of bloat and policy: with POE or similar
99 modules, you get an enormous amount of code and strict rules you have
100 to follow. AnyEvent, on the other hand, is lean and to the point, by
101 only offering the functionality that is necessary, in as thin as a
102 wrapper as technically possible.
103
104 Of course, AnyEvent comes with a big (and fully optional!) toolbox of
105 useful functionality, such as an asynchronous DNS resolver, 100% non-
106 blocking connects (even with TLS/SSL, IPv6 and on broken platforms such
107 as Windows) and lots of real-world knowledge and workarounds for
108 platform bugs and differences.
109
110 Now, if you do want lots of policy (this can arguably be somewhat
111 useful) and you want to force your users to use the one and only event
112 model, you should not use this module.
113
115 AnyEvent provides a uniform interface to various event loops. This
116 allows module authors to use event loop functionality without forcing
117 module users to use a specific event loop implementation (since more
118 than one event loop cannot coexist peacefully).
119
120 The interface itself is vaguely similar, but not identical to the Event
121 module.
122
123 During the first call of any watcher-creation method, the module tries
124 to detect the currently loaded event loop by probing whether one of the
125 following modules is already loaded: EV, AnyEvent::Loop, Event, Glib,
126 Tk, Event::Lib, Qt, POE. The first one found is used. If none are
127 detected, the module tries to load the first four modules in the order
128 given; but note that if EV is not available, the pure-perl
129 AnyEvent::Loop should always work, so the other two are not normally
130 tried.
131
132 Because AnyEvent first checks for modules that are already loaded,
133 loading an event model explicitly before first using AnyEvent will
134 likely make that model the default. For example:
135
136 use Tk;
137 use AnyEvent;
138
139 # .. AnyEvent will likely default to Tk
140
141 The likely means that, if any module loads another event model and
142 starts using it, all bets are off - this case should be very rare
143 though, as very few modules hardcode event loops without announcing
144 this very loudly.
145
146 The pure-perl implementation of AnyEvent is called "AnyEvent::Loop".
147 Like other event modules you can load it explicitly and enjoy the high
148 availability of that event loop :)
149
151 AnyEvent has the central concept of a watcher, which is an object that
152 stores relevant data for each kind of event you are waiting for, such
153 as the callback to call, the file handle to watch, etc.
154
155 These watchers are normal Perl objects with normal Perl lifetime. After
156 creating a watcher it will immediately "watch" for events and invoke
157 the callback when the event occurs (of course, only when the event
158 model is in control).
159
160 Note that callbacks must not permanently change global variables
161 potentially in use by the event loop (such as $_ or $[) and that
162 callbacks must not "die". The former is good programming practice in
163 Perl and the latter stems from the fact that exception handling differs
164 widely between event loops.
165
166 To disable a watcher you have to destroy it (e.g. by setting the
167 variable you store it in to "undef" or otherwise deleting all
168 references to it).
169
170 All watchers are created by calling a method on the "AnyEvent" class.
171
172 Many watchers either are used with "recursion" (repeating timers for
173 example), or need to refer to their watcher object in other ways.
174
175 One way to achieve that is this pattern:
176
177 my $w; $w = AnyEvent->type (arg => value ..., cb => sub {
178 # you can use $w here, for example to undef it
179 undef $w;
180 });
181
182 Note that "my $w; $w =" combination. This is necessary because in Perl,
183 my variables are only visible after the statement in which they are
184 declared.
185
186 I/O WATCHERS
187 $w = AnyEvent->io (
188 fh => <filehandle_or_fileno>,
189 poll => <"r" or "w">,
190 cb => <callback>,
191 );
192
193 You can create an I/O watcher by calling the "AnyEvent->io" method with
194 the following mandatory key-value pairs as arguments:
195
196 "fh" is the Perl file handle (or a naked file descriptor) to watch for
197 events (AnyEvent might or might not keep a reference to this file
198 handle). Note that only file handles pointing to things for which non-
199 blocking operation makes sense are allowed. This includes sockets, most
200 character devices, pipes, fifos and so on, but not for example files or
201 block devices.
202
203 "poll" must be a string that is either "r" or "w", which creates a
204 watcher waiting for "r"eadable or "w"ritable events, respectively.
205
206 "cb" is the callback to invoke each time the file handle becomes ready.
207
208 Although the callback might get passed parameters, their value and
209 presence is undefined and you cannot rely on them. Portable AnyEvent
210 callbacks cannot use arguments passed to I/O watcher callbacks.
211
212 The I/O watcher might use the underlying file descriptor or a copy of
213 it. You must not close a file handle as long as any watcher is active
214 on the underlying file descriptor.
215
216 Some event loops issue spurious readiness notifications, so you should
217 always use non-blocking calls when reading/writing from/to your file
218 handles.
219
220 Example: wait for readability of STDIN, then read a line and disable
221 the watcher.
222
223 my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
224 chomp (my $input = <STDIN>);
225 warn "read: $input\n";
226 undef $w;
227 });
228
229 TIME WATCHERS
230 $w = AnyEvent->timer (after => <seconds>, cb => <callback>);
231
232 $w = AnyEvent->timer (
233 after => <fractional_seconds>,
234 interval => <fractional_seconds>,
235 cb => <callback>,
236 );
237
238 You can create a time watcher by calling the "AnyEvent->timer" method
239 with the following mandatory arguments:
240
241 "after" specifies after how many seconds (fractional values are
242 supported) the callback should be invoked. "cb" is the callback to
243 invoke in that case.
244
245 Although the callback might get passed parameters, their value and
246 presence is undefined and you cannot rely on them. Portable AnyEvent
247 callbacks cannot use arguments passed to time watcher callbacks.
248
249 The callback will normally be invoked only once. If you specify another
250 parameter, "interval", as a strictly positive number (> 0), then the
251 callback will be invoked regularly at that interval (in fractional
252 seconds) after the first invocation. If "interval" is specified with a
253 false value, then it is treated as if it were not specified at all.
254
255 The callback will be rescheduled before invoking the callback, but no
256 attempt is made to avoid timer drift in most backends, so the interval
257 is only approximate.
258
259 Example: fire an event after 7.7 seconds.
260
261 my $w = AnyEvent->timer (after => 7.7, cb => sub {
262 warn "timeout\n";
263 });
264
265 # to cancel the timer:
266 undef $w;
267
268 Example 2: fire an event after 0.5 seconds, then roughly every second.
269
270 my $w = AnyEvent->timer (after => 0.5, interval => 1, cb => sub {
271 warn "timeout\n";
272 });
273
274 TIMING ISSUES
275
276 There are two ways to handle timers: based on real time (relative,
277 "fire in 10 seconds") and based on wallclock time (absolute, "fire at
278 12 o'clock").
279
280 While most event loops expect timers to specified in a relative way,
281 they use absolute time internally. This makes a difference when your
282 clock "jumps", for example, when ntp decides to set your clock
283 backwards from the wrong date of 2014-01-01 to 2008-01-01, a watcher
284 that is supposed to fire "after a second" might actually take six years
285 to finally fire.
286
287 AnyEvent cannot compensate for this. The only event loop that is
288 conscious of these issues is EV, which offers both relative (ev_timer,
289 based on true relative time) and absolute (ev_periodic, based on
290 wallclock time) timers.
291
292 AnyEvent always prefers relative timers, if available, matching the
293 AnyEvent API.
294
295 AnyEvent has two additional methods that return the "current time":
296
297 AnyEvent->time
298 This returns the "current wallclock time" as a fractional number of
299 seconds since the Epoch (the same thing as "time" or
300 "Time::HiRes::time" return, and the result is guaranteed to be
301 compatible with those).
302
303 It progresses independently of any event loop processing, i.e. each
304 call will check the system clock, which usually gets updated
305 frequently.
306
307 AnyEvent->now
308 This also returns the "current wallclock time", but unlike "time",
309 above, this value might change only once per event loop iteration,
310 depending on the event loop (most return the same time as "time",
311 above). This is the time that AnyEvent's timers get scheduled
312 against.
313
314 In almost all cases (in all cases if you don't care), this is the
315 function to call when you want to know the current time.
316
317 This function is also often faster then "AnyEvent->time", and thus
318 the preferred method if you want some timestamp (for example,
319 AnyEvent::Handle uses this to update its activity timeouts).
320
321 The rest of this section is only of relevance if you try to be very
322 exact with your timing; you can skip it without a bad conscience.
323
324 For a practical example of when these times differ, consider
325 Event::Lib and EV and the following set-up:
326
327 The event loop is running and has just invoked one of your
328 callbacks at time=500 (assume no other callbacks delay processing).
329 In your callback, you wait a second by executing "sleep 1"
330 (blocking the process for a second) and then (at time=501) you
331 create a relative timer that fires after three seconds.
332
333 With Event::Lib, "AnyEvent->time" and "AnyEvent->now" will both
334 return 501, because that is the current time, and the timer will be
335 scheduled to fire at time=504 (501 + 3).
336
337 With EV, "AnyEvent->time" returns 501 (as that is the current
338 time), but "AnyEvent->now" returns 500, as that is the time the
339 last event processing phase started. With EV, your timer gets
340 scheduled to run at time=503 (500 + 3).
341
342 In one sense, Event::Lib is more exact, as it uses the current time
343 regardless of any delays introduced by event processing. However,
344 most callbacks do not expect large delays in processing, so this
345 causes a higher drift (and a lot more system calls to get the
346 current time).
347
348 In another sense, EV is more exact, as your timer will be scheduled
349 at the same time, regardless of how long event processing actually
350 took.
351
352 In either case, if you care (and in most cases, you don't), then
353 you can get whatever behaviour you want with any event loop, by
354 taking the difference between "AnyEvent->time" and "AnyEvent->now"
355 into account.
356
357 AnyEvent->now_update
358 Some event loops (such as EV or AnyEvent::Loop) cache the current
359 time for each loop iteration (see the discussion of AnyEvent->now,
360 above).
361
362 When a callback runs for a long time (or when the process sleeps),
363 then this "current" time will differ substantially from the real
364 time, which might affect timers and time-outs.
365
366 When this is the case, you can call this method, which will update
367 the event loop's idea of "current time".
368
369 A typical example would be a script in a web server (e.g.
370 "mod_perl") - when mod_perl executes the script, then the event
371 loop will have the wrong idea about the "current time" (being
372 potentially far in the past, when the script ran the last time). In
373 that case you should arrange a call to "AnyEvent->now_update" each
374 time the web server process wakes up again (e.g. at the start of
375 your script, or in a handler).
376
377 Note that updating the time might cause some events to be handled.
378
379 SIGNAL WATCHERS
380 $w = AnyEvent->signal (signal => <uppercase_signal_name>, cb => <callback>);
381
382 You can watch for signals using a signal watcher, "signal" is the
383 signal name in uppercase and without any "SIG" prefix, "cb" is the Perl
384 callback to be invoked whenever a signal occurs.
385
386 Although the callback might get passed parameters, their value and
387 presence is undefined and you cannot rely on them. Portable AnyEvent
388 callbacks cannot use arguments passed to signal watcher callbacks.
389
390 Multiple signal occurrences can be clumped together into one callback
391 invocation, and callback invocation will be synchronous. Synchronous
392 means that it might take a while until the signal gets handled by the
393 process, but it is guaranteed not to interrupt any other callbacks.
394
395 The main advantage of using these watchers is that you can share a
396 signal between multiple watchers, and AnyEvent will ensure that signals
397 will not interrupt your program at bad times.
398
399 This watcher might use %SIG (depending on the event loop used), so
400 programs overwriting those signals directly will likely not work
401 correctly.
402
403 Example: exit on SIGINT
404
405 my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });
406
407 Restart Behaviour
408
409 While restart behaviour is up to the event loop implementation, most
410 will not restart syscalls (that includes Async::Interrupt and
411 AnyEvent's pure perl implementation).
412
413 Safe/Unsafe Signals
414
415 Perl signals can be either "safe" (synchronous to opcode handling) or
416 "unsafe" (asynchronous) - the former might delay signal delivery
417 indefinitely, the latter might corrupt your memory.
418
419 AnyEvent signal handlers are, in addition, synchronous to the event
420 loop, i.e. they will not interrupt your running perl program but will
421 only be called as part of the normal event handling (just like timer,
422 I/O etc. callbacks, too).
423
424 Signal Races, Delays and Workarounds
425
426 Many event loops (e.g. Glib, Tk, Qt, IO::Async) do not support
427 attaching callbacks to signals in a generic way, which is a pity, as
428 you cannot do race-free signal handling in perl, requiring C libraries
429 for this. AnyEvent will try to do its best, which means in some cases,
430 signals will be delayed. The maximum time a signal might be delayed is
431 10 seconds by default, but can be overriden via
432 $ENV{PERL_ANYEVENT_MAX_SIGNAL_LATENCY} or $AnyEvent::MAX_SIGNAL_LATENCY
433 - see the "ENVIRONMENT VARIABLES" section for details.
434
435 All these problems can be avoided by installing the optional
436 Async::Interrupt module, which works with most event loops. It will not
437 work with inherently broken event loops such as Event or Event::Lib
438 (and not with POE currently). For those, you just have to suffer the
439 delays.
440
441 CHILD PROCESS WATCHERS
442 $w = AnyEvent->child (pid => <process id>, cb => <callback>);
443
444 You can also watch for a child process exit and catch its exit status.
445
446 The child process is specified by the "pid" argument (on some backends,
447 using 0 watches for any child process exit, on others this will croak).
448 The watcher will be triggered only when the child process has finished
449 and an exit status is available, not on any trace events
450 (stopped/continued).
451
452 The callback will be called with the pid and exit status (as returned
453 by waitpid), so unlike other watcher types, you can rely on child
454 watcher callback arguments.
455
456 This watcher type works by installing a signal handler for "SIGCHLD",
457 and since it cannot be shared, nothing else should use SIGCHLD or reap
458 random child processes (waiting for specific child processes, e.g.
459 inside "system", is just fine).
460
461 There is a slight catch to child watchers, however: you usually start
462 them after the child process was created, and this means the process
463 could have exited already (and no SIGCHLD will be sent anymore).
464
465 Not all event models handle this correctly (neither POE nor IO::Async
466 do, see their AnyEvent::Impl manpages for details), but even for event
467 models that do handle this correctly, they usually need to be loaded
468 before the process exits (i.e. before you fork in the first place).
469 AnyEvent's pure perl event loop handles all cases correctly regardless
470 of when you start the watcher.
471
472 This means you cannot create a child watcher as the very first thing in
473 an AnyEvent program, you have to create at least one watcher before you
474 "fork" the child (alternatively, you can call "AnyEvent::detect").
475
476 As most event loops do not support waiting for child events, they will
477 be emulated by AnyEvent in most cases, in which case the latency and
478 race problems mentioned in the description of signal watchers apply.
479
480 Example: fork a process and wait for it
481
482 my $done = AnyEvent->condvar;
483
484 # this forks and immediately calls exit in the child. this
485 # normally has all sorts of bad consequences for your parent,
486 # so take this as an example only. always fork and exec,
487 # or call POSIX::_exit, in real code.
488 my $pid = fork or exit 5;
489
490 my $w = AnyEvent->child (
491 pid => $pid,
492 cb => sub {
493 my ($pid, $status) = @_;
494 warn "pid $pid exited with status $status";
495 $done->send;
496 },
497 );
498
499 # do something else, then wait for process exit
500 $done->recv;
501
502 IDLE WATCHERS
503 $w = AnyEvent->idle (cb => <callback>);
504
505 This will repeatedly invoke the callback after the process becomes
506 idle, until either the watcher is destroyed or new events have been
507 detected.
508
509 Idle watchers are useful when there is a need to do something, but it
510 is not so important (or wise) to do it instantly. The callback will be
511 invoked only when there is "nothing better to do", which is usually
512 defined as "all outstanding events have been handled and no new events
513 have been detected". That means that idle watchers ideally get invoked
514 when the event loop has just polled for new events but none have been
515 detected. Instead of blocking to wait for more events, the idle
516 watchers will be invoked.
517
518 Unfortunately, most event loops do not really support idle watchers
519 (only EV, Event and Glib do it in a usable fashion) - for the rest,
520 AnyEvent will simply call the callback "from time to time".
521
522 Example: read lines from STDIN, but only process them when the program
523 is otherwise idle:
524
525 my @lines; # read data
526 my $idle_w;
527 my $io_w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
528 push @lines, scalar <STDIN>;
529
530 # start an idle watcher, if not already done
531 $idle_w ||= AnyEvent->idle (cb => sub {
532 # handle only one line, when there are lines left
533 if (my $line = shift @lines) {
534 print "handled when idle: $line";
535 } else {
536 # otherwise disable the idle watcher again
537 undef $idle_w;
538 }
539 });
540 });
541
542 CONDITION VARIABLES
543 $cv = AnyEvent->condvar;
544
545 $cv->send (<list>);
546 my @res = $cv->recv;
547
548 If you are familiar with some event loops you will know that all of
549 them require you to run some blocking "loop", "run" or similar function
550 that will actively watch for new events and call your callbacks.
551
552 AnyEvent is slightly different: it expects somebody else to run the
553 event loop and will only block when necessary (usually when told by the
554 user).
555
556 The tool to do that is called a "condition variable", so called because
557 they represent a condition that must become true.
558
559 Now is probably a good time to look at the examples further below.
560
561 Condition variables can be created by calling the "AnyEvent->condvar"
562 method, usually without arguments. The only argument pair allowed is
563 "cb", which specifies a callback to be called when the condition
564 variable becomes true, with the condition variable as the first
565 argument (but not the results).
566
567 After creation, the condition variable is "false" until it becomes
568 "true" by calling the "send" method (or calling the condition variable
569 as if it were a callback, read about the caveats in the description for
570 the "->send" method).
571
572 Since condition variables are the most complex part of the AnyEvent
573 API, here are some different mental models of what they are - pick the
574 ones you can connect to:
575
576 · Condition variables are like callbacks - you can call them (and
577 pass them instead of callbacks). Unlike callbacks however, you can
578 also wait for them to be called.
579
580 · Condition variables are signals - one side can emit or send them,
581 the other side can wait for them, or install a handler that is
582 called when the signal fires.
583
584 · Condition variables are like "Merge Points" - points in your
585 program where you merge multiple independent results/control flows
586 into one.
587
588 · Condition variables represent a transaction - functions that start
589 some kind of transaction can return them, leaving the caller the
590 choice between waiting in a blocking fashion, or setting a
591 callback.
592
593 · Condition variables represent future values, or promises to deliver
594 some result, long before the result is available.
595
596 Condition variables are very useful to signal that something has
597 finished, for example, if you write a module that does asynchronous
598 http requests, then a condition variable would be the ideal candidate
599 to signal the availability of results. The user can either act when the
600 callback is called or can synchronously "->recv" for the results.
601
602 You can also use them to simulate traditional event loops - for
603 example, you can block your main program until an event occurs - for
604 example, you could "->recv" in your main program until the user clicks
605 the Quit button of your app, which would "->send" the "quit" event.
606
607 Note that condition variables recurse into the event loop - if you have
608 two pieces of code that call "->recv" in a round-robin fashion, you
609 lose. Therefore, condition variables are good to export to your caller,
610 but you should avoid making a blocking wait yourself, at least in
611 callbacks, as this asks for trouble.
612
613 Condition variables are represented by hash refs in perl, and the keys
614 used by AnyEvent itself are all named "_ae_XXX" to make subclassing
615 easy (it is often useful to build your own transaction class on top of
616 AnyEvent). To subclass, use "AnyEvent::CondVar" as base class and call
617 its "new" method in your own "new" method.
618
619 There are two "sides" to a condition variable - the "producer side"
620 which eventually calls "-> send", and the "consumer side", which waits
621 for the send to occur.
622
623 Example: wait for a timer.
624
625 # condition: "wait till the timer is fired"
626 my $timer_fired = AnyEvent->condvar;
627
628 # create the timer - we could wait for, say
629 # a handle becomign ready, or even an
630 # AnyEvent::HTTP request to finish, but
631 # in this case, we simply use a timer:
632 my $w = AnyEvent->timer (
633 after => 1,
634 cb => sub { $timer_fired->send },
635 );
636
637 # this "blocks" (while handling events) till the callback
638 # calls ->send
639 $timer_fired->recv;
640
641 Example: wait for a timer, but take advantage of the fact that
642 condition variables are also callable directly.
643
644 my $done = AnyEvent->condvar;
645 my $delay = AnyEvent->timer (after => 5, cb => $done);
646 $done->recv;
647
648 Example: Imagine an API that returns a condvar and doesn't support
649 callbacks. This is how you make a synchronous call, for example from
650 the main program:
651
652 use AnyEvent::CouchDB;
653
654 ...
655
656 my @info = $couchdb->info->recv;
657
658 And this is how you would just set a callback to be called whenever the
659 results are available:
660
661 $couchdb->info->cb (sub {
662 my @info = $_[0]->recv;
663 });
664
665 METHODS FOR PRODUCERS
666
667 These methods should only be used by the producing side, i.e. the
668 code/module that eventually sends the signal. Note that it is also the
669 producer side which creates the condvar in most cases, but it isn't
670 uncommon for the consumer to create it as well.
671
672 $cv->send (...)
673 Flag the condition as ready - a running "->recv" and all further
674 calls to "recv" will (eventually) return after this method has been
675 called. If nobody is waiting the send will be remembered.
676
677 If a callback has been set on the condition variable, it is called
678 immediately from within send.
679
680 Any arguments passed to the "send" call will be returned by all
681 future "->recv" calls.
682
683 Condition variables are overloaded so one can call them directly
684 (as if they were a code reference). Calling them directly is the
685 same as calling "send".
686
687 $cv->croak ($error)
688 Similar to send, but causes all calls to "->recv" to invoke
689 "Carp::croak" with the given error message/object/scalar.
690
691 This can be used to signal any errors to the condition variable
692 user/consumer. Doing it this way instead of calling "croak"
693 directly delays the error detection, but has the overwhelming
694 advantage that it diagnoses the error at the place where the result
695 is expected, and not deep in some event callback with no connection
696 to the actual code causing the problem.
697
698 $cv->begin ([group callback])
699 $cv->end
700 These two methods can be used to combine many transactions/events
701 into one. For example, a function that pings many hosts in parallel
702 might want to use a condition variable for the whole process.
703
704 Every call to "->begin" will increment a counter, and every call to
705 "->end" will decrement it. If the counter reaches 0 in "->end",
706 the (last) callback passed to "begin" will be executed, passing the
707 condvar as first argument. That callback is supposed to call
708 "->send", but that is not required. If no group callback was set,
709 "send" will be called without any arguments.
710
711 You can think of "$cv->send" giving you an OR condition (one call
712 sends), while "$cv->begin" and "$cv->end" giving you an AND
713 condition (all "begin" calls must be "end"'ed before the condvar
714 sends).
715
716 Let's start with a simple example: you have two I/O watchers (for
717 example, STDOUT and STDERR for a program), and you want to wait for
718 both streams to close before activating a condvar:
719
720 my $cv = AnyEvent->condvar;
721
722 $cv->begin; # first watcher
723 my $w1 = AnyEvent->io (fh => $fh1, cb => sub {
724 defined sysread $fh1, my $buf, 4096
725 or $cv->end;
726 });
727
728 $cv->begin; # second watcher
729 my $w2 = AnyEvent->io (fh => $fh2, cb => sub {
730 defined sysread $fh2, my $buf, 4096
731 or $cv->end;
732 });
733
734 $cv->recv;
735
736 This works because for every event source (EOF on file handle),
737 there is one call to "begin", so the condvar waits for all calls to
738 "end" before sending.
739
740 The ping example mentioned above is slightly more complicated, as
741 the there are results to be passed back, and the number of tasks
742 that are begun can potentially be zero:
743
744 my $cv = AnyEvent->condvar;
745
746 my %result;
747 $cv->begin (sub { shift->send (\%result) });
748
749 for my $host (@list_of_hosts) {
750 $cv->begin;
751 ping_host_then_call_callback $host, sub {
752 $result{$host} = ...;
753 $cv->end;
754 };
755 }
756
757 $cv->end;
758
759 ...
760
761 my $results = $cv->recv;
762
763 This code fragment supposedly pings a number of hosts and calls
764 "send" after results for all then have have been gathered - in any
765 order. To achieve this, the code issues a call to "begin" when it
766 starts each ping request and calls "end" when it has received some
767 result for it. Since "begin" and "end" only maintain a counter, the
768 order in which results arrive is not relevant.
769
770 There is an additional bracketing call to "begin" and "end" outside
771 the loop, which serves two important purposes: first, it sets the
772 callback to be called once the counter reaches 0, and second, it
773 ensures that "send" is called even when "no" hosts are being pinged
774 (the loop doesn't execute once).
775
776 This is the general pattern when you "fan out" into multiple (but
777 potentially zero) subrequests: use an outer "begin"/"end" pair to
778 set the callback and ensure "end" is called at least once, and
779 then, for each subrequest you start, call "begin" and for each
780 subrequest you finish, call "end".
781
782 METHODS FOR CONSUMERS
783
784 These methods should only be used by the consuming side, i.e. the code
785 awaits the condition.
786
787 $cv->recv
788 Wait (blocking if necessary) until the "->send" or "->croak"
789 methods have been called on $cv, while servicing other watchers
790 normally.
791
792 You can only wait once on a condition - additional calls are valid
793 but will return immediately.
794
795 If an error condition has been set by calling "->croak", then this
796 function will call "croak".
797
798 In list context, all parameters passed to "send" will be returned,
799 in scalar context only the first one will be returned.
800
801 Note that doing a blocking wait in a callback is not supported by
802 any event loop, that is, recursive invocation of a blocking
803 "->recv" is not allowed and the "recv" call will "croak" if such a
804 condition is detected. This requirement can be dropped by relying
805 on Coro::AnyEvent , which allows you to do a blocking "->recv" from
806 any thread that doesn't run the event loop itself. Coro::AnyEvent
807 is loaded automatically when Coro is used with AnyEvent, so code
808 does not need to do anything special to take advantage of that: any
809 code that would normally block your program because it calls
810 "recv", be executed in an "async" thread instead without blocking
811 other threads.
812
813 Not all event models support a blocking wait - some die in that
814 case (programs might want to do that to stay interactive), so if
815 you are using this from a module, never require a blocking wait.
816 Instead, let the caller decide whether the call will block or not
817 (for example, by coupling condition variables with some kind of
818 request results and supporting callbacks so the caller knows that
819 getting the result will not block, while still supporting blocking
820 waits if the caller so desires).
821
822 You can ensure that "->recv" never blocks by setting a callback and
823 only calling "->recv" from within that callback (or at a later
824 time). This will work even when the event loop does not support
825 blocking waits otherwise.
826
827 $bool = $cv->ready
828 Returns true when the condition is "true", i.e. whether "send" or
829 "croak" have been called.
830
831 $cb = $cv->cb ($cb->($cv))
832 This is a mutator function that returns the callback set (or
833 "undef" if not) and optionally replaces it before doing so.
834
835 The callback will be called when the condition becomes "true", i.e.
836 when "send" or "croak" are called, with the only argument being the
837 condition variable itself. If the condition is already true, the
838 callback is called immediately when it is set. Calling "recv"
839 inside the callback or at any later time is guaranteed not to
840 block.
841
842 Additionally, when the callback is invoked, it is also removed from
843 the condvar (reset to "undef"), so the condvar does not keep a
844 reference to the callback after invocation.
845
847 The available backend classes are (every class has its own manpage):
848
849 Backends that are autoprobed when no other event loop can be found.
850 EV is the preferred backend when no other event loop seems to be in
851 use. If EV is not installed, then AnyEvent will fall back to its
852 own pure-perl implementation, which is available everywhere as it
853 comes with AnyEvent itself.
854
855 AnyEvent::Impl::EV based on EV (interface to libev, best choice).
856 AnyEvent::Impl::Perl pure-perl AnyEvent::Loop, fast and portable.
857
858 Backends that are transparently being picked up when they are used.
859 These will be used if they are already loaded when the first
860 watcher is created, in which case it is assumed that the
861 application is using them. This means that AnyEvent will
862 automatically pick the right backend when the main program loads an
863 event module before anything starts to create watchers. Nothing
864 special needs to be done by the main program.
865
866 AnyEvent::Impl::Event based on Event, very stable, few glitches.
867 AnyEvent::Impl::Glib based on Glib, slow but very stable.
868 AnyEvent::Impl::Tk based on Tk, very broken.
869 AnyEvent::Impl::UV based on UV, innovated square wheels.
870 AnyEvent::Impl::EventLib based on Event::Lib, leaks memory and worse.
871 AnyEvent::Impl::POE based on POE, very slow, some limitations.
872 AnyEvent::Impl::Irssi used when running within irssi.
873 AnyEvent::Impl::IOAsync based on IO::Async.
874 AnyEvent::Impl::Cocoa based on Cocoa::EventLoop.
875 AnyEvent::Impl::FLTK based on FLTK (fltk 2 binding).
876
877 Backends with special needs.
878 Qt requires the Qt::Application to be instantiated first, but will
879 otherwise be picked up automatically. As long as the main program
880 instantiates the application before any AnyEvent watchers are
881 created, everything should just work.
882
883 AnyEvent::Impl::Qt based on Qt.
884
885 Event loops that are indirectly supported via other backends.
886 Some event loops can be supported via other modules:
887
888 There is no direct support for WxWidgets (Wx) or Prima.
889
890 WxWidgets has no support for watching file handles. However, you
891 can use WxWidgets through the POE adaptor, as POE has a Wx backend
892 that simply polls 20 times per second, which was considered to be
893 too horrible to even consider for AnyEvent.
894
895 Prima is not supported as nobody seems to be using it, but it has a
896 POE backend, so it can be supported through POE.
897
898 AnyEvent knows about both Prima and Wx, however, and will try to
899 load POE when detecting them, in the hope that POE will pick them
900 up, in which case everything will be automatic.
901
903 These are not normally required to use AnyEvent, but can be useful to
904 write AnyEvent extension modules.
905
906 $AnyEvent::MODEL
907 Contains "undef" until the first watcher is being created, before
908 the backend has been autodetected.
909
910 Afterwards it contains the event model that is being used, which is
911 the name of the Perl class implementing the model. This class is
912 usually one of the "AnyEvent::Impl::xxx" modules, but can be any
913 other class in the case AnyEvent has been extended at runtime (e.g.
914 in rxvt-unicode it will be "urxvt::anyevent").
915
916 AnyEvent::detect
917 Returns $AnyEvent::MODEL, forcing autodetection of the event model
918 if necessary. You should only call this function right before you
919 would have created an AnyEvent watcher anyway, that is, as late as
920 possible at runtime, and not e.g. during initialisation of your
921 module.
922
923 The effect of calling this function is as if a watcher had been
924 created (specifically, actions that happen "when the first watcher
925 is created" happen when calling detetc as well).
926
927 If you need to do some initialisation before AnyEvent watchers are
928 created, use "post_detect".
929
930 $guard = AnyEvent::post_detect { BLOCK }
931 Arranges for the code block to be executed as soon as the event
932 model is autodetected (or immediately if that has already
933 happened).
934
935 The block will be executed after the actual backend has been
936 detected ($AnyEvent::MODEL is set), so it is possible to do some
937 initialisation only when AnyEvent is actually initialised - see the
938 sources of AnyEvent::AIO to see how this is used.
939
940 The most common usage is to create some global watchers, without
941 forcing event module detection too early. For example,
942 AnyEvent::AIO creates and installs the global IO::AIO watcher in a
943 "post_detect" block to avoid autodetecting the event module at load
944 time.
945
946 If called in scalar or list context, then it creates and returns an
947 object that automatically removes the callback again when it is
948 destroyed (or "undef" when the hook was immediately executed). See
949 AnyEvent::AIO for a case where this is useful.
950
951 Example: Create a watcher for the IO::AIO module and store it in
952 $WATCHER, but do so only do so after the event loop is initialised.
953
954 our WATCHER;
955
956 my $guard = AnyEvent::post_detect {
957 $WATCHER = AnyEvent->io (fh => IO::AIO::poll_fileno, poll => 'r', cb => \&IO::AIO::poll_cb);
958 };
959
960 # the ||= is important in case post_detect immediately runs the block,
961 # as to not clobber the newly-created watcher. assigning both watcher and
962 # post_detect guard to the same variable has the advantage of users being
963 # able to just C<undef $WATCHER> if the watcher causes them grief.
964
965 $WATCHER ||= $guard;
966
967 @AnyEvent::post_detect
968 This is a lower level interface then "AnyEvent::post_detect" (the
969 function). This variable is mainly useful for modules that can do
970 something useful when AnyEvent is used and thus want to know when
971 it is initialised, but do not need to even load it by default. This
972 array provides the means to hook into AnyEvent passively, without
973 loading it.
974
975 Here is how it works: If there are any code references in this
976 array (you can "push" to it before or after loading AnyEvent), then
977 they will be called directly after the event loop has been chosen.
978
979 You should check $AnyEvent::MODEL before adding to this array,
980 though: if it is defined then the event loop has already been
981 detected, and the array will be ignored.
982
983 Best use "AnyEvent::post_detect { BLOCK }" when your application
984 allows it, as it takes care of these details.
985
986 Example: To load Coro::AnyEvent whenever Coro and AnyEvent are used
987 together, you could put this into Coro (this is the actual code
988 used by Coro to accomplish this):
989
990 if (defined $AnyEvent::MODEL) {
991 # AnyEvent already initialised, so load Coro::AnyEvent
992 require Coro::AnyEvent;
993 } else {
994 # AnyEvent not yet initialised, so make sure to load Coro::AnyEvent
995 # as soon as it is
996 push @AnyEvent::post_detect, sub { require Coro::AnyEvent };
997 }
998
999 AnyEvent::postpone { BLOCK }
1000 Arranges for the block to be executed as soon as possible, but not
1001 before the call itself returns. In practise, the block will be
1002 executed just before the event loop polls for new events, or
1003 shortly afterwards.
1004
1005 This function never returns anything (to make the "return postpone
1006 { ... }" idiom more useful.
1007
1008 To understand the usefulness of this function, consider a function
1009 that asynchronously does something for you and returns some
1010 transaction object or guard to let you cancel the operation. For
1011 example, "AnyEvent::Socket::tcp_connect":
1012
1013 # start a connection attempt unless one is active
1014 $self->{connect_guard} ||= AnyEvent::Socket::tcp_connect "www.example.net", 80, sub {
1015 delete $self->{connect_guard};
1016 ...
1017 };
1018
1019 Imagine that this function could instantly call the callback, for
1020 example, because it detects an obvious error such as a negative
1021 port number. Invoking the callback before the function returns
1022 causes problems however: the callback will be called and will try
1023 to delete the guard object. But since the function hasn't returned
1024 yet, there is nothing to delete. When the function eventually
1025 returns it will assign the guard object to
1026 "$self->{connect_guard}", where it will likely never be deleted, so
1027 the program thinks it is still trying to connect.
1028
1029 This is where "AnyEvent::postpone" should be used. Instead of
1030 calling the callback directly on error:
1031
1032 $cb->(undef), return # signal error to callback, BAD!
1033 if $some_error_condition;
1034
1035 It should use "postpone":
1036
1037 AnyEvent::postpone { $cb->(undef) }, return # signal error to callback, later
1038 if $some_error_condition;
1039
1040 AnyEvent::log $level, $msg[, @args]
1041 Log the given $msg at the given $level.
1042
1043 If AnyEvent::Log is not loaded then this function makes a simple
1044 test to see whether the message will be logged. If the test
1045 succeeds it will load AnyEvent::Log and call "AnyEvent::Log::log" -
1046 consequently, look at the AnyEvent::Log documentation for details.
1047
1048 If the test fails it will simply return. Right now this happens
1049 when a numerical loglevel is used and it is larger than the level
1050 specified via $ENV{PERL_ANYEVENT_VERBOSE}.
1051
1052 If you want to sprinkle loads of logging calls around your code,
1053 consider creating a logger callback with the
1054 "AnyEvent::Log::logger" function, which can reduce typing, codesize
1055 and can reduce the logging overhead enourmously.
1056
1057 AnyEvent::fh_block $filehandle
1058 AnyEvent::fh_unblock $filehandle
1059 Sets blocking or non-blocking behaviour for the given filehandle.
1060
1062 As a module author, you should "use AnyEvent" and call AnyEvent methods
1063 freely, but you should not load a specific event module or rely on it.
1064
1065 Be careful when you create watchers in the module body - AnyEvent will
1066 decide which event module to use as soon as the first method is called,
1067 so by calling AnyEvent in your module body you force the user of your
1068 module to load the event module first.
1069
1070 Never call "->recv" on a condition variable unless you know that the
1071 "->send" method has been called on it already. This is because it will
1072 stall the whole program, and the whole point of using events is to stay
1073 interactive.
1074
1075 It is fine, however, to call "->recv" when the user of your module
1076 requests it (i.e. if you create a http request object ad have a method
1077 called "results" that returns the results, it may call "->recv" freely,
1078 as the user of your module knows what she is doing. Always).
1079
1081 There will always be a single main program - the only place that should
1082 dictate which event model to use.
1083
1084 If the program is not event-based, it need not do anything special,
1085 even when it depends on a module that uses an AnyEvent. If the program
1086 itself uses AnyEvent, but does not care which event loop is used, all
1087 it needs to do is "use AnyEvent". In either case, AnyEvent will choose
1088 the best available loop implementation.
1089
1090 If the main program relies on a specific event model - for example, in
1091 Gtk2 programs you have to rely on the Glib module - you should load the
1092 event module before loading AnyEvent or any module that uses it:
1093 generally speaking, you should load it as early as possible. The reason
1094 is that modules might create watchers when they are loaded, and
1095 AnyEvent will decide on the event model to use as soon as it creates
1096 watchers, and it might choose the wrong one unless you load the correct
1097 one yourself.
1098
1099 You can chose to use a pure-perl implementation by loading the
1100 "AnyEvent::Loop" module, which gives you similar behaviour everywhere,
1101 but letting AnyEvent chose the model is generally better.
1102
1103 MAINLOOP EMULATION
1104 Sometimes (often for short test scripts, or even standalone programs
1105 who only want to use AnyEvent), you do not want to run a specific event
1106 loop.
1107
1108 In that case, you can use a condition variable like this:
1109
1110 AnyEvent->condvar->recv;
1111
1112 This has the effect of entering the event loop and looping forever.
1113
1114 Note that usually your program has some exit condition, in which case
1115 it is better to use the "traditional" approach of storing a condition
1116 variable somewhere, waiting for it, and sending it when the program
1117 should exit cleanly.
1118
1120 The following is a non-exhaustive list of additional modules that use
1121 AnyEvent as a client and can therefore be mixed easily with other
1122 AnyEvent modules and other event loops in the same program. Some of the
1123 modules come as part of AnyEvent, the others are available via CPAN
1124 (see <http://search.cpan.org/search?m=module&q=anyevent%3A%3A*> for a
1125 longer non-exhaustive list), and the list is heavily biased towards
1126 modules of the AnyEvent author himself :)
1127
1128 AnyEvent::Util (part of the AnyEvent distribution)
1129 Contains various utility functions that replace often-used blocking
1130 functions such as "inet_aton" with event/callback-based versions.
1131
1132 AnyEvent::Socket (part of the AnyEvent distribution)
1133 Provides various utility functions for (internet protocol) sockets,
1134 addresses and name resolution. Also functions to create non-
1135 blocking tcp connections or tcp servers, with IPv6 and SRV record
1136 support and more.
1137
1138 AnyEvent::Handle (part of the AnyEvent distribution)
1139 Provide read and write buffers, manages watchers for reads and
1140 writes, supports raw and formatted I/O, I/O queued and fully
1141 transparent and non-blocking SSL/TLS (via AnyEvent::TLS).
1142
1143 AnyEvent::DNS (part of the AnyEvent distribution)
1144 Provides rich asynchronous DNS resolver capabilities.
1145
1146 AnyEvent::HTTP, AnyEvent::IRC, AnyEvent::XMPP, AnyEvent::GPSD,
1147 AnyEvent::IGS, AnyEvent::FCP
1148 Implement event-based interfaces to the protocols of the same name
1149 (for the curious, IGS is the International Go Server and FCP is the
1150 Freenet Client Protocol).
1151
1152 AnyEvent::AIO (part of the AnyEvent distribution)
1153 Truly asynchronous (as opposed to non-blocking) I/O, should be in
1154 the toolbox of every event programmer. AnyEvent::AIO transparently
1155 fuses IO::AIO and AnyEvent together, giving AnyEvent access to
1156 event-based file I/O, and much more.
1157
1158 AnyEvent::Fork, AnyEvent::Fork::RPC, AnyEvent::Fork::Pool,
1159 AnyEvent::Fork::Remote
1160 These let you safely fork new subprocesses, either locally or
1161 remotely (e.g.v ia ssh), using some RPC protocol or not, without
1162 the limitations normally imposed by fork (AnyEvent works fine for
1163 example). Dynamically-resized worker pools are obviously included
1164 as well.
1165
1166 And they are quite tiny and fast as well - "abusing" AnyEvent::Fork
1167 just to exec external programs can easily beat using "fork" and
1168 "exec" (or even "system") in most programs.
1169
1170 AnyEvent::Filesys::Notify
1171 AnyEvent is good for non-blocking stuff, but it can't detect file
1172 or path changes (e.g. "watch this directory for new files", "watch
1173 this file for changes"). The AnyEvent::Filesys::Notify module
1174 promises to do just that in a portbale fashion, supporting inotify
1175 on GNU/Linux and some weird, without doubt broken, stuff on OS X to
1176 monitor files. It can fall back to blocking scans at regular
1177 intervals transparently on other platforms, so it's about as
1178 portable as it gets.
1179
1180 (I haven't used it myself, but it seems the biggest problem with it
1181 is it quite bad performance).
1182
1183 AnyEvent::DBI
1184 Executes DBI requests asynchronously in a proxy process for you,
1185 notifying you in an event-based way when the operation is finished.
1186
1187 AnyEvent::FastPing
1188 The fastest ping in the west.
1189
1190 Coro
1191 Has special support for AnyEvent via Coro::AnyEvent, which allows
1192 you to simply invert the flow control - don't call us, we will call
1193 you:
1194
1195 async {
1196 Coro::AnyEvent::sleep 5; # creates a 5s timer and waits for it
1197 print "5 seconds later!\n";
1198
1199 Coro::AnyEvent::readable *STDIN; # uses an I/O watcher
1200 my $line = <STDIN>; # works for ttys
1201
1202 AnyEvent::HTTP::http_get "url", Coro::rouse_cb;
1203 my ($body, $hdr) = Coro::rouse_wait;
1204 };
1205
1207 Starting with version 5.0, AnyEvent officially supports a second, much
1208 simpler, API that is designed to reduce the calling, typing and memory
1209 overhead by using function call syntax and a fixed number of
1210 parameters.
1211
1212 See the AE manpage for details.
1213
1215 In general, AnyEvent does not do any error handling - it relies on the
1216 caller to do that if required. The AnyEvent::Strict module (see also
1217 the "PERL_ANYEVENT_STRICT" environment variable, below) provides strict
1218 checking of all AnyEvent methods, however, which is highly useful
1219 during development.
1220
1221 As for exception handling (i.e. runtime errors and exceptions thrown
1222 while executing a callback), this is not only highly event-loop
1223 specific, but also not in any way wrapped by this module, as this is
1224 the job of the main program.
1225
1226 The pure perl event loop simply re-throws the exception (usually within
1227 "condvar->recv"), the Event and EV modules call "$Event/EV::DIED->()",
1228 Glib uses "install_exception_handler" and so on.
1229
1231 AnyEvent supports a number of environment variables that tune the
1232 runtime behaviour. They are usually evaluated when AnyEvent is loaded,
1233 initialised, or a submodule that uses them is loaded. Many of them also
1234 cause AnyEvent to load additional modules - for example,
1235 "PERL_ANYEVENT_DEBUG_WRAP" causes the AnyEvent::Debug module to be
1236 loaded.
1237
1238 All the environment variables documented here start with
1239 "PERL_ANYEVENT_", which is what AnyEvent considers its own namespace.
1240 Other modules are encouraged (but by no means required) to use
1241 "PERL_ANYEVENT_SUBMODULE" if they have registered the
1242 AnyEvent::Submodule namespace on CPAN, for any submodule. For example,
1243 AnyEvent::HTTP could be expected to use "PERL_ANYEVENT_HTTP_PROXY" (it
1244 should not access env variables starting with "AE_", see below).
1245
1246 All variables can also be set via the "AE_" prefix, that is, instead of
1247 setting "PERL_ANYEVENT_VERBOSE" you can also set "AE_VERBOSE". In case
1248 there is a clash btween anyevent and another program that uses
1249 "AE_something" you can set the corresponding "PERL_ANYEVENT_something"
1250 variable to the empty string, as those variables take precedence.
1251
1252 When AnyEvent is first loaded, it copies all "AE_xxx" env variables to
1253 their "PERL_ANYEVENT_xxx" counterpart unless that variable already
1254 exists. If taint mode is on, then AnyEvent will remove all environment
1255 variables starting with "PERL_ANYEVENT_" from %ENV (or replace them
1256 with "undef" or the empty string, if the corresaponding "AE_" variable
1257 is set).
1258
1259 The exact algorithm is currently:
1260
1261 1. if taint mode enabled, delete all PERL_ANYEVENT_xyz variables from %ENV
1262 2. copy over AE_xyz to PERL_ANYEVENT_xyz unless the latter alraedy exists
1263 3. if taint mode enabled, set all PERL_ANYEVENT_xyz variables to undef.
1264
1265 This ensures that child processes will not see the "AE_" variables.
1266
1267 The following environment variables are currently known to AnyEvent:
1268
1269 "PERL_ANYEVENT_VERBOSE"
1270 By default, AnyEvent will log messages with loglevel 4 ("error") or
1271 higher (see AnyEvent::Log). You can set this environment variable
1272 to a numerical loglevel to make AnyEvent more (or less) talkative.
1273
1274 If you want to do more than just set the global logging level you
1275 should have a look at "PERL_ANYEVENT_LOG", which allows much more
1276 complex specifications.
1277
1278 When set to 0 ("off"), then no messages whatsoever will be logged
1279 with everything else at defaults.
1280
1281 When set to 5 or higher ("warn"), AnyEvent warns about unexpected
1282 conditions, such as not being able to load the event model
1283 specified by "PERL_ANYEVENT_MODEL", or a guard callback throwing an
1284 exception - this is the minimum recommended level for use during
1285 development.
1286
1287 When set to 7 or higher (info), AnyEvent reports which event model
1288 it chooses.
1289
1290 When set to 8 or higher (debug), then AnyEvent will report extra
1291 information on which optional modules it loads and how it
1292 implements certain features.
1293
1294 "PERL_ANYEVENT_LOG"
1295 Accepts rather complex logging specifications. For example, you
1296 could log all "debug" messages of some module to stderr, warnings
1297 and above to stderr, and errors and above to syslog, with:
1298
1299 PERL_ANYEVENT_LOG=Some::Module=debug,+log:filter=warn,+%syslog:%syslog=error,syslog
1300
1301 For the rather extensive details, see AnyEvent::Log.
1302
1303 This variable is evaluated when AnyEvent (or AnyEvent::Log) is
1304 loaded, so will take effect even before AnyEvent has initialised
1305 itself.
1306
1307 Note that specifying this environment variable causes the
1308 AnyEvent::Log module to be loaded, while "PERL_ANYEVENT_VERBOSE"
1309 does not, so only using the latter saves a few hundred kB of memory
1310 unless a module explicitly needs the extra features of
1311 AnyEvent::Log.
1312
1313 "PERL_ANYEVENT_STRICT"
1314 AnyEvent does not do much argument checking by default, as thorough
1315 argument checking is very costly. Setting this variable to a true
1316 value will cause AnyEvent to load "AnyEvent::Strict" and then to
1317 thoroughly check the arguments passed to most method calls. If it
1318 finds any problems, it will croak.
1319
1320 In other words, enables "strict" mode.
1321
1322 Unlike "use strict" (or its modern cousin, "use common::sense", it
1323 is definitely recommended to keep it off in production. Keeping
1324 "PERL_ANYEVENT_STRICT=1" in your environment while developing
1325 programs can be very useful, however.
1326
1327 "PERL_ANYEVENT_DEBUG_SHELL"
1328 If this env variable is nonempty, then its contents will be
1329 interpreted by "AnyEvent::Socket::parse_hostport" and
1330 "AnyEvent::Debug::shell" (after replacing every occurance of $$ by
1331 the process pid). The shell object is saved in
1332 $AnyEvent::Debug::SHELL.
1333
1334 This happens when the first watcher is created.
1335
1336 For example, to bind a debug shell on a unix domain socket in
1337 /tmp/debug<pid>.sock, you could use this:
1338
1339 PERL_ANYEVENT_DEBUG_SHELL=/tmp/debug\$\$.sock perlprog
1340 # connect with e.g.: socat readline /tmp/debug123.sock
1341
1342 Or to bind to tcp port 4545 on localhost:
1343
1344 PERL_ANYEVENT_DEBUG_SHELL=127.0.0.1:4545 perlprog
1345 # connect with e.g.: telnet localhost 4545
1346
1347 Note that creating sockets in /tmp or on localhost is very unsafe
1348 on multiuser systems.
1349
1350 "PERL_ANYEVENT_DEBUG_WRAP"
1351 Can be set to 0, 1 or 2 and enables wrapping of all watchers for
1352 debugging purposes. See "AnyEvent::Debug::wrap" for details.
1353
1354 "PERL_ANYEVENT_MODEL"
1355 This can be used to specify the event model to be used by AnyEvent,
1356 before auto detection and -probing kicks in.
1357
1358 It normally is a string consisting entirely of ASCII letters (e.g.
1359 "EV" or "IOAsync"). The string "AnyEvent::Impl::" gets prepended
1360 and the resulting module name is loaded and - if the load was
1361 successful - used as event model backend. If it fails to load then
1362 AnyEvent will proceed with auto detection and -probing.
1363
1364 If the string ends with "::" instead (e.g. "AnyEvent::Impl::EV::")
1365 then nothing gets prepended and the module name is used as-is
1366 (hint: "::" at the end of a string designates a module name and
1367 quotes it appropriately).
1368
1369 For example, to force the pure perl model (AnyEvent::Loop::Perl)
1370 you could start your program like this:
1371
1372 PERL_ANYEVENT_MODEL=Perl perl ...
1373
1374 "PERL_ANYEVENT_IO_MODEL"
1375 The current file I/O model - see AnyEvent::IO for more info.
1376
1377 At the moment, only "Perl" (small, pure-perl, synchronous) and
1378 "IOAIO" (truly asynchronous) are supported. The default is "IOAIO"
1379 if AnyEvent::AIO can be loaded, otherwise it is "Perl".
1380
1381 "PERL_ANYEVENT_PROTOCOLS"
1382 Used by both AnyEvent::DNS and AnyEvent::Socket to determine
1383 preferences for IPv4 or IPv6. The default is unspecified (and might
1384 change, or be the result of auto probing).
1385
1386 Must be set to a comma-separated list of protocols or address
1387 families, current supported: "ipv4" and "ipv6". Only protocols
1388 mentioned will be used, and preference will be given to protocols
1389 mentioned earlier in the list.
1390
1391 This variable can effectively be used for denial-of-service attacks
1392 against local programs (e.g. when setuid), although the impact is
1393 likely small, as the program has to handle connection and other
1394 failures anyways.
1395
1396 Examples: "PERL_ANYEVENT_PROTOCOLS=ipv4,ipv6" - prefer IPv4 over
1397 IPv6, but support both and try to use both.
1398 "PERL_ANYEVENT_PROTOCOLS=ipv4" - only support IPv4, never try to
1399 resolve or contact IPv6 addresses.
1400 "PERL_ANYEVENT_PROTOCOLS=ipv6,ipv4" support either IPv4 or IPv6,
1401 but prefer IPv6 over IPv4.
1402
1403 "PERL_ANYEVENT_HOSTS"
1404 This variable, if specified, overrides the /etc/hosts file used by
1405 AnyEvent::Socket"::resolve_sockaddr", i.e. hosts aliases will be
1406 read from that file instead.
1407
1408 "PERL_ANYEVENT_EDNS0"
1409 Used by AnyEvent::DNS to decide whether to use the EDNS0 extension
1410 for DNS. This extension is generally useful to reduce DNS traffic,
1411 especially when DNSSEC is involved, but some (broken) firewalls
1412 drop such DNS packets, which is why it is off by default.
1413
1414 Setting this variable to 1 will cause AnyEvent::DNS to announce
1415 EDNS0 in its DNS requests.
1416
1417 "PERL_ANYEVENT_MAX_FORKS"
1418 The maximum number of child processes that
1419 "AnyEvent::Util::fork_call" will create in parallel.
1420
1421 "PERL_ANYEVENT_MAX_OUTSTANDING_DNS"
1422 The default value for the "max_outstanding" parameter for the
1423 default DNS resolver - this is the maximum number of parallel DNS
1424 requests that are sent to the DNS server.
1425
1426 "PERL_ANYEVENT_MAX_SIGNAL_LATENCY"
1427 Perl has inherently racy signal handling (you can basically choose
1428 between losing signals and memory corruption) - pure perl event
1429 loops (including "AnyEvent::Loop", when "Async::Interrupt" isn't
1430 available) therefore have to poll regularly to avoid losing
1431 signals.
1432
1433 Some event loops are racy, but don't poll regularly, and some event
1434 loops are written in C but are still racy. For those event loops,
1435 AnyEvent installs a timer that regularly wakes up the event loop.
1436
1437 By default, the interval for this timer is 10 seconds, but you can
1438 override this delay with this environment variable (or by setting
1439 the $AnyEvent::MAX_SIGNAL_LATENCY variable before creating signal
1440 watchers).
1441
1442 Lower values increase CPU (and energy) usage, higher values can
1443 introduce long delays when reaping children or waiting for signals.
1444
1445 The AnyEvent::Async module, if available, will be used to avoid
1446 this polling (with most event loops).
1447
1448 "PERL_ANYEVENT_RESOLV_CONF"
1449 The absolute path to a resolv.conf-style file to use instead of
1450 /etc/resolv.conf (or the OS-specific configuration) in the default
1451 resolver, or the empty string to select the default configuration.
1452
1453 "PERL_ANYEVENT_CA_FILE", "PERL_ANYEVENT_CA_PATH".
1454 When neither "ca_file" nor "ca_path" was specified during
1455 AnyEvent::TLS context creation, and either of these environment
1456 variables are nonempty, they will be used to specify CA certificate
1457 locations instead of a system-dependent default.
1458
1459 "PERL_ANYEVENT_AVOID_GUARD" and "PERL_ANYEVENT_AVOID_ASYNC_INTERRUPT"
1460 When these are set to 1, then the respective modules are not
1461 loaded. Mostly good for testing AnyEvent itself.
1462
1464 This is an advanced topic that you do not normally need to use AnyEvent
1465 in a module. This section is only of use to event loop authors who want
1466 to provide AnyEvent compatibility.
1467
1468 If you need to support another event library which isn't directly
1469 supported by AnyEvent, you can supply your own interface to it by
1470 pushing, before the first watcher gets created, the package name of the
1471 event module and the package name of the interface to use onto
1472 @AnyEvent::REGISTRY. You can do that before and even without loading
1473 AnyEvent, so it is reasonably cheap.
1474
1475 Example:
1476
1477 push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
1478
1479 This tells AnyEvent to (literally) use the "urxvt::anyevent::"
1480 package/class when it finds the "urxvt" package/module is already
1481 loaded.
1482
1483 When AnyEvent is loaded and asked to find a suitable event model, it
1484 will first check for the presence of urxvt by trying to "use" the
1485 "urxvt::anyevent" module.
1486
1487 The class should provide implementations for all watcher types. See
1488 AnyEvent::Impl::EV (source code), AnyEvent::Impl::Glib (Source code)
1489 and so on for actual examples. Use "perldoc -m AnyEvent::Impl::Glib" to
1490 see the sources.
1491
1492 If you don't provide "signal" and "child" watchers than AnyEvent will
1493 provide suitable (hopefully) replacements.
1494
1495 The above example isn't fictitious, the rxvt-unicode (a.k.a. urxvt)
1496 terminal emulator uses the above line as-is. An interface isn't
1497 included in AnyEvent because it doesn't make sense outside the embedded
1498 interpreter inside rxvt-unicode, and it is updated and maintained as
1499 part of the rxvt-unicode distribution.
1500
1501 rxvt-unicode also cheats a bit by not providing blocking access to
1502 condition variables: code blocking while waiting for a condition will
1503 "die". This still works with most modules/usages, and blocking calls
1504 must not be done in an interactive application, so it makes sense.
1505
1507 The following program uses an I/O watcher to read data from STDIN, a
1508 timer to display a message once per second, and a condition variable to
1509 quit the program when the user enters quit:
1510
1511 use AnyEvent;
1512
1513 my $cv = AnyEvent->condvar;
1514
1515 my $io_watcher = AnyEvent->io (
1516 fh => \*STDIN,
1517 poll => 'r',
1518 cb => sub {
1519 warn "io event <$_[0]>\n"; # will always output <r>
1520 chomp (my $input = <STDIN>); # read a line
1521 warn "read: $input\n"; # output what has been read
1522 $cv->send if $input =~ /^q/i; # quit program if /^q/i
1523 },
1524 );
1525
1526 my $time_watcher = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1527 warn "timeout\n"; # print 'timeout' at most every second
1528 });
1529
1530 $cv->recv; # wait until user enters /^q/i
1531
1533 Consider the Net::FCP module. It features (among others) the following
1534 API calls, which are to freenet what HTTP GET requests are to http:
1535
1536 my $data = $fcp->client_get ($url); # blocks
1537
1538 my $transaction = $fcp->txn_client_get ($url); # does not block
1539 $transaction->cb ( sub { ... } ); # set optional result callback
1540 my $data = $transaction->result; # possibly blocks
1541
1542 The "client_get" method works like "LWP::Simple::get": it requests the
1543 given URL and waits till the data has arrived. It is defined to be:
1544
1545 sub client_get { $_[0]->txn_client_get ($_[1])->result }
1546
1547 And in fact is automatically generated. This is the blocking API of
1548 Net::FCP, and it works as simple as in any other, similar, module.
1549
1550 More complicated is "txn_client_get": It only creates a transaction
1551 (completion, result, ...) object and initiates the transaction.
1552
1553 my $txn = bless { }, Net::FCP::Txn::;
1554
1555 It also creates a condition variable that is used to signal the
1556 completion of the request:
1557
1558 $txn->{finished} = AnyAvent->condvar;
1559
1560 It then creates a socket in non-blocking mode.
1561
1562 socket $txn->{fh}, ...;
1563 fcntl $txn->{fh}, F_SETFL, O_NONBLOCK;
1564 connect $txn->{fh}, ...
1565 and !$!{EWOULDBLOCK}
1566 and !$!{EINPROGRESS}
1567 and Carp::croak "unable to connect: $!\n";
1568
1569 Then it creates a write-watcher which gets called whenever an error
1570 occurs or the connection succeeds:
1571
1572 $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w });
1573
1574 And returns this transaction object. The "fh_ready_w" callback gets
1575 called as soon as the event loop detects that the socket is ready for
1576 writing.
1577
1578 The "fh_ready_w" method makes the socket blocking again, writes the
1579 request data and replaces the watcher by a read watcher (waiting for
1580 reply data). The actual code is more complicated, but that doesn't
1581 matter for this example:
1582
1583 fcntl $txn->{fh}, F_SETFL, 0;
1584 syswrite $txn->{fh}, $txn->{request}
1585 or die "connection or write error";
1586 $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r });
1587
1588 Again, "fh_ready_r" waits till all data has arrived, and then stores
1589 the result and signals any possible waiters that the request has
1590 finished:
1591
1592 sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf};
1593
1594 if (end-of-file or data complete) {
1595 $txn->{result} = $txn->{buf};
1596 $txn->{finished}->send;
1597 $txb->{cb}->($txn) of $txn->{cb}; # also call callback
1598 }
1599
1600 The "result" method, finally, just waits for the finished signal (if
1601 the request was already finished, it doesn't wait, of course, and
1602 returns the data:
1603
1604 $txn->{finished}->recv;
1605 return $txn->{result};
1606
1607 The actual code goes further and collects all errors ("die"s,
1608 exceptions) that occurred during request processing. The "result"
1609 method detects whether an exception as thrown (it is stored inside the
1610 $txn object) and just throws the exception, which means connection
1611 errors and other problems get reported to the code that tries to use
1612 the result, not in a random callback.
1613
1614 All of this enables the following usage styles:
1615
1616 1. Blocking:
1617
1618 my $data = $fcp->client_get ($url);
1619
1620 2. Blocking, but running in parallel:
1621
1622 my @datas = map $_->result,
1623 map $fcp->txn_client_get ($_),
1624 @urls;
1625
1626 Both blocking examples work without the module user having to know
1627 anything about events.
1628
1629 3a. Event-based in a main program, using any supported event module:
1630
1631 use EV;
1632
1633 $fcp->txn_client_get ($url)->cb (sub {
1634 my $txn = shift;
1635 my $data = $txn->result;
1636 ...
1637 });
1638
1639 EV::run;
1640
1641 3b. The module user could use AnyEvent, too:
1642
1643 use AnyEvent;
1644
1645 my $quit = AnyEvent->condvar;
1646
1647 $fcp->txn_client_get ($url)->cb (sub {
1648 ...
1649 $quit->send;
1650 });
1651
1652 $quit->recv;
1653
1655 To give you an idea of the performance and overheads that AnyEvent adds
1656 over the event loops themselves and to give you an impression of the
1657 speed of various event loops I prepared some benchmarks.
1658
1659 BENCHMARKING ANYEVENT OVERHEAD
1660 Here is a benchmark of various supported event models used natively and
1661 through AnyEvent. The benchmark creates a lot of timers (with a zero
1662 timeout) and I/O watchers (watching STDOUT, a pty, to become writable,
1663 which it is), lets them fire exactly once and destroys them again.
1664
1665 Source code for this benchmark is found as eg/bench in the AnyEvent
1666 distribution. It uses the AE interface, which makes a real difference
1667 for the EV and Perl backends only.
1668
1669 Explanation of the columns
1670
1671 watcher is the number of event watchers created/destroyed. Since
1672 different event models feature vastly different performances, each
1673 event loop was given a number of watchers so that overall runtime is
1674 acceptable and similar between tested event loop (and keep them from
1675 crashing): Glib would probably take thousands of years if asked to
1676 process the same number of watchers as EV in this benchmark.
1677
1678 bytes is the number of bytes (as measured by the resident set size,
1679 RSS) consumed by each watcher. This method of measuring captures both C
1680 and Perl-based overheads.
1681
1682 create is the time, in microseconds (millionths of seconds), that it
1683 takes to create a single watcher. The callback is a closure shared
1684 between all watchers, to avoid adding memory overhead. That means
1685 closure creation and memory usage is not included in the figures.
1686
1687 invoke is the time, in microseconds, used to invoke a simple callback.
1688 The callback simply counts down a Perl variable and after it was
1689 invoked "watcher" times, it would "->send" a condvar once to signal the
1690 end of this phase.
1691
1692 destroy is the time, in microseconds, that it takes to destroy a single
1693 watcher.
1694
1695 Results
1696
1697 name watchers bytes create invoke destroy comment
1698 EV/EV 100000 223 0.47 0.43 0.27 EV native interface
1699 EV/Any 100000 223 0.48 0.42 0.26 EV + AnyEvent watchers
1700 Coro::EV/Any 100000 223 0.47 0.42 0.26 coroutines + Coro::Signal
1701 Perl/Any 100000 431 2.70 0.74 0.92 pure perl implementation
1702 Event/Event 16000 516 31.16 31.84 0.82 Event native interface
1703 Event/Any 16000 1203 42.61 34.79 1.80 Event + AnyEvent watchers
1704 IOAsync/Any 16000 1911 41.92 27.45 16.81 via IO::Async::Loop::IO_Poll
1705 IOAsync/Any 16000 1726 40.69 26.37 15.25 via IO::Async::Loop::Epoll
1706 Glib/Any 16000 1118 89.00 12.57 51.17 quadratic behaviour
1707 Tk/Any 2000 1346 20.96 10.75 8.00 SEGV with >> 2000 watchers
1708 POE/Any 2000 6951 108.97 795.32 14.24 via POE::Loop::Event
1709 POE/Any 2000 6648 94.79 774.40 575.51 via POE::Loop::Select
1710
1711 Discussion
1712
1713 The benchmark does not measure scalability of the event loop very well.
1714 For example, a select-based event loop (such as the pure perl one) can
1715 never compete with an event loop that uses epoll when the number of
1716 file descriptors grows high. In this benchmark, all events become ready
1717 at the same time, so select/poll-based implementations get an unnatural
1718 speed boost.
1719
1720 Also, note that the number of watchers usually has a nonlinear effect
1721 on overall speed, that is, creating twice as many watchers doesn't take
1722 twice the time - usually it takes longer. This puts event loops tested
1723 with a higher number of watchers at a disadvantage.
1724
1725 To put the range of results into perspective, consider that on the
1726 benchmark machine, handling an event takes roughly 1600 CPU cycles with
1727 EV, 3100 CPU cycles with AnyEvent's pure perl loop and almost 3000000
1728 CPU cycles with POE.
1729
1730 "EV" is the sole leader regarding speed and memory use, which are both
1731 maximal/minimal, respectively. When using the AE API there is zero
1732 overhead (when going through the AnyEvent API create is about 5-6 times
1733 slower, with other times being equal, so still uses far less memory
1734 than any other event loop and is still faster than Event natively).
1735
1736 The pure perl implementation is hit in a few sweet spots (both the
1737 constant timeout and the use of a single fd hit optimisations in the
1738 perl interpreter and the backend itself). Nevertheless this shows that
1739 it adds very little overhead in itself. Like any select-based backend
1740 its performance becomes really bad with lots of file descriptors (and
1741 few of them active), of course, but this was not subject of this
1742 benchmark.
1743
1744 The "Event" module has a relatively high setup and callback invocation
1745 cost, but overall scores in on the third place.
1746
1747 "IO::Async" performs admirably well, about on par with "Event", even
1748 when using its pure perl backend.
1749
1750 "Glib"'s memory usage is quite a bit higher, but it features a faster
1751 callback invocation and overall ends up in the same class as "Event".
1752 However, Glib scales extremely badly, doubling the number of watchers
1753 increases the processing time by more than a factor of four, making it
1754 completely unusable when using larger numbers of watchers (note that
1755 only a single file descriptor was used in the benchmark, so
1756 inefficiencies of "poll" do not account for this).
1757
1758 The "Tk" adaptor works relatively well. The fact that it crashes with
1759 more than 2000 watchers is a big setback, however, as correctness takes
1760 precedence over speed. Nevertheless, its performance is surprising, as
1761 the file descriptor is dup()ed for each watcher. This shows that the
1762 dup() employed by some adaptors is not a big performance issue (it does
1763 incur a hidden memory cost inside the kernel which is not reflected in
1764 the figures above).
1765
1766 "POE", regardless of underlying event loop (whether using its pure perl
1767 select-based backend or the Event module, the POE-EV backend couldn't
1768 be tested because it wasn't working) shows abysmal performance and
1769 memory usage with AnyEvent: Watchers use almost 30 times as much memory
1770 as EV watchers, and 10 times as much memory as Event (the high memory
1771 requirements are caused by requiring a session for each watcher).
1772 Watcher invocation speed is almost 900 times slower than with
1773 AnyEvent's pure perl implementation.
1774
1775 The design of the POE adaptor class in AnyEvent can not really account
1776 for the performance issues, though, as session creation overhead is
1777 small compared to execution of the state machine, which is coded pretty
1778 optimally within AnyEvent::Impl::POE (and while everybody agrees that
1779 using multiple sessions is not a good approach, especially regarding
1780 memory usage, even the author of POE could not come up with a faster
1781 design).
1782
1783 Summary
1784
1785 · Using EV through AnyEvent is faster than any other event loop (even
1786 when used without AnyEvent), but most event loops have acceptable
1787 performance with or without AnyEvent.
1788
1789 · The overhead AnyEvent adds is usually much smaller than the
1790 overhead of the actual event loop, only with extremely fast event
1791 loops such as EV does AnyEvent add significant overhead.
1792
1793 · You should avoid POE like the plague if you want performance or
1794 reasonable memory usage.
1795
1796 BENCHMARKING THE LARGE SERVER CASE
1797 This benchmark actually benchmarks the event loop itself. It works by
1798 creating a number of "servers": each server consists of a socket pair,
1799 a timeout watcher that gets reset on activity (but never fires), and an
1800 I/O watcher waiting for input on one side of the socket. Each time the
1801 socket watcher reads a byte it will write that byte to a random other
1802 "server".
1803
1804 The effect is that there will be a lot of I/O watchers, only part of
1805 which are active at any one point (so there is a constant number of
1806 active fds for each loop iteration, but which fds these are is random).
1807 The timeout is reset each time something is read because that reflects
1808 how most timeouts work (and puts extra pressure on the event loops).
1809
1810 In this benchmark, we use 10000 socket pairs (20000 sockets), of which
1811 100 (1%) are active. This mirrors the activity of large servers with
1812 many connections, most of which are idle at any one point in time.
1813
1814 Source code for this benchmark is found as eg/bench2 in the AnyEvent
1815 distribution. It uses the AE interface, which makes a real difference
1816 for the EV and Perl backends only.
1817
1818 Explanation of the columns
1819
1820 sockets is the number of sockets, and twice the number of "servers" (as
1821 each server has a read and write socket end).
1822
1823 create is the time it takes to create a socket pair (which is
1824 nontrivial) and two watchers: an I/O watcher and a timeout watcher.
1825
1826 request, the most important value, is the time it takes to handle a
1827 single "request", that is, reading the token from the pipe and
1828 forwarding it to another server. This includes deleting the old timeout
1829 and creating a new one that moves the timeout into the future.
1830
1831 Results
1832
1833 name sockets create request
1834 EV 20000 62.66 7.99
1835 Perl 20000 68.32 32.64
1836 IOAsync 20000 174.06 101.15 epoll
1837 IOAsync 20000 174.67 610.84 poll
1838 Event 20000 202.69 242.91
1839 Glib 20000 557.01 1689.52
1840 POE 20000 341.54 12086.32 uses POE::Loop::Event
1841
1842 Discussion
1843
1844 This benchmark does measure scalability and overall performance of the
1845 particular event loop.
1846
1847 EV is again fastest. Since it is using epoll on my system, the setup
1848 time is relatively high, though.
1849
1850 Perl surprisingly comes second. It is much faster than the C-based
1851 event loops Event and Glib.
1852
1853 IO::Async performs very well when using its epoll backend, and still
1854 quite good compared to Glib when using its pure perl backend.
1855
1856 Event suffers from high setup time as well (look at its code and you
1857 will understand why). Callback invocation also has a high overhead
1858 compared to the "$_->() for .."-style loop that the Perl event loop
1859 uses. Event uses select or poll in basically all documented
1860 configurations.
1861
1862 Glib is hit hard by its quadratic behaviour w.r.t. many watchers. It
1863 clearly fails to perform with many filehandles or in busy servers.
1864
1865 POE is still completely out of the picture, taking over 1000 times as
1866 long as EV, and over 100 times as long as the Perl implementation, even
1867 though it uses a C-based event loop in this case.
1868
1869 Summary
1870
1871 · The pure perl implementation performs extremely well.
1872
1873 · Avoid Glib or POE in large projects where performance matters.
1874
1875 BENCHMARKING SMALL SERVERS
1876 While event loops should scale (and select-based ones do not...) even
1877 to large servers, most programs we (or I :) actually write have only a
1878 few I/O watchers.
1879
1880 In this benchmark, I use the same benchmark program as in the large
1881 server case, but it uses only eight "servers", of which three are
1882 active at any one time. This should reflect performance for a small
1883 server relatively well.
1884
1885 The columns are identical to the previous table.
1886
1887 Results
1888
1889 name sockets create request
1890 EV 16 20.00 6.54
1891 Perl 16 25.75 12.62
1892 Event 16 81.27 35.86
1893 Glib 16 32.63 15.48
1894 POE 16 261.87 276.28 uses POE::Loop::Event
1895
1896 Discussion
1897
1898 The benchmark tries to test the performance of a typical small server.
1899 While knowing how various event loops perform is interesting, keep in
1900 mind that their overhead in this case is usually not as important, due
1901 to the small absolute number of watchers (that is, you need efficiency
1902 and speed most when you have lots of watchers, not when you only have a
1903 few of them).
1904
1905 EV is again fastest.
1906
1907 Perl again comes second. It is noticeably faster than the C-based event
1908 loops Event and Glib, although the difference is too small to really
1909 matter.
1910
1911 POE also performs much better in this case, but is is still far behind
1912 the others.
1913
1914 Summary
1915
1916 · C-based event loops perform very well with small number of
1917 watchers, as the management overhead dominates.
1918
1919 THE IO::Lambda BENCHMARK
1920 Recently I was told about the benchmark in the IO::Lambda manpage,
1921 which could be misinterpreted to make AnyEvent look bad. In fact, the
1922 benchmark simply compares IO::Lambda with POE, and IO::Lambda looks
1923 better (which shouldn't come as a surprise to anybody). As such, the
1924 benchmark is fine, and mostly shows that the AnyEvent backend from
1925 IO::Lambda isn't very optimal. But how would AnyEvent compare when used
1926 without the extra baggage? To explore this, I wrote the equivalent
1927 benchmark for AnyEvent.
1928
1929 The benchmark itself creates an echo-server, and then, for 500 times,
1930 connects to the echo server, sends a line, waits for the reply, and
1931 then creates the next connection. This is a rather bad benchmark, as it
1932 doesn't test the efficiency of the framework or much non-blocking I/O,
1933 but it is a benchmark nevertheless.
1934
1935 name runtime
1936 Lambda/select 0.330 sec
1937 + optimized 0.122 sec
1938 Lambda/AnyEvent 0.327 sec
1939 + optimized 0.138 sec
1940 Raw sockets/select 0.077 sec
1941 POE/select, components 0.662 sec
1942 POE/select, raw sockets 0.226 sec
1943 POE/select, optimized 0.404 sec
1944
1945 AnyEvent/select/nb 0.085 sec
1946 AnyEvent/EV/nb 0.068 sec
1947 +state machine 0.134 sec
1948
1949 The benchmark is also a bit unfair (my fault): the IO::Lambda/POE
1950 benchmarks actually make blocking connects and use 100% blocking I/O,
1951 defeating the purpose of an event-based solution. All of the newly
1952 written AnyEvent benchmarks use 100% non-blocking connects (using
1953 AnyEvent::Socket::tcp_connect and the asynchronous pure perl DNS
1954 resolver), so AnyEvent is at a disadvantage here, as non-blocking
1955 connects generally require a lot more bookkeeping and event handling
1956 than blocking connects (which involve a single syscall only).
1957
1958 The last AnyEvent benchmark additionally uses AnyEvent::Handle, which
1959 offers similar expressive power as POE and IO::Lambda, using
1960 conventional Perl syntax. This means that both the echo server and the
1961 client are 100% non-blocking, further placing it at a disadvantage.
1962
1963 As you can see, the AnyEvent + EV combination even beats the hand-
1964 optimised "raw sockets benchmark", while AnyEvent + its pure perl
1965 backend easily beats IO::Lambda and POE.
1966
1967 And even the 100% non-blocking version written using the high-level
1968 (and slow :) AnyEvent::Handle abstraction beats both POE and IO::Lambda
1969 higher level ("unoptimised") abstractions by a large margin, even
1970 though it does all of DNS, tcp-connect and socket I/O in a non-blocking
1971 way.
1972
1973 The two AnyEvent benchmarks programs can be found as eg/ae0.pl and
1974 eg/ae2.pl in the AnyEvent distribution, the remaining benchmarks are
1975 part of the IO::Lambda distribution and were used without any changes.
1976
1978 AnyEvent currently installs handlers for these signals:
1979
1980 SIGCHLD
1981 A handler for "SIGCHLD" is installed by AnyEvent's child watcher
1982 emulation for event loops that do not support them natively. Also,
1983 some event loops install a similar handler.
1984
1985 Additionally, when AnyEvent is loaded and SIGCHLD is set to IGNORE,
1986 then AnyEvent will reset it to default, to avoid losing child exit
1987 statuses.
1988
1989 SIGPIPE
1990 A no-op handler is installed for "SIGPIPE" when $SIG{PIPE} is
1991 "undef" when AnyEvent gets loaded.
1992
1993 The rationale for this is that AnyEvent users usually do not really
1994 depend on SIGPIPE delivery (which is purely an optimisation for
1995 shell use, or badly-written programs), but "SIGPIPE" can cause
1996 spurious and rare program exits as a lot of people do not expect
1997 "SIGPIPE" when writing to some random socket.
1998
1999 The rationale for installing a no-op handler as opposed to ignoring
2000 it is that this way, the handler will be restored to defaults on
2001 exec.
2002
2003 Feel free to install your own handler, or reset it to defaults.
2004
2006 One of AnyEvent's main goals is to be 100% Pure-Perl(tm): only perl
2007 (and its built-in modules) are required to use it.
2008
2009 That does not mean that AnyEvent won't take advantage of some
2010 additional modules if they are installed.
2011
2012 This section explains which additional modules will be used, and how
2013 they affect AnyEvent's operation.
2014
2015 Async::Interrupt
2016 This slightly arcane module is used to implement fast signal
2017 handling: To my knowledge, there is no way to do completely race-
2018 free and quick signal handling in pure perl. To ensure that signals
2019 still get delivered, AnyEvent will start an interval timer to wake
2020 up perl (and catch the signals) with some delay (default is 10
2021 seconds, look for $AnyEvent::MAX_SIGNAL_LATENCY).
2022
2023 If this module is available, then it will be used to implement
2024 signal catching, which means that signals will not be delayed, and
2025 the event loop will not be interrupted regularly, which is more
2026 efficient (and good for battery life on laptops).
2027
2028 This affects not just the pure-perl event loop, but also other
2029 event loops that have no signal handling on their own (e.g. Glib,
2030 Tk, Qt).
2031
2032 Some event loops (POE, Event, Event::Lib) offer signal watchers
2033 natively, and either employ their own workarounds (POE) or use
2034 AnyEvent's workaround (using $AnyEvent::MAX_SIGNAL_LATENCY).
2035 Installing Async::Interrupt does nothing for those backends.
2036
2037 EV This module isn't really "optional", as it is simply one of the
2038 backend event loops that AnyEvent can use. However, it is simply
2039 the best event loop available in terms of features, speed and
2040 stability: It supports the AnyEvent API optimally, implements all
2041 the watcher types in XS, does automatic timer adjustments even when
2042 no monotonic clock is available, can take avdantage of advanced
2043 kernel interfaces such as "epoll" and "kqueue", and is the fastest
2044 backend by far. You can even embed Glib/Gtk2 in it (or vice versa,
2045 see EV::Glib and Glib::EV).
2046
2047 If you only use backends that rely on another event loop (e.g.
2048 "Tk"), then this module will do nothing for you.
2049
2050 Guard
2051 The guard module, when used, will be used to implement
2052 "AnyEvent::Util::guard". This speeds up guards considerably (and
2053 uses a lot less memory), but otherwise doesn't affect guard
2054 operation much. It is purely used for performance.
2055
2056 JSON and JSON::XS
2057 One of these modules is required when you want to read or write
2058 JSON data via AnyEvent::Handle. JSON is also written in pure-perl,
2059 but can take advantage of the ultra-high-speed JSON::XS module when
2060 it is installed.
2061
2062 Net::SSLeay
2063 Implementing TLS/SSL in Perl is certainly interesting, but not very
2064 worthwhile: If this module is installed, then AnyEvent::Handle
2065 (with the help of AnyEvent::TLS), gains the ability to do TLS/SSL.
2066
2067 Time::HiRes
2068 This module is part of perl since release 5.008. It will be used
2069 when the chosen event library does not come with a timing source of
2070 its own. The pure-perl event loop (AnyEvent::Loop) will
2071 additionally load it to try to use a monotonic clock for timing
2072 stability.
2073
2074 AnyEvent::AIO (and IO::AIO)
2075 The default implementation of AnyEvent::IO is to do I/O
2076 synchronously, stopping programs while they access the disk, which
2077 is fine for a lot of programs.
2078
2079 Installing AnyEvent::AIO (and its IO::AIO dependency) makes it
2080 switch to a true asynchronous implementation, so event processing
2081 can continue even while waiting for disk I/O.
2082
2084 Most event libraries are not fork-safe. The ones who are usually are
2085 because they rely on inefficient but fork-safe "select" or "poll" calls
2086 - higher performance APIs such as BSD's kqueue or the dreaded Linux
2087 epoll are usually badly thought-out hacks that are incompatible with
2088 fork in one way or another. Only EV is fully fork-aware and ensures
2089 that you continue event-processing in both parent and child (or both,
2090 if you know what you are doing).
2091
2092 This means that, in general, you cannot fork and do event processing in
2093 the child if the event library was initialised before the fork (which
2094 usually happens when the first AnyEvent watcher is created, or the
2095 library is loaded).
2096
2097 If you have to fork, you must either do so before creating your first
2098 watcher OR you must not use AnyEvent at all in the child OR you must do
2099 something completely out of the scope of AnyEvent (see below).
2100
2101 The problem of doing event processing in the parent and the child is
2102 much more complicated: even for backends that are fork-aware or fork-
2103 safe, their behaviour is not usually what you want: fork clones all
2104 watchers, that means all timers, I/O watchers etc. are active in both
2105 parent and child, which is almost never what you want. Using "exec" to
2106 start worker children from some kind of manage prrocess is usually
2107 preferred, because it is much easier and cleaner, at the expense of
2108 having to have another binary.
2109
2110 In addition to logical problems with fork, there are also
2111 implementation problems. For example, on POSIX systems, you cannot fork
2112 at all in Perl code if a thread (I am talking of pthreads here) was
2113 ever created in the process, and this is just the tip of the iceberg.
2114 In general, using fork from Perl is difficult, and attempting to use
2115 fork without an exec to implement some kind of parallel processing is
2116 almost certainly doomed.
2117
2118 To safely fork and exec, you should use a module such as
2119 Proc::FastSpawn that let's you safely fork and exec new processes.
2120
2121 If you want to do multiprocessing using processes, you can look at the
2122 AnyEvent::Fork module (and some related modules such as
2123 AnyEvent::Fork::RPC, AnyEvent::Fork::Pool and AnyEvent::Fork::Remote).
2124 This module allows you to safely create subprocesses without any
2125 limitations - you can use X11 toolkits or AnyEvent in the children
2126 created by AnyEvent::Fork safely and without any special precautions.
2127
2129 AnyEvent can be forced to load any event model via
2130 $ENV{PERL_ANYEVENT_MODEL}. While this cannot (to my knowledge) be used
2131 to execute arbitrary code or directly gain access, it can easily be
2132 used to make the program hang or malfunction in subtle ways, as
2133 AnyEvent watchers will not be active when the program uses a different
2134 event model than specified in the variable.
2135
2136 You can make AnyEvent completely ignore this variable by deleting it
2137 before the first watcher gets created, e.g. with a "BEGIN" block:
2138
2139 BEGIN { delete $ENV{PERL_ANYEVENT_MODEL} }
2140
2141 use AnyEvent;
2142
2143 Similar considerations apply to $ENV{PERL_ANYEVENT_VERBOSE}, as that
2144 can be used to probe what backend is used and gain other information
2145 (which is probably even less useful to an attacker than
2146 PERL_ANYEVENT_MODEL), and $ENV{PERL_ANYEVENT_STRICT}.
2147
2148 Note that AnyEvent will remove all environment variables starting with
2149 "PERL_ANYEVENT_" from %ENV when it is loaded while taint mode is
2150 enabled.
2151
2153 Perl 5.8 has numerous memleaks that sometimes hit this module and are
2154 hard to work around. If you suffer from memleaks, first upgrade to Perl
2155 5.10 and check wether the leaks still show up. (Perl 5.10.0 has other
2156 annoying memleaks, such as leaking on "map" and "grep" but it is
2157 usually not as pronounced).
2158
2160 Tutorial/Introduction: AnyEvent::Intro.
2161
2162 FAQ: AnyEvent::FAQ.
2163
2164 Utility functions: AnyEvent::Util (misc. grab-bag), AnyEvent::Log
2165 (simply logging).
2166
2167 Development/Debugging: AnyEvent::Strict (stricter checking),
2168 AnyEvent::Debug (interactive shell, watcher tracing).
2169
2170 Supported event modules: AnyEvent::Loop, EV, EV::Glib, Glib::EV, Event,
2171 Glib::Event, Glib, Tk, Event::Lib, Qt, POE, FLTK, Cocoa::EventLoop, UV.
2172
2173 Implementations: AnyEvent::Impl::EV, AnyEvent::Impl::Event,
2174 AnyEvent::Impl::Glib, AnyEvent::Impl::Tk, AnyEvent::Impl::Perl,
2175 AnyEvent::Impl::EventLib, AnyEvent::Impl::Qt, AnyEvent::Impl::POE,
2176 AnyEvent::Impl::IOAsync, AnyEvent::Impl::Irssi, AnyEvent::Impl::FLTK,
2177 AnyEvent::Impl::Cocoa, AnyEvent::Impl::UV.
2178
2179 Non-blocking handles, pipes, stream sockets, TCP clients and servers:
2180 AnyEvent::Handle, AnyEvent::Socket, AnyEvent::TLS.
2181
2182 Asynchronous File I/O: AnyEvent::IO.
2183
2184 Asynchronous DNS: AnyEvent::DNS.
2185
2186 Thread support: Coro, Coro::AnyEvent, Coro::EV, Coro::Event.
2187
2188 Nontrivial usage examples: AnyEvent::GPSD, AnyEvent::IRC,
2189 AnyEvent::HTTP.
2190
2192 Marc Lehmann <schmorp@schmorp.de>
2193 http://anyevent.schmorp.de
2194
2195
2196
2197perl v5.28.0 2017-06-23 AnyEvent(3)