1AnyEvent(3)           User Contributed Perl Documentation          AnyEvent(3)
2
3
4

NAME

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

SYNOPSIS

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

INTRODUCTION/TUTORIAL

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

SUPPORT

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

WHY YOU SHOULD USE THIS MODULE (OR NOT)

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

DESCRIPTION

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

WATCHERS

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

SUPPORTED EVENT LOOPS/BACKENDS

847       The following backend classes are part of the AnyEvent distribution
848       (every class has its own manpage):
849
850       Backends that are autoprobed when no other event loop can be found.
851           EV is the preferred backend when no other event loop seems to be in
852           use. If EV is not installed, then AnyEvent will fall back to its
853           own pure-perl implementation, which is available everywhere as it
854           comes with AnyEvent itself.
855
856              AnyEvent::Impl::EV        based on EV (interface to libev, best choice).
857              AnyEvent::Impl::Perl      pure-perl AnyEvent::Loop, fast and portable.
858
859       Backends that are transparently being picked up when they are used.
860           These will be used if they are already loaded when the first
861           watcher is created, in which case it is assumed that the
862           application is using them. This means that AnyEvent will
863           automatically pick the right backend when the main program loads an
864           event module before anything starts to create watchers. Nothing
865           special needs to be done by the main program.
866
867              AnyEvent::Impl::Event     based on Event, very stable, few glitches.
868              AnyEvent::Impl::Glib      based on Glib, slow but very stable.
869              AnyEvent::Impl::Tk        based on Tk, very broken.
870              AnyEvent::Impl::UV        based on UV, innovated square wheels.
871              AnyEvent::Impl::EventLib  based on Event::Lib, leaks memory and worse.
872              AnyEvent::Impl::POE       based on POE, very slow, some limitations.
873              AnyEvent::Impl::Irssi     used when running within irssi.
874              AnyEvent::Impl::IOAsync   based on IO::Async.
875              AnyEvent::Impl::Cocoa     based on Cocoa::EventLoop.
876              AnyEvent::Impl::FLTK      based on FLTK (fltk 2 binding).
877
878       Backends with special needs.
879           Qt requires the Qt::Application to be instantiated first, but will
880           otherwise be picked up automatically. As long as the main program
881           instantiates the application before any AnyEvent watchers are
882           created, everything should just work.
883
884              AnyEvent::Impl::Qt        based on Qt.
885
886       Event loops that are indirectly supported via other backends.
887           Some event loops can be supported via other modules:
888
889           There is no direct support for WxWidgets (Wx) or Prima.
890
891           WxWidgets has no support for watching file handles. However, you
892           can use WxWidgets through the POE adaptor, as POE has a Wx backend
893           that simply polls 20 times per second, which was considered to be
894           too horrible to even consider for AnyEvent.
895
896           Prima is not supported as nobody seems to be using it, but it has a
897           POE backend, so it can be supported through POE.
898
899           AnyEvent knows about both Prima and Wx, however, and will try to
900           load POE when detecting them, in the hope that POE will pick them
901           up, in which case everything will be automatic.
902
903       Known event loops outside the AnyEvent distribution
904           The following event loops or programs support AnyEvent by providing
905           their own AnyEvent backend. They will be picked up automatically.
906
907              urxvt::anyevent           available to rxvt-unicode extensions
908

GLOBAL VARIABLES AND FUNCTIONS

910       These are not normally required to use AnyEvent, but can be useful to
911       write AnyEvent extension modules.
912
913       $AnyEvent::MODEL
914           Contains "undef" until the first watcher is being created, before
915           the backend has been autodetected.
916
917           Afterwards it contains the event model that is being used, which is
918           the name of the Perl class implementing the model. This class is
919           usually one of the "AnyEvent::Impl::xxx" modules, but can be any
920           other class in the case AnyEvent has been extended at runtime (e.g.
921           in rxvt-unicode it will be "urxvt::anyevent").
922
923       AnyEvent::detect
924           Returns $AnyEvent::MODEL, forcing autodetection of the event model
925           if necessary. You should only call this function right before you
926           would have created an AnyEvent watcher anyway, that is, as late as
927           possible at runtime, and not e.g. during initialisation of your
928           module.
929
930           The effect of calling this function is as if a watcher had been
931           created (specifically, actions that happen "when the first watcher
932           is created" happen when calling detetc as well).
933
934           If you need to do some initialisation before AnyEvent watchers are
935           created, use "post_detect".
936
937       $guard = AnyEvent::post_detect { BLOCK }
938           Arranges for the code block to be executed as soon as the event
939           model is autodetected (or immediately if that has already
940           happened).
941
942           The block will be executed after the actual backend has been
943           detected ($AnyEvent::MODEL is set), so it is possible to do some
944           initialisation only when AnyEvent is actually initialised - see the
945           sources of AnyEvent::AIO to see how this is used.
946
947           The most common usage is to create some global watchers, without
948           forcing event module detection too early. For example,
949           AnyEvent::AIO creates and installs the global IO::AIO watcher in a
950           "post_detect" block to avoid autodetecting the event module at load
951           time.
952
953           If called in scalar or list context, then it creates and returns an
954           object that automatically removes the callback again when it is
955           destroyed (or "undef" when the hook was immediately executed). See
956           AnyEvent::AIO for a case where this is useful.
957
958           Example: Create a watcher for the IO::AIO module and store it in
959           $WATCHER, but do so only do so after the event loop is initialised.
960
961              our WATCHER;
962
963              my $guard = AnyEvent::post_detect {
964                 $WATCHER = AnyEvent->io (fh => IO::AIO::poll_fileno, poll => 'r', cb => \&IO::AIO::poll_cb);
965              };
966
967              # the ||= is important in case post_detect immediately runs the block,
968              # as to not clobber the newly-created watcher. assigning both watcher and
969              # post_detect guard to the same variable has the advantage of users being
970              # able to just C<undef $WATCHER> if the watcher causes them grief.
971
972              $WATCHER ||= $guard;
973
974       @AnyEvent::post_detect
975           This is a lower level interface then "AnyEvent::post_detect" (the
976           function). This variable is mainly useful for modules that can do
977           something useful when AnyEvent is used and thus want to know when
978           it is initialised, but do not need to even load it by default. This
979           array provides the means to hook into AnyEvent passively, without
980           loading it.
981
982           Here is how it works: If there are any code references in this
983           array (you can "push" to it before or after loading AnyEvent), then
984           they will be called directly after the event loop has been chosen.
985
986           You should check $AnyEvent::MODEL before adding to this array,
987           though: if it is defined then the event loop has already been
988           detected, and the array will be ignored.
989
990           Best use "AnyEvent::post_detect { BLOCK }" when your application
991           allows it, as it takes care of these details.
992
993           Example: To load Coro::AnyEvent whenever Coro and AnyEvent are used
994           together, you could put this into Coro (this is the actual code
995           used by Coro to accomplish this):
996
997              if (defined $AnyEvent::MODEL) {
998                 # AnyEvent already initialised, so load Coro::AnyEvent
999                 require Coro::AnyEvent;
1000              } else {
1001                 # AnyEvent not yet initialised, so make sure to load Coro::AnyEvent
1002                 # as soon as it is
1003                 push @AnyEvent::post_detect, sub { require Coro::AnyEvent };
1004              }
1005
1006       AnyEvent::postpone { BLOCK }
1007           Arranges for the block to be executed as soon as possible, but not
1008           before the call itself returns. In practise, the block will be
1009           executed just before the event loop polls for new events, or
1010           shortly afterwards.
1011
1012           This function never returns anything (to make the "return postpone
1013           { ...  }" idiom more useful.
1014
1015           To understand the usefulness of this function, consider a function
1016           that asynchronously does something for you and returns some
1017           transaction object or guard to let you cancel the operation. For
1018           example, "AnyEvent::Socket::tcp_connect":
1019
1020              # start a connection attempt unless one is active
1021              $self->{connect_guard} ||= AnyEvent::Socket::tcp_connect "www.example.net", 80, sub {
1022                 delete $self->{connect_guard};
1023                 ...
1024              };
1025
1026           Imagine that this function could instantly call the callback, for
1027           example, because it detects an obvious error such as a negative
1028           port number. Invoking the callback before the function returns
1029           causes problems however: the callback will be called and will try
1030           to delete the guard object. But since the function hasn't returned
1031           yet, there is nothing to delete. When the function eventually
1032           returns it will assign the guard object to
1033           "$self->{connect_guard}", where it will likely never be deleted, so
1034           the program thinks it is still trying to connect.
1035
1036           This is where "AnyEvent::postpone" should be used. Instead of
1037           calling the callback directly on error:
1038
1039              $cb->(undef), return # signal error to callback, BAD!
1040                 if $some_error_condition;
1041
1042           It should use "postpone":
1043
1044              AnyEvent::postpone { $cb->(undef) }, return # signal error to callback, later
1045                 if $some_error_condition;
1046
1047       AnyEvent::log $level, $msg[, @args]
1048           Log the given $msg at the given $level.
1049
1050           If AnyEvent::Log is not loaded then this function makes a simple
1051           test to see whether the message will be logged. If the test
1052           succeeds it will load AnyEvent::Log and call "AnyEvent::Log::log" -
1053           consequently, look at the AnyEvent::Log documentation for details.
1054
1055           If the test fails it will simply return. Right now this happens
1056           when a numerical loglevel is used and it is larger than the level
1057           specified via $ENV{PERL_ANYEVENT_VERBOSE}.
1058
1059           If you want to sprinkle loads of logging calls around your code,
1060           consider creating a logger callback with the
1061           "AnyEvent::Log::logger" function, which can reduce typing, codesize
1062           and can reduce the logging overhead enourmously.
1063
1064       AnyEvent::fh_block $filehandle
1065       AnyEvent::fh_unblock $filehandle
1066           Sets blocking or non-blocking behaviour for the given filehandle.
1067

WHAT TO DO IN A MODULE

1069       As a module author, you should "use AnyEvent" and call AnyEvent methods
1070       freely, but you should not load a specific event module or rely on it.
1071
1072       Be careful when you create watchers in the module body - AnyEvent will
1073       decide which event module to use as soon as the first method is called,
1074       so by calling AnyEvent in your module body you force the user of your
1075       module to load the event module first.
1076
1077       Never call "->recv" on a condition variable unless you know that the
1078       "->send" method has been called on it already. This is because it will
1079       stall the whole program, and the whole point of using events is to stay
1080       interactive.
1081
1082       It is fine, however, to call "->recv" when the user of your module
1083       requests it (i.e. if you create a http request object ad have a method
1084       called "results" that returns the results, it may call "->recv" freely,
1085       as the user of your module knows what she is doing. Always).
1086

WHAT TO DO IN THE MAIN PROGRAM

1088       There will always be a single main program - the only place that should
1089       dictate which event model to use.
1090
1091       If the program is not event-based, it need not do anything special,
1092       even when it depends on a module that uses an AnyEvent. If the program
1093       itself uses AnyEvent, but does not care which event loop is used, all
1094       it needs to do is "use AnyEvent". In either case, AnyEvent will choose
1095       the best available loop implementation.
1096
1097       If the main program relies on a specific event model - for example, in
1098       Gtk2 programs you have to rely on the Glib module - you should load the
1099       event module before loading AnyEvent or any module that uses it:
1100       generally speaking, you should load it as early as possible. The reason
1101       is that modules might create watchers when they are loaded, and
1102       AnyEvent will decide on the event model to use as soon as it creates
1103       watchers, and it might choose the wrong one unless you load the correct
1104       one yourself.
1105
1106       You can chose to use a pure-perl implementation by loading the
1107       "AnyEvent::Loop" module, which gives you similar behaviour everywhere,
1108       but letting AnyEvent chose the model is generally better.
1109
1110   MAINLOOP EMULATION
1111       Sometimes (often for short test scripts, or even standalone programs
1112       who only want to use AnyEvent), you do not want to run a specific event
1113       loop.
1114
1115       In that case, you can use a condition variable like this:
1116
1117          AnyEvent->condvar->recv;
1118
1119       This has the effect of entering the event loop and looping forever.
1120
1121       Note that usually your program has some exit condition, in which case
1122       it is better to use the "traditional" approach of storing a condition
1123       variable somewhere, waiting for it, and sending it when the program
1124       should exit cleanly.
1125

OTHER MODULES

1127       The following is a non-exhaustive list of additional modules that use
1128       AnyEvent as a client and can therefore be mixed easily with other
1129       AnyEvent modules and other event loops in the same program. Some of the
1130       modules come as part of AnyEvent, the others are available via CPAN
1131       (see <http://search.cpan.org/search?m=module&q=anyevent%3A%3A*> for a
1132       longer non-exhaustive list), and the list is heavily biased towards
1133       modules of the AnyEvent author himself :)
1134
1135       AnyEvent::Util (part of the AnyEvent distribution)
1136           Contains various utility functions that replace often-used blocking
1137           functions such as "inet_aton" with event/callback-based versions.
1138
1139       AnyEvent::Socket (part of the AnyEvent distribution)
1140           Provides various utility functions for (internet protocol) sockets,
1141           addresses and name resolution. Also functions to create non-
1142           blocking tcp connections or tcp servers, with IPv6 and SRV record
1143           support and more.
1144
1145       AnyEvent::Handle (part of the AnyEvent distribution)
1146           Provide read and write buffers, manages watchers for reads and
1147           writes, supports raw and formatted I/O, I/O queued and fully
1148           transparent and non-blocking SSL/TLS (via AnyEvent::TLS).
1149
1150       AnyEvent::DNS (part of the AnyEvent distribution)
1151           Provides rich asynchronous DNS resolver capabilities.
1152
1153       AnyEvent::HTTP, AnyEvent::IRC, AnyEvent::XMPP, AnyEvent::GPSD,
1154       AnyEvent::IGS, AnyEvent::FCP
1155           Implement event-based interfaces to the protocols of the same name
1156           (for the curious, IGS is the International Go Server and FCP is the
1157           Freenet Client Protocol).
1158
1159       AnyEvent::AIO (part of the AnyEvent distribution)
1160           Truly asynchronous (as opposed to non-blocking) I/O, should be in
1161           the toolbox of every event programmer. AnyEvent::AIO transparently
1162           fuses IO::AIO and AnyEvent together, giving AnyEvent access to
1163           event-based file I/O, and much more.
1164
1165       AnyEvent::Fork, AnyEvent::Fork::RPC, AnyEvent::Fork::Pool,
1166       AnyEvent::Fork::Remote
1167           These let you safely fork new subprocesses, either locally or
1168           remotely (e.g.v ia ssh), using some RPC protocol or not, without
1169           the limitations normally imposed by fork (AnyEvent works fine for
1170           example). Dynamically-resized worker pools are obviously included
1171           as well.
1172
1173           And they are quite tiny and fast as well - "abusing" AnyEvent::Fork
1174           just to exec external programs can easily beat using "fork" and
1175           "exec" (or even "system") in most programs.
1176
1177       AnyEvent::Filesys::Notify
1178           AnyEvent is good for non-blocking stuff, but it can't detect file
1179           or path changes (e.g. "watch this directory for new files", "watch
1180           this file for changes"). The AnyEvent::Filesys::Notify module
1181           promises to do just that in a portbale fashion, supporting inotify
1182           on GNU/Linux and some weird, without doubt broken, stuff on OS X to
1183           monitor files. It can fall back to blocking scans at regular
1184           intervals transparently on other platforms, so it's about as
1185           portable as it gets.
1186
1187           (I haven't used it myself, but it seems the biggest problem with it
1188           is it quite bad performance).
1189
1190       AnyEvent::DBI
1191           Executes DBI requests asynchronously in a proxy process for you,
1192           notifying you in an event-based way when the operation is finished.
1193
1194       AnyEvent::FastPing
1195           The fastest ping in the west.
1196
1197       Coro
1198           Has special support for AnyEvent via Coro::AnyEvent, which allows
1199           you to simply invert the flow control - don't call us, we will call
1200           you:
1201
1202              async {
1203                 Coro::AnyEvent::sleep 5; # creates a 5s timer and waits for it
1204                 print "5 seconds later!\n";
1205
1206                 Coro::AnyEvent::readable *STDIN; # uses an I/O watcher
1207                 my $line = <STDIN>; # works for ttys
1208
1209                 AnyEvent::HTTP::http_get "url", Coro::rouse_cb;
1210                 my ($body, $hdr) = Coro::rouse_wait;
1211              };
1212

SIMPLIFIED AE API

1214       Starting with version 5.0, AnyEvent officially supports a second, much
1215       simpler, API that is designed to reduce the calling, typing and memory
1216       overhead by using function call syntax and a fixed number of
1217       parameters.
1218
1219       See the AE manpage for details.
1220

ERROR AND EXCEPTION HANDLING

1222       In general, AnyEvent does not do any error handling - it relies on the
1223       caller to do that if required. The AnyEvent::Strict module (see also
1224       the "PERL_ANYEVENT_STRICT" environment variable, below) provides strict
1225       checking of all AnyEvent methods, however, which is highly useful
1226       during development.
1227
1228       As for exception handling (i.e. runtime errors and exceptions thrown
1229       while executing a callback), this is not only highly event-loop
1230       specific, but also not in any way wrapped by this module, as this is
1231       the job of the main program.
1232
1233       The pure perl event loop simply re-throws the exception (usually within
1234       "condvar->recv"), the Event and EV modules call "$Event/EV::DIED->()",
1235       Glib uses "install_exception_handler" and so on.
1236

ENVIRONMENT VARIABLES

1238       AnyEvent supports a number of environment variables that tune the
1239       runtime behaviour. They are usually evaluated when AnyEvent is loaded,
1240       initialised, or a submodule that uses them is loaded. Many of them also
1241       cause AnyEvent to load additional modules - for example,
1242       "PERL_ANYEVENT_DEBUG_WRAP" causes the AnyEvent::Debug module to be
1243       loaded.
1244
1245       All the environment variables documented here start with
1246       "PERL_ANYEVENT_", which is what AnyEvent considers its own namespace.
1247       Other modules are encouraged (but by no means required) to use
1248       "PERL_ANYEVENT_SUBMODULE" if they have registered the
1249       AnyEvent::Submodule namespace on CPAN, for any submodule. For example,
1250       AnyEvent::HTTP could be expected to use "PERL_ANYEVENT_HTTP_PROXY" (it
1251       should not access env variables starting with "AE_", see below).
1252
1253       All variables can also be set via the "AE_" prefix, that is, instead of
1254       setting "PERL_ANYEVENT_VERBOSE" you can also set "AE_VERBOSE". In case
1255       there is a clash btween anyevent and another program that uses
1256       "AE_something" you can set the corresponding "PERL_ANYEVENT_something"
1257       variable to the empty string, as those variables take precedence.
1258
1259       When AnyEvent is first loaded, it copies all "AE_xxx" env variables to
1260       their "PERL_ANYEVENT_xxx" counterpart unless that variable already
1261       exists. If taint mode is on, then AnyEvent will remove all environment
1262       variables starting with "PERL_ANYEVENT_" from %ENV (or replace them
1263       with "undef" or the empty string, if the corresaponding "AE_" variable
1264       is set).
1265
1266       The exact algorithm is currently:
1267
1268          1. if taint mode enabled, delete all PERL_ANYEVENT_xyz variables from %ENV
1269          2. copy over AE_xyz to PERL_ANYEVENT_xyz unless the latter alraedy exists
1270          3. if taint mode enabled, set all PERL_ANYEVENT_xyz variables to undef.
1271
1272       This ensures that child processes will not see the "AE_" variables.
1273
1274       The following environment variables are currently known to AnyEvent:
1275
1276       "PERL_ANYEVENT_VERBOSE"
1277           By default, AnyEvent will log messages with loglevel 4 ("error") or
1278           higher (see AnyEvent::Log). You can set this environment variable
1279           to a numerical loglevel to make AnyEvent more (or less) talkative.
1280
1281           If you want to do more than just set the global logging level you
1282           should have a look at "PERL_ANYEVENT_LOG", which allows much more
1283           complex specifications.
1284
1285           When set to 0 ("off"), then no messages whatsoever will be logged
1286           with everything else at defaults.
1287
1288           When set to 5 or higher ("warn"), AnyEvent warns about unexpected
1289           conditions, such as not being able to load the event model
1290           specified by "PERL_ANYEVENT_MODEL", or a guard callback throwing an
1291           exception - this is the minimum recommended level for use during
1292           development.
1293
1294           When set to 7 or higher (info), AnyEvent reports which event model
1295           it chooses.
1296
1297           When set to 8 or higher (debug), then AnyEvent will report extra
1298           information on which optional modules it loads and how it
1299           implements certain features.
1300
1301       "PERL_ANYEVENT_LOG"
1302           Accepts rather complex logging specifications. For example, you
1303           could log all "debug" messages of some module to stderr, warnings
1304           and above to stderr, and errors and above to syslog, with:
1305
1306              PERL_ANYEVENT_LOG=Some::Module=debug,+log:filter=warn,+%syslog:%syslog=error,syslog
1307
1308           For the rather extensive details, see AnyEvent::Log.
1309
1310           This variable is evaluated when AnyEvent (or AnyEvent::Log) is
1311           loaded, so will take effect even before AnyEvent has initialised
1312           itself.
1313
1314           Note that specifying this environment variable causes the
1315           AnyEvent::Log module to be loaded, while "PERL_ANYEVENT_VERBOSE"
1316           does not, so only using the latter saves a few hundred kB of memory
1317           unless a module explicitly needs the extra features of
1318           AnyEvent::Log.
1319
1320       "PERL_ANYEVENT_STRICT"
1321           AnyEvent does not do much argument checking by default, as thorough
1322           argument checking is very costly. Setting this variable to a true
1323           value will cause AnyEvent to load "AnyEvent::Strict" and then to
1324           thoroughly check the arguments passed to most method calls. If it
1325           finds any problems, it will croak.
1326
1327           In other words, enables "strict" mode.
1328
1329           Unlike "use strict" (or its modern cousin, "use common::sense", it
1330           is definitely recommended to keep it off in production. Keeping
1331           "PERL_ANYEVENT_STRICT=1" in your environment while developing
1332           programs can be very useful, however.
1333
1334       "PERL_ANYEVENT_DEBUG_SHELL"
1335           If this env variable is nonempty, then its contents will be
1336           interpreted by "AnyEvent::Socket::parse_hostport" and
1337           "AnyEvent::Debug::shell" (after replacing every occurance of $$ by
1338           the process pid). The shell object is saved in
1339           $AnyEvent::Debug::SHELL.
1340
1341           This happens when the first watcher is created.
1342
1343           For example, to bind a debug shell on a unix domain socket in
1344           /tmp/debug<pid>.sock, you could use this:
1345
1346              PERL_ANYEVENT_DEBUG_SHELL=/tmp/debug\$\$.sock perlprog
1347              # connect with e.g.: socat readline /tmp/debug123.sock
1348
1349           Or to bind to tcp port 4545 on localhost:
1350
1351              PERL_ANYEVENT_DEBUG_SHELL=127.0.0.1:4545 perlprog
1352              # connect with e.g.: telnet localhost 4545
1353
1354           Note that creating sockets in /tmp or on localhost is very unsafe
1355           on multiuser systems.
1356
1357       "PERL_ANYEVENT_DEBUG_WRAP"
1358           Can be set to 0, 1 or 2 and enables wrapping of all watchers for
1359           debugging purposes. See "AnyEvent::Debug::wrap" for details.
1360
1361       "PERL_ANYEVENT_MODEL"
1362           This can be used to specify the event model to be used by AnyEvent,
1363           before auto detection and -probing kicks in.
1364
1365           It normally is a string consisting entirely of ASCII letters (e.g.
1366           "EV" or "IOAsync"). The string "AnyEvent::Impl::" gets prepended
1367           and the resulting module name is loaded and - if the load was
1368           successful - used as event model backend. If it fails to load then
1369           AnyEvent will proceed with auto detection and -probing.
1370
1371           If the string ends with "::" instead (e.g. "AnyEvent::Impl::EV::")
1372           then nothing gets prepended and the module name is used as-is
1373           (hint: "::" at the end of a string designates a module name and
1374           quotes it appropriately).
1375
1376           For example, to force the pure perl model (AnyEvent::Loop::Perl)
1377           you could start your program like this:
1378
1379              PERL_ANYEVENT_MODEL=Perl perl ...
1380
1381       "PERL_ANYEVENT_IO_MODEL"
1382           The current file I/O model - see AnyEvent::IO for more info.
1383
1384           At the moment, only "Perl" (small, pure-perl, synchronous) and
1385           "IOAIO" (truly asynchronous) are supported. The default is "IOAIO"
1386           if AnyEvent::AIO can be loaded, otherwise it is "Perl".
1387
1388       "PERL_ANYEVENT_PROTOCOLS"
1389           Used by both AnyEvent::DNS and AnyEvent::Socket to determine
1390           preferences for IPv4 or IPv6. The default is unspecified (and might
1391           change, or be the result of auto probing).
1392
1393           Must be set to a comma-separated list of protocols or address
1394           families, current supported: "ipv4" and "ipv6". Only protocols
1395           mentioned will be used, and preference will be given to protocols
1396           mentioned earlier in the list.
1397
1398           This variable can effectively be used for denial-of-service attacks
1399           against local programs (e.g. when setuid), although the impact is
1400           likely small, as the program has to handle connection and other
1401           failures anyways.
1402
1403           Examples: "PERL_ANYEVENT_PROTOCOLS=ipv4,ipv6" - prefer IPv4 over
1404           IPv6, but support both and try to use both.
1405           "PERL_ANYEVENT_PROTOCOLS=ipv4" - only support IPv4, never try to
1406           resolve or contact IPv6 addresses.
1407           "PERL_ANYEVENT_PROTOCOLS=ipv6,ipv4" support either IPv4 or IPv6,
1408           but prefer IPv6 over IPv4.
1409
1410       "PERL_ANYEVENT_HOSTS"
1411           This variable, if specified, overrides the /etc/hosts file used by
1412           AnyEvent::Socket"::resolve_sockaddr", i.e. hosts aliases will be
1413           read from that file instead.
1414
1415       "PERL_ANYEVENT_EDNS0"
1416           Used by AnyEvent::DNS to decide whether to use the EDNS0 extension
1417           for DNS. This extension is generally useful to reduce DNS traffic,
1418           especially when DNSSEC is involved, but some (broken) firewalls
1419           drop such DNS packets, which is why it is off by default.
1420
1421           Setting this variable to 1 will cause AnyEvent::DNS to announce
1422           EDNS0 in its DNS requests.
1423
1424       "PERL_ANYEVENT_MAX_FORKS"
1425           The maximum number of child processes that
1426           "AnyEvent::Util::fork_call" will create in parallel.
1427
1428       "PERL_ANYEVENT_MAX_OUTSTANDING_DNS"
1429           The default value for the "max_outstanding" parameter for the
1430           default DNS resolver - this is the maximum number of parallel DNS
1431           requests that are sent to the DNS server.
1432
1433       "PERL_ANYEVENT_MAX_SIGNAL_LATENCY"
1434           Perl has inherently racy signal handling (you can basically choose
1435           between losing signals and memory corruption) - pure perl event
1436           loops (including "AnyEvent::Loop", when "Async::Interrupt" isn't
1437           available) therefore have to poll regularly to avoid losing
1438           signals.
1439
1440           Some event loops are racy, but don't poll regularly, and some event
1441           loops are written in C but are still racy. For those event loops,
1442           AnyEvent installs a timer that regularly wakes up the event loop.
1443
1444           By default, the interval for this timer is 10 seconds, but you can
1445           override this delay with this environment variable (or by setting
1446           the $AnyEvent::MAX_SIGNAL_LATENCY variable before creating signal
1447           watchers).
1448
1449           Lower values increase CPU (and energy) usage, higher values can
1450           introduce long delays when reaping children or waiting for signals.
1451
1452           The AnyEvent::Async module, if available, will be used to avoid
1453           this polling (with most event loops).
1454
1455       "PERL_ANYEVENT_RESOLV_CONF"
1456           The absolute path to a resolv.conf-style file to use instead of
1457           /etc/resolv.conf (or the OS-specific configuration) in the default
1458           resolver, or the empty string to select the default configuration.
1459
1460       "PERL_ANYEVENT_CA_FILE", "PERL_ANYEVENT_CA_PATH".
1461           When neither "ca_file" nor "ca_path" was specified during
1462           AnyEvent::TLS context creation, and either of these environment
1463           variables are nonempty, they will be used to specify CA certificate
1464           locations instead of a system-dependent default.
1465
1466       "PERL_ANYEVENT_AVOID_GUARD" and "PERL_ANYEVENT_AVOID_ASYNC_INTERRUPT"
1467           When these are set to 1, then the respective modules are not
1468           loaded. Mostly good for testing AnyEvent itself.
1469

SUPPLYING YOUR OWN EVENT MODEL INTERFACE

1471       This is an advanced topic that you do not normally need to use AnyEvent
1472       in a module. This section is only of use to event loop authors who want
1473       to provide AnyEvent compatibility.
1474
1475       If you need to support another event library which isn't directly
1476       supported by AnyEvent, you can supply your own interface to it by
1477       pushing, before the first watcher gets created, the package name of the
1478       event module and the package name of the interface to use onto
1479       @AnyEvent::REGISTRY. You can do that before and even without loading
1480       AnyEvent, so it is reasonably cheap.
1481
1482       Example:
1483
1484          push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
1485
1486       This tells AnyEvent to (literally) use the "urxvt::anyevent::"
1487       package/class when it finds the "urxvt" package/module is already
1488       loaded.
1489
1490       When AnyEvent is loaded and asked to find a suitable event model, it
1491       will first check for the presence of urxvt by trying to "use" the
1492       "urxvt::anyevent" module.
1493
1494       The class should provide implementations for all watcher types. See
1495       AnyEvent::Impl::EV (source code), AnyEvent::Impl::Glib (Source code)
1496       and so on for actual examples. Use "perldoc -m AnyEvent::Impl::Glib" to
1497       see the sources.
1498
1499       If you don't provide "signal" and "child" watchers than AnyEvent will
1500       provide suitable (hopefully) replacements.
1501
1502       The above example isn't fictitious, the rxvt-unicode (a.k.a. urxvt)
1503       terminal emulator uses the above line as-is. An interface isn't
1504       included in AnyEvent because it doesn't make sense outside the embedded
1505       interpreter inside rxvt-unicode, and it is updated and maintained as
1506       part of the rxvt-unicode distribution.
1507
1508       rxvt-unicode also cheats a bit by not providing blocking access to
1509       condition variables: code blocking while waiting for a condition will
1510       "die". This still works with most modules/usages, and blocking calls
1511       must not be done in an interactive application, so it makes sense.
1512

EXAMPLE PROGRAM

1514       The following program uses an I/O watcher to read data from STDIN, a
1515       timer to display a message once per second, and a condition variable to
1516       quit the program when the user enters quit:
1517
1518          use AnyEvent;
1519
1520          my $cv = AnyEvent->condvar;
1521
1522          my $io_watcher = AnyEvent->io (
1523             fh   => \*STDIN,
1524             poll => 'r',
1525             cb   => sub {
1526                warn "io event <$_[0]>\n";   # will always output <r>
1527                chomp (my $input = <STDIN>); # read a line
1528                warn "read: $input\n";       # output what has been read
1529                $cv->send if $input =~ /^q/i; # quit program if /^q/i
1530             },
1531          );
1532
1533          my $time_watcher = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1534             warn "timeout\n"; # print 'timeout' at most every second
1535          });
1536
1537          $cv->recv; # wait until user enters /^q/i
1538

REAL-WORLD EXAMPLE

1540       Consider the Net::FCP module. It features (among others) the following
1541       API calls, which are to freenet what HTTP GET requests are to http:
1542
1543          my $data = $fcp->client_get ($url); # blocks
1544
1545          my $transaction = $fcp->txn_client_get ($url); # does not block
1546          $transaction->cb ( sub { ... } ); # set optional result callback
1547          my $data = $transaction->result; # possibly blocks
1548
1549       The "client_get" method works like "LWP::Simple::get": it requests the
1550       given URL and waits till the data has arrived. It is defined to be:
1551
1552          sub client_get { $_[0]->txn_client_get ($_[1])->result }
1553
1554       And in fact is automatically generated. This is the blocking API of
1555       Net::FCP, and it works as simple as in any other, similar, module.
1556
1557       More complicated is "txn_client_get": It only creates a transaction
1558       (completion, result, ...) object and initiates the transaction.
1559
1560          my $txn = bless { }, Net::FCP::Txn::;
1561
1562       It also creates a condition variable that is used to signal the
1563       completion of the request:
1564
1565          $txn->{finished} = AnyAvent->condvar;
1566
1567       It then creates a socket in non-blocking mode.
1568
1569          socket $txn->{fh}, ...;
1570          fcntl $txn->{fh}, F_SETFL, O_NONBLOCK;
1571          connect $txn->{fh}, ...
1572             and !$!{EWOULDBLOCK}
1573             and !$!{EINPROGRESS}
1574             and Carp::croak "unable to connect: $!\n";
1575
1576       Then it creates a write-watcher which gets called whenever an error
1577       occurs or the connection succeeds:
1578
1579          $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w });
1580
1581       And returns this transaction object. The "fh_ready_w" callback gets
1582       called as soon as the event loop detects that the socket is ready for
1583       writing.
1584
1585       The "fh_ready_w" method makes the socket blocking again, writes the
1586       request data and replaces the watcher by a read watcher (waiting for
1587       reply data). The actual code is more complicated, but that doesn't
1588       matter for this example:
1589
1590          fcntl $txn->{fh}, F_SETFL, 0;
1591          syswrite $txn->{fh}, $txn->{request}
1592             or die "connection or write error";
1593          $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r });
1594
1595       Again, "fh_ready_r" waits till all data has arrived, and then stores
1596       the result and signals any possible waiters that the request has
1597       finished:
1598
1599          sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf};
1600
1601          if (end-of-file or data complete) {
1602            $txn->{result} = $txn->{buf};
1603            $txn->{finished}->send;
1604            $txb->{cb}->($txn) of $txn->{cb}; # also call callback
1605          }
1606
1607       The "result" method, finally, just waits for the finished signal (if
1608       the request was already finished, it doesn't wait, of course, and
1609       returns the data:
1610
1611          $txn->{finished}->recv;
1612          return $txn->{result};
1613
1614       The actual code goes further and collects all errors ("die"s,
1615       exceptions) that occurred during request processing. The "result"
1616       method detects whether an exception as thrown (it is stored inside the
1617       $txn object) and just throws the exception, which means connection
1618       errors and other problems get reported to the code that tries to use
1619       the result, not in a random callback.
1620
1621       All of this enables the following usage styles:
1622
1623       1. Blocking:
1624
1625          my $data = $fcp->client_get ($url);
1626
1627       2. Blocking, but running in parallel:
1628
1629          my @datas = map $_->result,
1630                         map $fcp->txn_client_get ($_),
1631                            @urls;
1632
1633       Both blocking examples work without the module user having to know
1634       anything about events.
1635
1636       3a. Event-based in a main program, using any supported event module:
1637
1638          use EV;
1639
1640          $fcp->txn_client_get ($url)->cb (sub {
1641             my $txn = shift;
1642             my $data = $txn->result;
1643             ...
1644          });
1645
1646          EV::run;
1647
1648       3b. The module user could use AnyEvent, too:
1649
1650          use AnyEvent;
1651
1652          my $quit = AnyEvent->condvar;
1653
1654          $fcp->txn_client_get ($url)->cb (sub {
1655             ...
1656             $quit->send;
1657          });
1658
1659          $quit->recv;
1660

BENCHMARKS

1662       To give you an idea of the performance and overheads that AnyEvent adds
1663       over the event loops themselves and to give you an impression of the
1664       speed of various event loops I prepared some benchmarks.
1665
1666   BENCHMARKING ANYEVENT OVERHEAD
1667       Here is a benchmark of various supported event models used natively and
1668       through AnyEvent. The benchmark creates a lot of timers (with a zero
1669       timeout) and I/O watchers (watching STDOUT, a pty, to become writable,
1670       which it is), lets them fire exactly once and destroys them again.
1671
1672       Source code for this benchmark is found as eg/bench in the AnyEvent
1673       distribution. It uses the AE interface, which makes a real difference
1674       for the EV and Perl backends only.
1675
1676       Explanation of the columns
1677
1678       watcher is the number of event watchers created/destroyed. Since
1679       different event models feature vastly different performances, each
1680       event loop was given a number of watchers so that overall runtime is
1681       acceptable and similar between tested event loop (and keep them from
1682       crashing): Glib would probably take thousands of years if asked to
1683       process the same number of watchers as EV in this benchmark.
1684
1685       bytes is the number of bytes (as measured by the resident set size,
1686       RSS) consumed by each watcher. This method of measuring captures both C
1687       and Perl-based overheads.
1688
1689       create is the time, in microseconds (millionths of seconds), that it
1690       takes to create a single watcher. The callback is a closure shared
1691       between all watchers, to avoid adding memory overhead. That means
1692       closure creation and memory usage is not included in the figures.
1693
1694       invoke is the time, in microseconds, used to invoke a simple callback.
1695       The callback simply counts down a Perl variable and after it was
1696       invoked "watcher" times, it would "->send" a condvar once to signal the
1697       end of this phase.
1698
1699       destroy is the time, in microseconds, that it takes to destroy a single
1700       watcher.
1701
1702       Results
1703
1704                 name watchers bytes create invoke destroy comment
1705                EV/EV   100000   223   0.47   0.43    0.27 EV native interface
1706               EV/Any   100000   223   0.48   0.42    0.26 EV + AnyEvent watchers
1707         Coro::EV/Any   100000   223   0.47   0.42    0.26 coroutines + Coro::Signal
1708             Perl/Any   100000   431   2.70   0.74    0.92 pure perl implementation
1709          Event/Event    16000   516  31.16  31.84    0.82 Event native interface
1710            Event/Any    16000  1203  42.61  34.79    1.80 Event + AnyEvent watchers
1711          IOAsync/Any    16000  1911  41.92  27.45   16.81 via IO::Async::Loop::IO_Poll
1712          IOAsync/Any    16000  1726  40.69  26.37   15.25 via IO::Async::Loop::Epoll
1713             Glib/Any    16000  1118  89.00  12.57   51.17 quadratic behaviour
1714               Tk/Any     2000  1346  20.96  10.75    8.00 SEGV with >> 2000 watchers
1715              POE/Any     2000  6951 108.97 795.32   14.24 via POE::Loop::Event
1716              POE/Any     2000  6648  94.79 774.40  575.51 via POE::Loop::Select
1717
1718       Discussion
1719
1720       The benchmark does not measure scalability of the event loop very well.
1721       For example, a select-based event loop (such as the pure perl one) can
1722       never compete with an event loop that uses epoll when the number of
1723       file descriptors grows high. In this benchmark, all events become ready
1724       at the same time, so select/poll-based implementations get an unnatural
1725       speed boost.
1726
1727       Also, note that the number of watchers usually has a nonlinear effect
1728       on overall speed, that is, creating twice as many watchers doesn't take
1729       twice the time - usually it takes longer. This puts event loops tested
1730       with a higher number of watchers at a disadvantage.
1731
1732       To put the range of results into perspective, consider that on the
1733       benchmark machine, handling an event takes roughly 1600 CPU cycles with
1734       EV, 3100 CPU cycles with AnyEvent's pure perl loop and almost 3000000
1735       CPU cycles with POE.
1736
1737       "EV" is the sole leader regarding speed and memory use, which are both
1738       maximal/minimal, respectively. When using the AE API there is zero
1739       overhead (when going through the AnyEvent API create is about 5-6 times
1740       slower, with other times being equal, so still uses far less memory
1741       than any other event loop and is still faster than Event natively).
1742
1743       The pure perl implementation is hit in a few sweet spots (both the
1744       constant timeout and the use of a single fd hit optimisations in the
1745       perl interpreter and the backend itself). Nevertheless this shows that
1746       it adds very little overhead in itself. Like any select-based backend
1747       its performance becomes really bad with lots of file descriptors (and
1748       few of them active), of course, but this was not subject of this
1749       benchmark.
1750
1751       The "Event" module has a relatively high setup and callback invocation
1752       cost, but overall scores in on the third place.
1753
1754       "IO::Async" performs admirably well, about on par with "Event", even
1755       when using its pure perl backend.
1756
1757       "Glib"'s memory usage is quite a bit higher, but it features a faster
1758       callback invocation and overall ends up in the same class as "Event".
1759       However, Glib scales extremely badly, doubling the number of watchers
1760       increases the processing time by more than a factor of four, making it
1761       completely unusable when using larger numbers of watchers (note that
1762       only a single file descriptor was used in the benchmark, so
1763       inefficiencies of "poll" do not account for this).
1764
1765       The "Tk" adaptor works relatively well. The fact that it crashes with
1766       more than 2000 watchers is a big setback, however, as correctness takes
1767       precedence over speed. Nevertheless, its performance is surprising, as
1768       the file descriptor is dup()ed for each watcher. This shows that the
1769       dup() employed by some adaptors is not a big performance issue (it does
1770       incur a hidden memory cost inside the kernel which is not reflected in
1771       the figures above).
1772
1773       "POE", regardless of underlying event loop (whether using its pure perl
1774       select-based backend or the Event module, the POE-EV backend couldn't
1775       be tested because it wasn't working) shows abysmal performance and
1776       memory usage with AnyEvent: Watchers use almost 30 times as much memory
1777       as EV watchers, and 10 times as much memory as Event (the high memory
1778       requirements are caused by requiring a session for each watcher).
1779       Watcher invocation speed is almost 900 times slower than with
1780       AnyEvent's pure perl implementation.
1781
1782       The design of the POE adaptor class in AnyEvent can not really account
1783       for the performance issues, though, as session creation overhead is
1784       small compared to execution of the state machine, which is coded pretty
1785       optimally within AnyEvent::Impl::POE (and while everybody agrees that
1786       using multiple sessions is not a good approach, especially regarding
1787       memory usage, even the author of POE could not come up with a faster
1788       design).
1789
1790       Summary
1791
1792       •   Using EV through AnyEvent is faster than any other event loop (even
1793           when used without AnyEvent), but most event loops have acceptable
1794           performance with or without AnyEvent.
1795
1796       •   The overhead AnyEvent adds is usually much smaller than the
1797           overhead of the actual event loop, only with extremely fast event
1798           loops such as EV does AnyEvent add significant overhead.
1799
1800       •   You should avoid POE like the plague if you want performance or
1801           reasonable memory usage.
1802
1803   BENCHMARKING THE LARGE SERVER CASE
1804       This benchmark actually benchmarks the event loop itself. It works by
1805       creating a number of "servers": each server consists of a socket pair,
1806       a timeout watcher that gets reset on activity (but never fires), and an
1807       I/O watcher waiting for input on one side of the socket. Each time the
1808       socket watcher reads a byte it will write that byte to a random other
1809       "server".
1810
1811       The effect is that there will be a lot of I/O watchers, only part of
1812       which are active at any one point (so there is a constant number of
1813       active fds for each loop iteration, but which fds these are is random).
1814       The timeout is reset each time something is read because that reflects
1815       how most timeouts work (and puts extra pressure on the event loops).
1816
1817       In this benchmark, we use 10000 socket pairs (20000 sockets), of which
1818       100 (1%) are active. This mirrors the activity of large servers with
1819       many connections, most of which are idle at any one point in time.
1820
1821       Source code for this benchmark is found as eg/bench2 in the AnyEvent
1822       distribution. It uses the AE interface, which makes a real difference
1823       for the EV and Perl backends only.
1824
1825       Explanation of the columns
1826
1827       sockets is the number of sockets, and twice the number of "servers" (as
1828       each server has a read and write socket end).
1829
1830       create is the time it takes to create a socket pair (which is
1831       nontrivial) and two watchers: an I/O watcher and a timeout watcher.
1832
1833       request, the most important value, is the time it takes to handle a
1834       single "request", that is, reading the token from the pipe and
1835       forwarding it to another server. This includes deleting the old timeout
1836       and creating a new one that moves the timeout into the future.
1837
1838       Results
1839
1840            name sockets create  request
1841              EV   20000  62.66     7.99
1842            Perl   20000  68.32    32.64
1843         IOAsync   20000 174.06   101.15 epoll
1844         IOAsync   20000 174.67   610.84 poll
1845           Event   20000 202.69   242.91
1846            Glib   20000 557.01  1689.52
1847             POE   20000 341.54 12086.32 uses POE::Loop::Event
1848
1849       Discussion
1850
1851       This benchmark does measure scalability and overall performance of the
1852       particular event loop.
1853
1854       EV is again fastest. Since it is using epoll on my system, the setup
1855       time is relatively high, though.
1856
1857       Perl surprisingly comes second. It is much faster than the C-based
1858       event loops Event and Glib.
1859
1860       IO::Async performs very well when using its epoll backend, and still
1861       quite good compared to Glib when using its pure perl backend.
1862
1863       Event suffers from high setup time as well (look at its code and you
1864       will understand why). Callback invocation also has a high overhead
1865       compared to the "$_->() for .."-style loop that the Perl event loop
1866       uses. Event uses select or poll in basically all documented
1867       configurations.
1868
1869       Glib is hit hard by its quadratic behaviour w.r.t. many watchers. It
1870       clearly fails to perform with many filehandles or in busy servers.
1871
1872       POE is still completely out of the picture, taking over 1000 times as
1873       long as EV, and over 100 times as long as the Perl implementation, even
1874       though it uses a C-based event loop in this case.
1875
1876       Summary
1877
1878       •   The pure perl implementation performs extremely well.
1879
1880       •   Avoid Glib or POE in large projects where performance matters.
1881
1882   BENCHMARKING SMALL SERVERS
1883       While event loops should scale (and select-based ones do not...) even
1884       to large servers, most programs we (or I :) actually write have only a
1885       few I/O watchers.
1886
1887       In this benchmark, I use the same benchmark program as in the large
1888       server case, but it uses only eight "servers", of which three are
1889       active at any one time. This should reflect performance for a small
1890       server relatively well.
1891
1892       The columns are identical to the previous table.
1893
1894       Results
1895
1896           name sockets create request
1897             EV      16  20.00    6.54
1898           Perl      16  25.75   12.62
1899          Event      16  81.27   35.86
1900           Glib      16  32.63   15.48
1901            POE      16 261.87  276.28 uses POE::Loop::Event
1902
1903       Discussion
1904
1905       The benchmark tries to test the performance of a typical small server.
1906       While knowing how various event loops perform is interesting, keep in
1907       mind that their overhead in this case is usually not as important, due
1908       to the small absolute number of watchers (that is, you need efficiency
1909       and speed most when you have lots of watchers, not when you only have a
1910       few of them).
1911
1912       EV is again fastest.
1913
1914       Perl again comes second. It is noticeably faster than the C-based event
1915       loops Event and Glib, although the difference is too small to really
1916       matter.
1917
1918       POE also performs much better in this case, but is is still far behind
1919       the others.
1920
1921       Summary
1922
1923       •   C-based event loops perform very well with small number of
1924           watchers, as the management overhead dominates.
1925
1926   THE IO::Lambda BENCHMARK
1927       Recently I was told about the benchmark in the IO::Lambda manpage,
1928       which could be misinterpreted to make AnyEvent look bad. In fact, the
1929       benchmark simply compares IO::Lambda with POE, and IO::Lambda looks
1930       better (which shouldn't come as a surprise to anybody). As such, the
1931       benchmark is fine, and mostly shows that the AnyEvent backend from
1932       IO::Lambda isn't very optimal. But how would AnyEvent compare when used
1933       without the extra baggage? To explore this, I wrote the equivalent
1934       benchmark for AnyEvent.
1935
1936       The benchmark itself creates an echo-server, and then, for 500 times,
1937       connects to the echo server, sends a line, waits for the reply, and
1938       then creates the next connection. This is a rather bad benchmark, as it
1939       doesn't test the efficiency of the framework or much non-blocking I/O,
1940       but it is a benchmark nevertheless.
1941
1942          name                    runtime
1943          Lambda/select           0.330 sec
1944             + optimized          0.122 sec
1945          Lambda/AnyEvent         0.327 sec
1946             + optimized          0.138 sec
1947          Raw sockets/select      0.077 sec
1948          POE/select, components  0.662 sec
1949          POE/select, raw sockets 0.226 sec
1950          POE/select, optimized   0.404 sec
1951
1952          AnyEvent/select/nb      0.085 sec
1953          AnyEvent/EV/nb          0.068 sec
1954             +state machine       0.134 sec
1955
1956       The benchmark is also a bit unfair (my fault): the IO::Lambda/POE
1957       benchmarks actually make blocking connects and use 100% blocking I/O,
1958       defeating the purpose of an event-based solution. All of the newly
1959       written AnyEvent benchmarks use 100% non-blocking connects (using
1960       AnyEvent::Socket::tcp_connect and the asynchronous pure perl DNS
1961       resolver), so AnyEvent is at a disadvantage here, as non-blocking
1962       connects generally require a lot more bookkeeping and event handling
1963       than blocking connects (which involve a single syscall only).
1964
1965       The last AnyEvent benchmark additionally uses AnyEvent::Handle, which
1966       offers similar expressive power as POE and IO::Lambda, using
1967       conventional Perl syntax. This means that both the echo server and the
1968       client are 100% non-blocking, further placing it at a disadvantage.
1969
1970       As you can see, the AnyEvent + EV combination even beats the hand-
1971       optimised "raw sockets benchmark", while AnyEvent + its pure perl
1972       backend easily beats IO::Lambda and POE.
1973
1974       And even the 100% non-blocking version written using the high-level
1975       (and slow :) AnyEvent::Handle abstraction beats both POE and IO::Lambda
1976       higher level ("unoptimised") abstractions by a large margin, even
1977       though it does all of DNS, tcp-connect and socket I/O in a non-blocking
1978       way.
1979
1980       The two AnyEvent benchmarks programs can be found as eg/ae0.pl and
1981       eg/ae2.pl in the AnyEvent distribution, the remaining benchmarks are
1982       part of the IO::Lambda distribution and were used without any changes.
1983

SIGNALS

1985       AnyEvent currently installs handlers for these signals:
1986
1987       SIGCHLD
1988           A handler for "SIGCHLD" is installed by AnyEvent's child watcher
1989           emulation for event loops that do not support them natively. Also,
1990           some event loops install a similar handler.
1991
1992           Additionally, when AnyEvent is loaded and SIGCHLD is set to IGNORE,
1993           then AnyEvent will reset it to default, to avoid losing child exit
1994           statuses.
1995
1996       SIGPIPE
1997           A no-op handler is installed for "SIGPIPE" when $SIG{PIPE} is
1998           "undef" when AnyEvent gets loaded.
1999
2000           The rationale for this is that AnyEvent users usually do not really
2001           depend on SIGPIPE delivery (which is purely an optimisation for
2002           shell use, or badly-written programs), but "SIGPIPE" can cause
2003           spurious and rare program exits as a lot of people do not expect
2004           "SIGPIPE" when writing to some random socket.
2005
2006           The rationale for installing a no-op handler as opposed to ignoring
2007           it is that this way, the handler will be restored to defaults on
2008           exec.
2009
2010           Feel free to install your own handler, or reset it to defaults.
2011

RECOMMENDED/OPTIONAL MODULES

2013       One of AnyEvent's main goals is to be 100% Pure-Perl(tm): only perl
2014       (and its built-in modules) are required to use it.
2015
2016       That does not mean that AnyEvent won't take advantage of some
2017       additional modules if they are installed.
2018
2019       This section explains which additional modules will be used, and how
2020       they affect AnyEvent's operation.
2021
2022       Async::Interrupt
2023           This slightly arcane module is used to implement fast signal
2024           handling: To my knowledge, there is no way to do completely race-
2025           free and quick signal handling in pure perl. To ensure that signals
2026           still get delivered, AnyEvent will start an interval timer to wake
2027           up perl (and catch the signals) with some delay (default is 10
2028           seconds, look for $AnyEvent::MAX_SIGNAL_LATENCY).
2029
2030           If this module is available, then it will be used to implement
2031           signal catching, which means that signals will not be delayed, and
2032           the event loop will not be interrupted regularly, which is more
2033           efficient (and good for battery life on laptops).
2034
2035           This affects not just the pure-perl event loop, but also other
2036           event loops that have no signal handling on their own (e.g. Glib,
2037           Tk, Qt).
2038
2039           Some event loops (POE, Event, Event::Lib) offer signal watchers
2040           natively, and either employ their own workarounds (POE) or use
2041           AnyEvent's workaround (using $AnyEvent::MAX_SIGNAL_LATENCY).
2042           Installing Async::Interrupt does nothing for those backends.
2043
2044       EV  This module isn't really "optional", as it is simply one of the
2045           backend event loops that AnyEvent can use. However, it is simply
2046           the best event loop available in terms of features, speed and
2047           stability: It supports the AnyEvent API optimally, implements all
2048           the watcher types in XS, does automatic timer adjustments even when
2049           no monotonic clock is available, can take avdantage of advanced
2050           kernel interfaces such as "epoll" and "kqueue", and is the fastest
2051           backend by far. You can even embed Glib/Gtk2 in it (or vice versa,
2052           see EV::Glib and Glib::EV).
2053
2054           If you only use backends that rely on another event loop (e.g.
2055           "Tk"), then this module will do nothing for you.
2056
2057       Guard
2058           The guard module, when used, will be used to implement
2059           "AnyEvent::Util::guard". This speeds up guards considerably (and
2060           uses a lot less memory), but otherwise doesn't affect guard
2061           operation much. It is purely used for performance.
2062
2063       JSON and JSON::XS
2064           One of these modules is required when you want to read or write
2065           JSON data via AnyEvent::Handle. JSON is also written in pure-perl,
2066           but can take advantage of the ultra-high-speed JSON::XS module when
2067           it is installed.
2068
2069       Net::SSLeay
2070           Implementing TLS/SSL in Perl is certainly interesting, but not very
2071           worthwhile: If this module is installed, then AnyEvent::Handle
2072           (with the help of AnyEvent::TLS), gains the ability to do TLS/SSL.
2073
2074       Time::HiRes
2075           This module is part of perl since release 5.008. It will be used
2076           when the chosen event library does not come with a timing source of
2077           its own. The pure-perl event loop (AnyEvent::Loop) will
2078           additionally load it to try to use a monotonic clock for timing
2079           stability.
2080
2081       AnyEvent::AIO (and IO::AIO)
2082           The default implementation of AnyEvent::IO is to do I/O
2083           synchronously, stopping programs while they access the disk, which
2084           is fine for a lot of programs.
2085
2086           Installing AnyEvent::AIO (and its IO::AIO dependency) makes it
2087           switch to a true asynchronous implementation, so event processing
2088           can continue even while waiting for disk I/O.
2089

FORK

2091       Most event libraries are not fork-safe. The ones who are usually are
2092       because they rely on inefficient but fork-safe "select" or "poll" calls
2093       - higher performance APIs such as BSD's kqueue or the dreaded Linux
2094       epoll are usually badly thought-out hacks that are incompatible with
2095       fork in one way or another. Only EV is fully fork-aware and ensures
2096       that you continue event-processing in both parent and child (or both,
2097       if you know what you are doing).
2098
2099       This means that, in general, you cannot fork and do event processing in
2100       the child if the event library was initialised before the fork (which
2101       usually happens when the first AnyEvent watcher is created, or the
2102       library is loaded).
2103
2104       If you have to fork, you must either do so before creating your first
2105       watcher OR you must not use AnyEvent at all in the child OR you must do
2106       something completely out of the scope of AnyEvent (see below).
2107
2108       The problem of doing event processing in the parent and the child is
2109       much more complicated: even for backends that are fork-aware or fork-
2110       safe, their behaviour is not usually what you want: fork clones all
2111       watchers, that means all timers, I/O watchers etc. are active in both
2112       parent and child, which is almost never what you want. Using "exec" to
2113       start worker children from some kind of manage prrocess is usually
2114       preferred, because it is much easier and cleaner, at the expense of
2115       having to have another binary.
2116
2117       In addition to logical problems with fork, there are also
2118       implementation problems. For example, on POSIX systems, you cannot fork
2119       at all in Perl code if a thread (I am talking of pthreads here) was
2120       ever created in the process, and this is just the tip of the iceberg.
2121       In general, using fork from Perl is difficult, and attempting to use
2122       fork without an exec to implement some kind of parallel processing is
2123       almost certainly doomed.
2124
2125       To safely fork and exec, you should use a module such as
2126       Proc::FastSpawn that let's you safely fork and exec new processes.
2127
2128       If you want to do multiprocessing using processes, you can look at the
2129       AnyEvent::Fork module (and some related modules such as
2130       AnyEvent::Fork::RPC, AnyEvent::Fork::Pool and AnyEvent::Fork::Remote).
2131       This module allows you to safely create subprocesses without any
2132       limitations - you can use X11 toolkits or AnyEvent in the children
2133       created by AnyEvent::Fork safely and without any special precautions.
2134

SECURITY CONSIDERATIONS

2136       AnyEvent can be forced to load any event model via
2137       $ENV{PERL_ANYEVENT_MODEL}. While this cannot (to my knowledge) be used
2138       to execute arbitrary code or directly gain access, it can easily be
2139       used to make the program hang or malfunction in subtle ways, as
2140       AnyEvent watchers will not be active when the program uses a different
2141       event model than specified in the variable.
2142
2143       You can make AnyEvent completely ignore this variable by deleting it
2144       before the first watcher gets created, e.g. with a "BEGIN" block:
2145
2146          BEGIN { delete $ENV{PERL_ANYEVENT_MODEL} }
2147
2148          use AnyEvent;
2149
2150       Similar considerations apply to $ENV{PERL_ANYEVENT_VERBOSE}, as that
2151       can be used to probe what backend is used and gain other information
2152       (which is probably even less useful to an attacker than
2153       PERL_ANYEVENT_MODEL), and $ENV{PERL_ANYEVENT_STRICT}.
2154
2155       Note that AnyEvent will remove all environment variables starting with
2156       "PERL_ANYEVENT_" from %ENV when it is loaded while taint mode is
2157       enabled.
2158

BUGS

2160       Perl 5.8 has numerous memleaks that sometimes hit this module and are
2161       hard to work around. If you suffer from memleaks, first upgrade to Perl
2162       5.10 and check wether the leaks still show up. (Perl 5.10.0 has other
2163       annoying memleaks, such as leaking on "map" and "grep" but it is
2164       usually not as pronounced).
2165

SEE ALSO

2167       Tutorial/Introduction: AnyEvent::Intro.
2168
2169       FAQ: AnyEvent::FAQ.
2170
2171       Utility functions: AnyEvent::Util (misc. grab-bag), AnyEvent::Log
2172       (simply logging).
2173
2174       Development/Debugging: AnyEvent::Strict (stricter checking),
2175       AnyEvent::Debug (interactive shell, watcher tracing).
2176
2177       Supported event modules: AnyEvent::Loop, EV, EV::Glib, Glib::EV, Event,
2178       Glib::Event, Glib, Tk, Event::Lib, Qt, POE, FLTK, Cocoa::EventLoop, UV.
2179
2180       Implementations: AnyEvent::Impl::EV, AnyEvent::Impl::Event,
2181       AnyEvent::Impl::Glib, AnyEvent::Impl::Tk, AnyEvent::Impl::Perl,
2182       AnyEvent::Impl::EventLib, AnyEvent::Impl::Qt, AnyEvent::Impl::POE,
2183       AnyEvent::Impl::IOAsync, AnyEvent::Impl::Irssi, AnyEvent::Impl::FLTK,
2184       AnyEvent::Impl::Cocoa, AnyEvent::Impl::UV.
2185
2186       Non-blocking handles, pipes, stream sockets, TCP clients and servers:
2187       AnyEvent::Handle, AnyEvent::Socket, AnyEvent::TLS.
2188
2189       Asynchronous File I/O: AnyEvent::IO.
2190
2191       Asynchronous DNS: AnyEvent::DNS.
2192
2193       Thread support: Coro, Coro::AnyEvent, Coro::EV, Coro::Event.
2194
2195       Nontrivial usage examples: AnyEvent::GPSD, AnyEvent::IRC,
2196       AnyEvent::HTTP.
2197

AUTHOR

2199          Marc Lehmann <schmorp@schmorp.de>
2200          http://anyevent.schmorp.de
2201
2202
2203
2204perl v5.34.0                      2021-07-22                       AnyEvent(3)
Impressum