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, Perl, Event::Lib, Irssi, rxvt-unicode, IO::Async,
9       Qt and POE are various supported event loops/environments.
10

SYNOPSIS

12          use AnyEvent;
13
14          # if you prefer function calls, look at the AE manpage for
15          # an alternative API.
16
17          # file handle or descriptor readable
18          my $w = AnyEvent->io (fh => $fh, poll => "r", cb => sub { ...  });
19
20          # one-shot or repeating timers
21          my $w = AnyEvent->timer (after => $seconds, cb => sub { ...  });
22          my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ...
23
24          print AnyEvent->now;  # prints current event loop time
25          print AnyEvent->time; # think Time::HiRes::time or simply CORE::time.
26
27          # POSIX signal
28          my $w = AnyEvent->signal (signal => "TERM", cb => sub { ... });
29
30          # child process exit
31          my $w = AnyEvent->child (pid => $pid, cb => sub {
32             my ($pid, $status) = @_;
33             ...
34          });
35
36          # called when event loop idle (if applicable)
37          my $w = AnyEvent->idle (cb => sub { ... });
38
39          my $w = AnyEvent->condvar; # stores whether a condition was flagged
40          $w->send; # wake up current and all future recv's
41          $w->recv; # enters "main loop" till $condvar gets ->send
42          # use a condvar in callback mode:
43          $w->cb (sub { $_[0]->recv });
44

INTRODUCTION/TUTORIAL

46       This manpage is mainly a reference manual. If you are interested in a
47       tutorial or some gentle introduction, have a look at the
48       AnyEvent::Intro manpage.
49

SUPPORT

51       There is a mailinglist for discussing all things AnyEvent, and an IRC
52       channel, too.
53
54       See the AnyEvent project page at the Schmorpforge Ta-Sa Software
55       Repository, at <http://anyevent.schmorp.de>, for more info.
56

WHY YOU SHOULD USE THIS MODULE (OR NOT)

58       Glib, POE, IO::Async, Event... CPAN offers event models by the dozen
59       nowadays. So what is different about AnyEvent?
60
61       Executive Summary: AnyEvent is compatible, AnyEvent is free of policy
62       and AnyEvent is small and efficient.
63
64       First and foremost, AnyEvent is not an event model itself, it only
65       interfaces to whatever event model the main program happens to use, in
66       a pragmatic way. For event models and certain classes of immortals
67       alike, the statement "there can only be one" is a bitter reality: In
68       general, only one event loop can be active at the same time in a
69       process. AnyEvent cannot change this, but it can hide the differences
70       between those event loops.
71
72       The goal of AnyEvent is to offer module authors the ability to do event
73       programming (waiting for I/O or timer events) without subscribing to a
74       religion, a way of living, and most importantly: without forcing your
75       module users into the same thing by forcing them to use the same event
76       model you use.
77
78       For modules like POE or IO::Async (which is a total misnomer as it is
79       actually doing all I/O synchronously...), using them in your module is
80       like joining a cult: After you joined, you are dependent on them and
81       you cannot use anything else, as they are simply incompatible to
82       everything that isn't them. What's worse, all the potential users of
83       your module are also forced to use the same event loop you use.
84
85       AnyEvent is different: AnyEvent + POE works fine. AnyEvent + Glib works
86       fine. AnyEvent + Tk works fine etc. etc. but none of these work
87       together with the rest: POE + IO::Async? No go. Tk + Event? No go.
88       Again: if your module uses one of those, every user of your module has
89       to use it, too. But if your module uses AnyEvent, it works
90       transparently with all event models it supports (including stuff like
91       IO::Async, as long as those use one of the supported event loops. It is
92       trivial to add new event loops to AnyEvent, too, so it is future-
93       proof).
94
95       In addition to being free of having to use the one and only true event
96       model, AnyEvent also is free of bloat and policy: with POE or similar
97       modules, you get an enormous amount of code and strict rules you have
98       to follow. AnyEvent, on the other hand, is lean and up to the point, by
99       only offering the functionality that is necessary, in as thin as a
100       wrapper as technically possible.
101
102       Of course, AnyEvent comes with a big (and fully optional!) toolbox of
103       useful functionality, such as an asynchronous DNS resolver, 100% non-
104       blocking connects (even with TLS/SSL, IPv6 and on broken platforms such
105       as Windows) and lots of real-world knowledge and workarounds for
106       platform bugs and differences.
107
108       Now, if you do want lots of policy (this can arguably be somewhat
109       useful) and you want to force your users to use the one and only event
110       model, you should not use this module.
111

DESCRIPTION

113       AnyEvent provides an identical interface to multiple event loops. This
114       allows module authors to utilise an event loop without forcing module
115       users to use the same event loop (as only a single event loop can
116       coexist peacefully at any one time).
117
118       The interface itself is vaguely similar, but not identical to the Event
119       module.
120
121       During the first call of any watcher-creation method, the module tries
122       to detect the currently loaded event loop by probing whether one of the
123       following modules is already loaded: EV, Event, Glib,
124       AnyEvent::Impl::Perl, Tk, Event::Lib, Qt, POE. The first one found is
125       used. If none are found, the module tries to load these modules
126       (excluding Tk, Event::Lib, Qt and POE as the pure perl adaptor should
127       always succeed) in the order given. The first one that can be
128       successfully loaded will be used. If, after this, still none could be
129       found, AnyEvent will fall back to a pure-perl event loop, which is not
130       very efficient, but should work everywhere.
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. Maybe you should tell their authors
143       to use AnyEvent so their modules work together with others
144       seamlessly...
145
146       The pure-perl implementation of AnyEvent is called
147       "AnyEvent::Impl::Perl". Like other event modules you can load it
148       explicitly and enjoy the high 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 practise in
163       Perl and the latter stems from the fact that exception handling differs
164       widely between event loops.
165
166       To disable the 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       An any 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 readyness 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 once only. 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 missing.
254
255       The callback will be rescheduled before invoking the callback, but no
256       attempt is done 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 about these issues is EV, which offers both relative
289       (ev_timer, based on true relative time) and absolute (ev_periodic,
290       based on 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 it's 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 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 callback
328           at time=500 (assume no other callbacks delay processing). In your
329           callback, you wait a second by executing "sleep 1" (blocking the
330           process for a second) and then (at time=501) you create a relative
331           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::Impl::Perl) cache the
359           current time for each loop iteration (see the discussion of
360           AnyEvent->now, 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 get delayed indefinitely,
417       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 it's best, which means in some cases,
430       signals will be delayed. The maximum time a signal might be delayed is
431       specified in $AnyEvent::MAX_SIGNAL_LATENCY (default: 10 seconds). This
432       variable can be changed only before the first signal watcher is
433       created, and should be left alone otherwise. This variable determines
434       how often AnyEvent polls for signals (in case a wake-up was missed).
435       Higher values will cause fewer spurious wake-ups, which is better for
436       power and CPU saving.
437
438       All these problems can be avoided by installing the optional
439       Async::Interrupt module, which works with most event loops. It will not
440       work with inherently broken event loops such as Event or Event::Lib
441       (and not with POE currently, as POE does it's own workaround with one-
442       second latency). For those, you just have to suffer the delays.
443
444   CHILD PROCESS WATCHERS
445          $w = AnyEvent->child (pid => <process id>, cb => <callback>);
446
447       You can also watch on a child process exit and catch its exit status.
448
449       The child process is specified by the "pid" argument (one some
450       backends, using 0 watches for any child process exit, on others this
451       will croak). The watcher will be triggered only when the child process
452       has finished and an exit status is available, not on any trace events
453       (stopped/continued).
454
455       The callback will be called with the pid and exit status (as returned
456       by waitpid), so unlike other watcher types, you can rely on child
457       watcher callback arguments.
458
459       This watcher type works by installing a signal handler for "SIGCHLD",
460       and since it cannot be shared, nothing else should use SIGCHLD or reap
461       random child processes (waiting for specific child processes, e.g.
462       inside "system", is just fine).
463
464       There is a slight catch to child watchers, however: you usually start
465       them after the child process was created, and this means the process
466       could have exited already (and no SIGCHLD will be sent anymore).
467
468       Not all event models handle this correctly (neither POE nor IO::Async
469       do, see their AnyEvent::Impl manpages for details), but even for event
470       models that do handle this correctly, they usually need to be loaded
471       before the process exits (i.e. before you fork in the first place).
472       AnyEvent's pure perl event loop handles all cases correctly regardless
473       of when you start the watcher.
474
475       This means you cannot create a child watcher as the very first thing in
476       an AnyEvent program, you have to create at least one watcher before you
477       "fork" the child (alternatively, you can call "AnyEvent::detect").
478
479       As most event loops do not support waiting for child events, they will
480       be emulated by AnyEvent in most cases, in which the latency and race
481       problems mentioned in the description of signal watchers apply.
482
483       Example: fork a process and wait for it
484
485          my $done = AnyEvent->condvar;
486
487          my $pid = fork or exit 5;
488
489          my $w = AnyEvent->child (
490             pid => $pid,
491             cb  => sub {
492                my ($pid, $status) = @_;
493                warn "pid $pid exited with status $status";
494                $done->send;
495             },
496          );
497
498          # do something else, then wait for process exit
499          $done->recv;
500
501   IDLE WATCHERS
502          $w = AnyEvent->idle (cb => <callback>);
503
504       Repeatedly invoke the callback after the process becomes idle, until
505       either the watcher is destroyed or new events have been detected.
506
507       Idle watchers are useful when there is a need to do something, but it
508       is not so important (or wise) to do it instantly. The callback will be
509       invoked only when there is "nothing better to do", which is usually
510       defined as "all outstanding events have been handled and no new events
511       have been detected". That means that idle watchers ideally get invoked
512       when the event loop has just polled for new events but none have been
513       detected. Instead of blocking to wait for more events, the idle
514       watchers will be invoked.
515
516       Unfortunately, most event loops do not really support idle watchers
517       (only EV, Event and Glib do it in a usable fashion) - for the rest,
518       AnyEvent will simply call the callback "from time to time".
519
520       Example: read lines from STDIN, but only process them when the program
521       is otherwise idle:
522
523          my @lines; # read data
524          my $idle_w;
525          my $io_w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
526             push @lines, scalar <STDIN>;
527
528             # start an idle watcher, if not already done
529             $idle_w ||= AnyEvent->idle (cb => sub {
530                # handle only one line, when there are lines left
531                if (my $line = shift @lines) {
532                   print "handled when idle: $line";
533                } else {
534                   # otherwise disable the idle watcher again
535                   undef $idle_w;
536                }
537             });
538          });
539
540   CONDITION VARIABLES
541          $cv = AnyEvent->condvar;
542
543          $cv->send (<list>);
544          my @res = $cv->recv;
545
546       If you are familiar with some event loops you will know that all of
547       them require you to run some blocking "loop", "run" or similar function
548       that will actively watch for new events and call your callbacks.
549
550       AnyEvent is slightly different: it expects somebody else to run the
551       event loop and will only block when necessary (usually when told by the
552       user).
553
554       The tool to do that is called a "condition variable", so called because
555       they represent a condition that must become true.
556
557       Now is probably a good time to look at the examples further below.
558
559       Condition variables can be created by calling the "AnyEvent->condvar"
560       method, usually without arguments. The only argument pair allowed is
561       "cb", which specifies a callback to be called when the condition
562       variable becomes true, with the condition variable as the first
563       argument (but not the results).
564
565       After creation, the condition variable is "false" until it becomes
566       "true" by calling the "send" method (or calling the condition variable
567       as if it were a callback, read about the caveats in the description for
568       the "->send" method).
569
570       Since condition variables are the most complex part of the AnyEvent
571       API, here are some different mental models of what they are - pick the
572       ones you can connect to:
573
574       ·   Condition variables are like callbacks - you can call them (and
575           pass them instead of callbacks). Unlike callbacks however, you can
576           also wait for them to be called.
577
578       ·   Condition variables are signals - one side can emit or send them,
579           the other side can wait for them, or install a handler that is
580           called when the signal fires.
581
582       ·   Condition variables are like "Merge Points" - points in your
583           program where you merge multiple independent results/control flows
584           into one.
585
586       ·   Condition variables represent a transaction - function that start
587           some kind of transaction can return them, leaving the caller the
588           choice between waiting in a blocking fashion, or setting a
589           callback.
590
591       ·   Condition variables represent future values, or promises to deliver
592           some result, long before the result is available.
593
594       Condition variables are very useful to signal that something has
595       finished, for example, if you write a module that does asynchronous
596       http requests, then a condition variable would be the ideal candidate
597       to signal the availability of results. The user can either act when the
598       callback is called or can synchronously "->recv" for the results.
599
600       You can also use them to simulate traditional event loops - for
601       example, you can block your main program until an event occurs - for
602       example, you could "->recv" in your main program until the user clicks
603       the Quit button of your app, which would "->send" the "quit" event.
604
605       Note that condition variables recurse into the event loop - if you have
606       two pieces of code that call "->recv" in a round-robin fashion, you
607       lose. Therefore, condition variables are good to export to your caller,
608       but you should avoid making a blocking wait yourself, at least in
609       callbacks, as this asks for trouble.
610
611       Condition variables are represented by hash refs in perl, and the keys
612       used by AnyEvent itself are all named "_ae_XXX" to make subclassing
613       easy (it is often useful to build your own transaction class on top of
614       AnyEvent). To subclass, use "AnyEvent::CondVar" as base class and call
615       it's "new" method in your own "new" method.
616
617       There are two "sides" to a condition variable - the "producer side"
618       which eventually calls "-> send", and the "consumer side", which waits
619       for the send to occur.
620
621       Example: wait for a timer.
622
623          # condition: "wait till the timer is fired"
624          my $timer_fired = AnyEvent->condvar;
625
626          # create the timer - we could wait for, say
627          # a handle becomign ready, or even an
628          # AnyEvent::HTTP request to finish, but
629          # in this case, we simply use a timer:
630          my $w = AnyEvent->timer (
631             after => 1,
632             cb    => sub { $timer_fired->send },
633          );
634
635          # this "blocks" (while handling events) till the callback
636          # calls ->send
637          $timer_fired->recv;
638
639       Example: wait for a timer, but take advantage of the fact that
640       condition variables are also callable directly.
641
642          my $done = AnyEvent->condvar;
643          my $delay = AnyEvent->timer (after => 5, cb => $done);
644          $done->recv;
645
646       Example: Imagine an API that returns a condvar and doesn't support
647       callbacks. This is how you make a synchronous call, for example from
648       the main program:
649
650          use AnyEvent::CouchDB;
651
652          ...
653
654          my @info = $couchdb->info->recv;
655
656       And this is how you would just set a callback to be called whenever the
657       results are available:
658
659          $couchdb->info->cb (sub {
660             my @info = $_[0]->recv;
661          });
662
663       METHODS FOR PRODUCERS
664
665       These methods should only be used by the producing side, i.e. the
666       code/module that eventually sends the signal. Note that it is also the
667       producer side which creates the condvar in most cases, but it isn't
668       uncommon for the consumer to create it as well.
669
670       $cv->send (...)
671           Flag the condition as ready - a running "->recv" and all further
672           calls to "recv" will (eventually) return after this method has been
673           called. If nobody is waiting the send will be remembered.
674
675           If a callback has been set on the condition variable, it is called
676           immediately from within send.
677
678           Any arguments passed to the "send" call will be returned by all
679           future "->recv" calls.
680
681           Condition variables are overloaded so one can call them directly
682           (as if they were a code reference). Calling them directly is the
683           same as calling "send".
684
685       $cv->croak ($error)
686           Similar to send, but causes all call's to "->recv" to invoke
687           "Carp::croak" with the given error message/object/scalar.
688
689           This can be used to signal any errors to the condition variable
690           user/consumer. Doing it this way instead of calling "croak"
691           directly delays the error detetcion, but has the overwhelmign
692           advantage that it diagnoses the error at the place where the result
693           is expected, and not deep in some event clalback without connection
694           to the actual code causing the problem.
695
696       $cv->begin ([group callback])
697       $cv->end
698           These two methods can be used to combine many transactions/events
699           into one. For example, a function that pings many hosts in parallel
700           might want to use a condition variable for the whole process.
701
702           Every call to "->begin" will increment a counter, and every call to
703           "->end" will decrement it.  If the counter reaches 0 in "->end",
704           the (last) callback passed to "begin" will be executed, passing the
705           condvar as first argument. That callback is supposed to call
706           "->send", but that is not required. If no group callback was set,
707           "send" will be called without any arguments.
708
709           You can think of "$cv->send" giving you an OR condition (one call
710           sends), while "$cv->begin" and "$cv->end" giving you an AND
711           condition (all "begin" calls must be "end"'ed before the condvar
712           sends).
713
714           Let's start with a simple example: you have two I/O watchers (for
715           example, STDOUT and STDERR for a program), and you want to wait for
716           both streams to close before activating a condvar:
717
718              my $cv = AnyEvent->condvar;
719
720              $cv->begin; # first watcher
721              my $w1 = AnyEvent->io (fh => $fh1, cb => sub {
722                 defined sysread $fh1, my $buf, 4096
723                    or $cv->end;
724              });
725
726              $cv->begin; # second watcher
727              my $w2 = AnyEvent->io (fh => $fh2, cb => sub {
728                 defined sysread $fh2, my $buf, 4096
729                    or $cv->end;
730              });
731
732              $cv->recv;
733
734           This works because for every event source (EOF on file handle),
735           there is one call to "begin", so the condvar waits for all calls to
736           "end" before sending.
737
738           The ping example mentioned above is slightly more complicated, as
739           the there are results to be passwd back, and the number of tasks
740           that are begung can potentially be zero:
741
742              my $cv = AnyEvent->condvar;
743
744              my %result;
745              $cv->begin (sub { shift->send (\%result) });
746
747              for my $host (@list_of_hosts) {
748                 $cv->begin;
749                 ping_host_then_call_callback $host, sub {
750                    $result{$host} = ...;
751                    $cv->end;
752                 };
753              }
754
755              $cv->end;
756
757           This code fragment supposedly pings a number of hosts and calls
758           "send" after results for all then have have been gathered - in any
759           order. To achieve this, the code issues a call to "begin" when it
760           starts each ping request and calls "end" when it has received some
761           result for it. Since "begin" and "end" only maintain a counter, the
762           order in which results arrive is not relevant.
763
764           There is an additional bracketing call to "begin" and "end" outside
765           the loop, which serves two important purposes: first, it sets the
766           callback to be called once the counter reaches 0, and second, it
767           ensures that "send" is called even when "no" hosts are being pinged
768           (the loop doesn't execute once).
769
770           This is the general pattern when you "fan out" into multiple (but
771           potentially none) subrequests: use an outer "begin"/"end" pair to
772           set the callback and ensure "end" is called at least once, and
773           then, for each subrequest you start, call "begin" and for each
774           subrequest you finish, call "end".
775
776       METHODS FOR CONSUMERS
777
778       These methods should only be used by the consuming side, i.e. the code
779       awaits the condition.
780
781       $cv->recv
782           Wait (blocking if necessary) until the "->send" or "->croak"
783           methods have been called on c<$cv>, while servicing other watchers
784           normally.
785
786           You can only wait once on a condition - additional calls are valid
787           but will return immediately.
788
789           If an error condition has been set by calling "->croak", then this
790           function will call "croak".
791
792           In list context, all parameters passed to "send" will be returned,
793           in scalar context only the first one will be returned.
794
795           Note that doing a blocking wait in a callback is not supported by
796           any event loop, that is, recursive invocation of a blocking
797           "->recv" is not allowed, and the "recv" call will "croak" if such a
798           condition is detected. This condition can be slightly loosened by
799           using Coro::AnyEvent, which allows you to do a blocking "->recv"
800           from any thread that doesn't run the event loop itself.
801
802           Not all event models support a blocking wait - some die in that
803           case (programs might want to do that to stay interactive), so if
804           you are using this from a module, never require a blocking wait.
805           Instead, let the caller decide whether the call will block or not
806           (for example, by coupling condition variables with some kind of
807           request results and supporting callbacks so the caller knows that
808           getting the result will not block, while still supporting blocking
809           waits if the caller so desires).
810
811           You can ensure that "-recv" never blocks by setting a callback and
812           only calling "->recv" from within that callback (or at a later
813           time). This will work even when the event loop does not support
814           blocking waits otherwise.
815
816       $bool = $cv->ready
817           Returns true when the condition is "true", i.e. whether "send" or
818           "croak" have been called.
819
820       $cb = $cv->cb ($cb->($cv))
821           This is a mutator function that returns the callback set and
822           optionally replaces it before doing so.
823
824           The callback will be called when the condition becomes (or already
825           was) "true", i.e. when "send" or "croak" are called (or were
826           called), with the only argument being the condition variable
827           itself. Calling "recv" inside the callback or at any later time is
828           guaranteed not to block.
829

SUPPORTED EVENT LOOPS/BACKENDS

831       The available backend classes are (every class has its own manpage):
832
833       Backends that are autoprobed when no other event loop can be found.
834           EV is the preferred backend when no other event loop seems to be in
835           use. If EV is not installed, then AnyEvent will fall back to its
836           own pure-perl implementation, which is available everywhere as it
837           comes with AnyEvent itself.
838
839              AnyEvent::Impl::EV        based on EV (interface to libev, best choice).
840              AnyEvent::Impl::Perl      pure-perl implementation, fast and portable.
841
842       Backends that are transparently being picked up when they are used.
843           These will be used when they are currently loaded when the first
844           watcher is created, in which case it is assumed that the
845           application is using them. This means that AnyEvent will
846           automatically pick the right backend when the main program loads an
847           event module before anything starts to create watchers. Nothing
848           special needs to be done by the main program.
849
850              AnyEvent::Impl::Event     based on Event, very stable, few glitches.
851              AnyEvent::Impl::Glib      based on Glib, slow but very stable.
852              AnyEvent::Impl::Tk        based on Tk, very broken.
853              AnyEvent::Impl::EventLib  based on Event::Lib, leaks memory and worse.
854              AnyEvent::Impl::POE       based on POE, very slow, some limitations.
855              AnyEvent::Impl::Irssi     used when running within irssi.
856
857       Backends with special needs.
858           Qt requires the Qt::Application to be instantiated first, but will
859           otherwise be picked up automatically. As long as the main program
860           instantiates the application before any AnyEvent watchers are
861           created, everything should just work.
862
863              AnyEvent::Impl::Qt        based on Qt.
864
865           Support for IO::Async can only be partial, as it is too broken and
866           architecturally limited to even support the AnyEvent API. It also
867           is the only event loop that needs the loop to be set explicitly, so
868           it can only be used by a main program knowing about AnyEvent. See
869           AnyEvent::Impl::Async for the gory details.
870
871              AnyEvent::Impl::IOAsync   based on IO::Async, cannot be autoprobed.
872
873       Event loops that are indirectly supported via other backends.
874           Some event loops can be supported via other modules:
875
876           There is no direct support for WxWidgets (Wx) or Prima.
877
878           WxWidgets has no support for watching file handles. However, you
879           can use WxWidgets through the POE adaptor, as POE has a Wx backend
880           that simply polls 20 times per second, which was considered to be
881           too horrible to even consider for AnyEvent.
882
883           Prima is not supported as nobody seems to be using it, but it has a
884           POE backend, so it can be supported through POE.
885
886           AnyEvent knows about both Prima and Wx, however, and will try to
887           load POE when detecting them, in the hope that POE will pick them
888           up, in which case everything will be automatic.
889

GLOBAL VARIABLES AND FUNCTIONS

891       These are not normally required to use AnyEvent, but can be useful to
892       write AnyEvent extension modules.
893
894       $AnyEvent::MODEL
895           Contains "undef" until the first watcher is being created, before
896           the backend has been autodetected.
897
898           Afterwards it contains the event model that is being used, which is
899           the name of the Perl class implementing the model. This class is
900           usually one of the "AnyEvent::Impl:xxx" modules, but can be any
901           other class in the case AnyEvent has been extended at runtime (e.g.
902           in rxvt-unicode it will be "urxvt::anyevent").
903
904       AnyEvent::detect
905           Returns $AnyEvent::MODEL, forcing autodetection of the event model
906           if necessary. You should only call this function right before you
907           would have created an AnyEvent watcher anyway, that is, as late as
908           possible at runtime, and not e.g. while initialising of your
909           module.
910
911           If you need to do some initialisation before AnyEvent watchers are
912           created, use "post_detect".
913
914       $guard = AnyEvent::post_detect { BLOCK }
915           Arranges for the code block to be executed as soon as the event
916           model is autodetected (or immediately if this has already
917           happened).
918
919           The block will be executed after the actual backend has been
920           detected ($AnyEvent::MODEL is set), but before any watchers have
921           been created, so it is possible to e.g. patch @AnyEvent::ISA or do
922           other initialisations - see the sources of AnyEvent::Strict or
923           AnyEvent::AIO to see how this is used.
924
925           The most common usage is to create some global watchers, without
926           forcing event module detection too early, for example,
927           AnyEvent::AIO creates and installs the global IO::AIO watcher in a
928           "post_detect" block to avoid autodetecting the event module at load
929           time.
930
931           If called in scalar or list context, then it creates and returns an
932           object that automatically removes the callback again when it is
933           destroyed (or "undef" when the hook was immediately executed). See
934           AnyEvent::AIO for a case where this is useful.
935
936           Example: Create a watcher for the IO::AIO module and store it in
937           $WATCHER. Only do so after the event loop is initialised, though.
938
939              our WATCHER;
940
941              my $guard = AnyEvent::post_detect {
942                 $WATCHER = AnyEvent->io (fh => IO::AIO::poll_fileno, poll => 'r', cb => \&IO::AIO::poll_cb);
943              };
944
945              # the ||= is important in case post_detect immediately runs the block,
946              # as to not clobber the newly-created watcher. assigning both watcher and
947              # post_detect guard to the same variable has the advantage of users being
948              # able to just C<undef $WATCHER> if the watcher causes them grief.
949
950              $WATCHER ||= $guard;
951
952       @AnyEvent::post_detect
953           If there are any code references in this array (you can "push" to
954           it before or after loading AnyEvent), then they will called
955           directly after the event loop has been chosen.
956
957           You should check $AnyEvent::MODEL before adding to this array,
958           though: if it is defined then the event loop has already been
959           detected, and the array will be ignored.
960
961           Best use "AnyEvent::post_detect { BLOCK }" when your application
962           allows it, as it takes care of these details.
963
964           This variable is mainly useful for modules that can do something
965           useful when AnyEvent is used and thus want to know when it is
966           initialised, but do not need to even load it by default. This array
967           provides the means to hook into AnyEvent passively, without loading
968           it.
969
970           Example: To load Coro::AnyEvent whenever Coro and AnyEvent are used
971           together, you could put this into Coro (this is the actual code
972           used by Coro to accomplish this):
973
974              if (defined $AnyEvent::MODEL) {
975                 # AnyEvent already initialised, so load Coro::AnyEvent
976                 require Coro::AnyEvent;
977              } else {
978                 # AnyEvent not yet initialised, so make sure to load Coro::AnyEvent
979                 # as soon as it is
980                 push @AnyEvent::post_detect, sub { require Coro::AnyEvent };
981              }
982

WHAT TO DO IN A MODULE

984       As a module author, you should "use AnyEvent" and call AnyEvent methods
985       freely, but you should not load a specific event module or rely on it.
986
987       Be careful when you create watchers in the module body - AnyEvent will
988       decide which event module to use as soon as the first method is called,
989       so by calling AnyEvent in your module body you force the user of your
990       module to load the event module first.
991
992       Never call "->recv" on a condition variable unless you know that the
993       "->send" method has been called on it already. This is because it will
994       stall the whole program, and the whole point of using events is to stay
995       interactive.
996
997       It is fine, however, to call "->recv" when the user of your module
998       requests it (i.e. if you create a http request object ad have a method
999       called "results" that returns the results, it should call "->recv"
1000       freely, as the user of your module knows what she is doing. always).
1001

WHAT TO DO IN THE MAIN PROGRAM

1003       There will always be a single main program - the only place that should
1004       dictate which event model to use.
1005
1006       If it doesn't care, it can just "use AnyEvent" and use it itself, or
1007       not do anything special (it does not need to be event-based) and let
1008       AnyEvent decide which implementation to chose if some module relies on
1009       it.
1010
1011       If the main program relies on a specific event model - for example, in
1012       Gtk2 programs you have to rely on the Glib module - you should load the
1013       event module before loading AnyEvent or any module that uses it:
1014       generally speaking, you should load it as early as possible. The reason
1015       is that modules might create watchers when they are loaded, and
1016       AnyEvent will decide on the event model to use as soon as it creates
1017       watchers, and it might chose the wrong one unless you load the correct
1018       one yourself.
1019
1020       You can chose to use a pure-perl implementation by loading the
1021       "AnyEvent::Impl::Perl" module, which gives you similar behaviour
1022       everywhere, but letting AnyEvent chose the model is generally better.
1023
1024   MAINLOOP EMULATION
1025       Sometimes (often for short test scripts, or even standalone programs
1026       who only want to use AnyEvent), you do not want to run a specific event
1027       loop.
1028
1029       In that case, you can use a condition variable like this:
1030
1031          AnyEvent->condvar->recv;
1032
1033       This has the effect of entering the event loop and looping forever.
1034
1035       Note that usually your program has some exit condition, in which case
1036       it is better to use the "traditional" approach of storing a condition
1037       variable somewhere, waiting for it, and sending it when the program
1038       should exit cleanly.
1039

OTHER MODULES

1041       The following is a non-exhaustive list of additional modules that use
1042       AnyEvent as a client and can therefore be mixed easily with other
1043       AnyEvent modules and other event loops in the same program. Some of the
1044       modules come as part of AnyEvent, the others are available via CPAN.
1045
1046       AnyEvent::Util
1047           Contains various utility functions that replace often-used but
1048           blocking functions such as "inet_aton" by event-/callback-based
1049           versions.
1050
1051       AnyEvent::Socket
1052           Provides various utility functions for (internet protocol) sockets,
1053           addresses and name resolution. Also functions to create non-
1054           blocking tcp connections or tcp servers, with IPv6 and SRV record
1055           support and more.
1056
1057       AnyEvent::Handle
1058           Provide read and write buffers, manages watchers for reads and
1059           writes, supports raw and formatted I/O, I/O queued and fully
1060           transparent and non-blocking SSL/TLS (via AnyEvent::TLS.
1061
1062       AnyEvent::DNS
1063           Provides rich asynchronous DNS resolver capabilities.
1064
1065       AnyEvent::HTTP, AnyEvent::IRC, AnyEvent::XMPP, AnyEvent::GPSD,
1066       AnyEvent::IGS, AnyEvent::FCP
1067           Implement event-based interfaces to the protocols of the same name
1068           (for the curious, IGS is the International Go Server and FCP is the
1069           Freenet Client Protocol).
1070
1071       AnyEvent::Handle::UDP
1072           Here be danger!
1073
1074           As Pauli would put it, "Not only is it not right, it's not even
1075           wrong!" - there are so many things wrong with
1076           AnyEvent::Handle::UDP, most notably it's use of a stream-based API
1077           with a protocol that isn't streamable, that the only way to improve
1078           it is to delete it.
1079
1080           It features data corruption (but typically only under load) and
1081           general confusion. On top, the author is not only clueless about
1082           UDP but also fact-resistant - some gems of his understanding:
1083           "connect doesn't work with UDP", "UDP packets are not IP packets",
1084           "UDP only has datagrams, not packets", "I don't need to implement
1085           proper error checking as UDP doesn't support error checking" and so
1086           on - he doesn't even understand what's wrong with his module when
1087           it is explained to him.
1088
1089       AnyEvent::DBI
1090           Executes DBI requests asynchronously in a proxy process for you,
1091           notifying you in an event-bnased way when the operation is
1092           finished.
1093
1094       AnyEvent::AIO
1095           Truly asynchronous (as opposed to non-blocking) I/O, should be in
1096           the toolbox of every event programmer. AnyEvent::AIO transparently
1097           fuses IO::AIO and AnyEvent together, giving AnyEvent access to
1098           event-based file I/O, and much more.
1099
1100       AnyEvent::HTTPD
1101           A simple embedded webserver.
1102
1103       AnyEvent::FastPing
1104           The fastest ping in the west.
1105
1106       Coro
1107           Has special support for AnyEvent via Coro::AnyEvent.
1108

SIMPLIFIED AE API

1110       Starting with version 5.0, AnyEvent officially supports a second, much
1111       simpler, API that is designed to reduce the calling, typing and memory
1112       overhead by using function call syntax and a fixed number of
1113       parameters.
1114
1115       See the AE manpage for details.
1116

ERROR AND EXCEPTION HANDLING

1118       In general, AnyEvent does not do any error handling - it relies on the
1119       caller to do that if required. The AnyEvent::Strict module (see also
1120       the "PERL_ANYEVENT_STRICT" environment variable, below) provides strict
1121       checking of all AnyEvent methods, however, which is highly useful
1122       during development.
1123
1124       As for exception handling (i.e. runtime errors and exceptions thrown
1125       while executing a callback), this is not only highly event-loop
1126       specific, but also not in any way wrapped by this module, as this is
1127       the job of the main program.
1128
1129       The pure perl event loop simply re-throws the exception (usually within
1130       "condvar->recv"), the Event and EV modules call "$Event/EV::DIED->()",
1131       Glib uses "install_exception_handler" and so on.
1132

ENVIRONMENT VARIABLES

1134       The following environment variables are used by this module or its
1135       submodules.
1136
1137       Note that AnyEvent will remove all environment variables starting with
1138       "PERL_ANYEVENT_" from %ENV when it is loaded while taint mode is
1139       enabled.
1140
1141       "PERL_ANYEVENT_VERBOSE"
1142           By default, AnyEvent will be completely silent except in fatal
1143           conditions. You can set this environment variable to make AnyEvent
1144           more talkative.
1145
1146           When set to 1 or higher, causes AnyEvent to warn about unexpected
1147           conditions, such as not being able to load the event model
1148           specified by "PERL_ANYEVENT_MODEL".
1149
1150           When set to 2 or higher, cause AnyEvent to report to STDERR which
1151           event model it chooses.
1152
1153           When set to 8 or higher, then AnyEvent will report extra
1154           information on which optional modules it loads and how it
1155           implements certain features.
1156
1157       "PERL_ANYEVENT_STRICT"
1158           AnyEvent does not do much argument checking by default, as thorough
1159           argument checking is very costly. Setting this variable to a true
1160           value will cause AnyEvent to load "AnyEvent::Strict" and then to
1161           thoroughly check the arguments passed to most method calls. If it
1162           finds any problems, it will croak.
1163
1164           In other words, enables "strict" mode.
1165
1166           Unlike "use strict" (or it's modern cousin, "use common::sense", it
1167           is definitely recommended to keep it off in production. Keeping
1168           "PERL_ANYEVENT_STRICT=1" in your environment while developing
1169           programs can be very useful, however.
1170
1171       "PERL_ANYEVENT_MODEL"
1172           This can be used to specify the event model to be used by AnyEvent,
1173           before auto detection and -probing kicks in. It must be a string
1174           consisting entirely of ASCII letters. The string "AnyEvent::Impl::"
1175           gets prepended and the resulting module name is loaded and if the
1176           load was successful, used as event model. If it fails to load
1177           AnyEvent will proceed with auto detection and -probing.
1178
1179           This functionality might change in future versions.
1180
1181           For example, to force the pure perl model (AnyEvent::Impl::Perl)
1182           you could start your program like this:
1183
1184              PERL_ANYEVENT_MODEL=Perl perl ...
1185
1186       "PERL_ANYEVENT_PROTOCOLS"
1187           Used by both AnyEvent::DNS and AnyEvent::Socket to determine
1188           preferences for IPv4 or IPv6. The default is unspecified (and might
1189           change, or be the result of auto probing).
1190
1191           Must be set to a comma-separated list of protocols or address
1192           families, current supported: "ipv4" and "ipv6". Only protocols
1193           mentioned will be used, and preference will be given to protocols
1194           mentioned earlier in the list.
1195
1196           This variable can effectively be used for denial-of-service attacks
1197           against local programs (e.g. when setuid), although the impact is
1198           likely small, as the program has to handle conenction and other
1199           failures anyways.
1200
1201           Examples: "PERL_ANYEVENT_PROTOCOLS=ipv4,ipv6" - prefer IPv4 over
1202           IPv6, but support both and try to use both.
1203           "PERL_ANYEVENT_PROTOCOLS=ipv4" - only support IPv4, never try to
1204           resolve or contact IPv6 addresses.
1205           "PERL_ANYEVENT_PROTOCOLS=ipv6,ipv4" support either IPv4 or IPv6,
1206           but prefer IPv6 over IPv4.
1207
1208       "PERL_ANYEVENT_EDNS0"
1209           Used by AnyEvent::DNS to decide whether to use the EDNS0 extension
1210           for DNS. This extension is generally useful to reduce DNS traffic,
1211           but some (broken) firewalls drop such DNS packets, which is why it
1212           is off by default.
1213
1214           Setting this variable to 1 will cause AnyEvent::DNS to announce
1215           EDNS0 in its DNS requests.
1216
1217       "PERL_ANYEVENT_MAX_FORKS"
1218           The maximum number of child processes that
1219           "AnyEvent::Util::fork_call" will create in parallel.
1220
1221       "PERL_ANYEVENT_MAX_OUTSTANDING_DNS"
1222           The default value for the "max_outstanding" parameter for the
1223           default DNS resolver - this is the maximum number of parallel DNS
1224           requests that are sent to the DNS server.
1225
1226       "PERL_ANYEVENT_RESOLV_CONF"
1227           The file to use instead of /etc/resolv.conf (or OS-specific
1228           configuration) in the default resolver. When set to the empty
1229           string, no default config will be used.
1230
1231       "PERL_ANYEVENT_CA_FILE", "PERL_ANYEVENT_CA_PATH".
1232           When neither "ca_file" nor "ca_path" was specified during
1233           AnyEvent::TLS context creation, and either of these environment
1234           variables exist, they will be used to specify CA certificate
1235           locations instead of a system-dependent default.
1236
1237       "PERL_ANYEVENT_AVOID_GUARD" and "PERL_ANYEVENT_AVOID_ASYNC_INTERRUPT"
1238           When these are set to 1, then the respective modules are not
1239           loaded. Mostly good for testing AnyEvent itself.
1240

SUPPLYING YOUR OWN EVENT MODEL INTERFACE

1242       This is an advanced topic that you do not normally need to use AnyEvent
1243       in a module. This section is only of use to event loop authors who want
1244       to provide AnyEvent compatibility.
1245
1246       If you need to support another event library which isn't directly
1247       supported by AnyEvent, you can supply your own interface to it by
1248       pushing, before the first watcher gets created, the package name of the
1249       event module and the package name of the interface to use onto
1250       @AnyEvent::REGISTRY. You can do that before and even without loading
1251       AnyEvent, so it is reasonably cheap.
1252
1253       Example:
1254
1255          push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
1256
1257       This tells AnyEvent to (literally) use the "urxvt::anyevent::"
1258       package/class when it finds the "urxvt" package/module is already
1259       loaded.
1260
1261       When AnyEvent is loaded and asked to find a suitable event model, it
1262       will first check for the presence of urxvt by trying to "use" the
1263       "urxvt::anyevent" module.
1264
1265       The class should provide implementations for all watcher types. See
1266       AnyEvent::Impl::EV (source code), AnyEvent::Impl::Glib (Source code)
1267       and so on for actual examples. Use "perldoc -m AnyEvent::Impl::Glib" to
1268       see the sources.
1269
1270       If you don't provide "signal" and "child" watchers than AnyEvent will
1271       provide suitable (hopefully) replacements.
1272
1273       The above example isn't fictitious, the rxvt-unicode (a.k.a. urxvt)
1274       terminal emulator uses the above line as-is. An interface isn't
1275       included in AnyEvent because it doesn't make sense outside the embedded
1276       interpreter inside rxvt-unicode, and it is updated and maintained as
1277       part of the rxvt-unicode distribution.
1278
1279       rxvt-unicode also cheats a bit by not providing blocking access to
1280       condition variables: code blocking while waiting for a condition will
1281       "die". This still works with most modules/usages, and blocking calls
1282       must not be done in an interactive application, so it makes sense.
1283

EXAMPLE PROGRAM

1285       The following program uses an I/O watcher to read data from STDIN, a
1286       timer to display a message once per second, and a condition variable to
1287       quit the program when the user enters quit:
1288
1289          use AnyEvent;
1290
1291          my $cv = AnyEvent->condvar;
1292
1293          my $io_watcher = AnyEvent->io (
1294             fh   => \*STDIN,
1295             poll => 'r',
1296             cb   => sub {
1297                warn "io event <$_[0]>\n";   # will always output <r>
1298                chomp (my $input = <STDIN>); # read a line
1299                warn "read: $input\n";       # output what has been read
1300                $cv->send if $input =~ /^q/i; # quit program if /^q/i
1301             },
1302          );
1303
1304          my $time_watcher = AnyEvent->timer (after => 1, interval => 1, cb => sub {
1305             warn "timeout\n"; # print 'timeout' at most every second
1306          });
1307
1308          $cv->recv; # wait until user enters /^q/i
1309

REAL-WORLD EXAMPLE

1311       Consider the Net::FCP module. It features (among others) the following
1312       API calls, which are to freenet what HTTP GET requests are to http:
1313
1314          my $data = $fcp->client_get ($url); # blocks
1315
1316          my $transaction = $fcp->txn_client_get ($url); # does not block
1317          $transaction->cb ( sub { ... } ); # set optional result callback
1318          my $data = $transaction->result; # possibly blocks
1319
1320       The "client_get" method works like "LWP::Simple::get": it requests the
1321       given URL and waits till the data has arrived. It is defined to be:
1322
1323          sub client_get { $_[0]->txn_client_get ($_[1])->result }
1324
1325       And in fact is automatically generated. This is the blocking API of
1326       Net::FCP, and it works as simple as in any other, similar, module.
1327
1328       More complicated is "txn_client_get": It only creates a transaction
1329       (completion, result, ...) object and initiates the transaction.
1330
1331          my $txn = bless { }, Net::FCP::Txn::;
1332
1333       It also creates a condition variable that is used to signal the
1334       completion of the request:
1335
1336          $txn->{finished} = AnyAvent->condvar;
1337
1338       It then creates a socket in non-blocking mode.
1339
1340          socket $txn->{fh}, ...;
1341          fcntl $txn->{fh}, F_SETFL, O_NONBLOCK;
1342          connect $txn->{fh}, ...
1343             and !$!{EWOULDBLOCK}
1344             and !$!{EINPROGRESS}
1345             and Carp::croak "unable to connect: $!\n";
1346
1347       Then it creates a write-watcher which gets called whenever an error
1348       occurs or the connection succeeds:
1349
1350          $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w });
1351
1352       And returns this transaction object. The "fh_ready_w" callback gets
1353       called as soon as the event loop detects that the socket is ready for
1354       writing.
1355
1356       The "fh_ready_w" method makes the socket blocking again, writes the
1357       request data and replaces the watcher by a read watcher (waiting for
1358       reply data). The actual code is more complicated, but that doesn't
1359       matter for this example:
1360
1361          fcntl $txn->{fh}, F_SETFL, 0;
1362          syswrite $txn->{fh}, $txn->{request}
1363             or die "connection or write error";
1364          $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r });
1365
1366       Again, "fh_ready_r" waits till all data has arrived, and then stores
1367       the result and signals any possible waiters that the request has
1368       finished:
1369
1370          sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf};
1371
1372          if (end-of-file or data complete) {
1373            $txn->{result} = $txn->{buf};
1374            $txn->{finished}->send;
1375            $txb->{cb}->($txn) of $txn->{cb}; # also call callback
1376          }
1377
1378       The "result" method, finally, just waits for the finished signal (if
1379       the request was already finished, it doesn't wait, of course, and
1380       returns the data:
1381
1382          $txn->{finished}->recv;
1383          return $txn->{result};
1384
1385       The actual code goes further and collects all errors ("die"s,
1386       exceptions) that occurred during request processing. The "result"
1387       method detects whether an exception as thrown (it is stored inside the
1388       $txn object) and just throws the exception, which means connection
1389       errors and other problems get reported to the code that tries to use
1390       the result, not in a random callback.
1391
1392       All of this enables the following usage styles:
1393
1394       1. Blocking:
1395
1396          my $data = $fcp->client_get ($url);
1397
1398       2. Blocking, but running in parallel:
1399
1400          my @datas = map $_->result,
1401                         map $fcp->txn_client_get ($_),
1402                            @urls;
1403
1404       Both blocking examples work without the module user having to know
1405       anything about events.
1406
1407       3a. Event-based in a main program, using any supported event module:
1408
1409          use EV;
1410
1411          $fcp->txn_client_get ($url)->cb (sub {
1412             my $txn = shift;
1413             my $data = $txn->result;
1414             ...
1415          });
1416
1417          EV::loop;
1418
1419       3b. The module user could use AnyEvent, too:
1420
1421          use AnyEvent;
1422
1423          my $quit = AnyEvent->condvar;
1424
1425          $fcp->txn_client_get ($url)->cb (sub {
1426             ...
1427             $quit->send;
1428          });
1429
1430          $quit->recv;
1431

BENCHMARKS

1433       To give you an idea of the performance and overheads that AnyEvent adds
1434       over the event loops themselves and to give you an impression of the
1435       speed of various event loops I prepared some benchmarks.
1436
1437   BENCHMARKING ANYEVENT OVERHEAD
1438       Here is a benchmark of various supported event models used natively and
1439       through AnyEvent. The benchmark creates a lot of timers (with a zero
1440       timeout) and I/O watchers (watching STDOUT, a pty, to become writable,
1441       which it is), lets them fire exactly once and destroys them again.
1442
1443       Source code for this benchmark is found as eg/bench in the AnyEvent
1444       distribution. It uses the AE interface, which makes a real difference
1445       for the EV and Perl backends only.
1446
1447       Explanation of the columns
1448
1449       watcher is the number of event watchers created/destroyed. Since
1450       different event models feature vastly different performances, each
1451       event loop was given a number of watchers so that overall runtime is
1452       acceptable and similar between tested event loop (and keep them from
1453       crashing): Glib would probably take thousands of years if asked to
1454       process the same number of watchers as EV in this benchmark.
1455
1456       bytes is the number of bytes (as measured by the resident set size,
1457       RSS) consumed by each watcher. This method of measuring captures both C
1458       and Perl-based overheads.
1459
1460       create is the time, in microseconds (millionths of seconds), that it
1461       takes to create a single watcher. The callback is a closure shared
1462       between all watchers, to avoid adding memory overhead. That means
1463       closure creation and memory usage is not included in the figures.
1464
1465       invoke is the time, in microseconds, used to invoke a simple callback.
1466       The callback simply counts down a Perl variable and after it was
1467       invoked "watcher" times, it would "->send" a condvar once to signal the
1468       end of this phase.
1469
1470       destroy is the time, in microseconds, that it takes to destroy a single
1471       watcher.
1472
1473       Results
1474
1475                 name watchers bytes create invoke destroy comment
1476                EV/EV   100000   223   0.47   0.43    0.27 EV native interface
1477               EV/Any   100000   223   0.48   0.42    0.26 EV + AnyEvent watchers
1478         Coro::EV/Any   100000   223   0.47   0.42    0.26 coroutines + Coro::Signal
1479             Perl/Any   100000   431   2.70   0.74    0.92 pure perl implementation
1480          Event/Event    16000   516  31.16  31.84    0.82 Event native interface
1481            Event/Any    16000  1203  42.61  34.79    1.80 Event + AnyEvent watchers
1482          IOAsync/Any    16000  1911  41.92  27.45   16.81 via IO::Async::Loop::IO_Poll
1483          IOAsync/Any    16000  1726  40.69  26.37   15.25 via IO::Async::Loop::Epoll
1484             Glib/Any    16000  1118  89.00  12.57   51.17 quadratic behaviour
1485               Tk/Any     2000  1346  20.96  10.75    8.00 SEGV with >> 2000 watchers
1486              POE/Any     2000  6951 108.97 795.32   14.24 via POE::Loop::Event
1487              POE/Any     2000  6648  94.79 774.40  575.51 via POE::Loop::Select
1488
1489       Discussion
1490
1491       The benchmark does not measure scalability of the event loop very well.
1492       For example, a select-based event loop (such as the pure perl one) can
1493       never compete with an event loop that uses epoll when the number of
1494       file descriptors grows high. In this benchmark, all events become ready
1495       at the same time, so select/poll-based implementations get an unnatural
1496       speed boost.
1497
1498       Also, note that the number of watchers usually has a nonlinear effect
1499       on overall speed, that is, creating twice as many watchers doesn't take
1500       twice the time - usually it takes longer. This puts event loops tested
1501       with a higher number of watchers at a disadvantage.
1502
1503       To put the range of results into perspective, consider that on the
1504       benchmark machine, handling an event takes roughly 1600 CPU cycles with
1505       EV, 3100 CPU cycles with AnyEvent's pure perl loop and almost 3000000
1506       CPU cycles with POE.
1507
1508       "EV" is the sole leader regarding speed and memory use, which are both
1509       maximal/minimal, respectively. When using the AE API there is zero
1510       overhead (when going through the AnyEvent API create is about 5-6 times
1511       slower, with other times being equal, so still uses far less memory
1512       than any other event loop and is still faster than Event natively).
1513
1514       The pure perl implementation is hit in a few sweet spots (both the
1515       constant timeout and the use of a single fd hit optimisations in the
1516       perl interpreter and the backend itself). Nevertheless this shows that
1517       it adds very little overhead in itself. Like any select-based backend
1518       its performance becomes really bad with lots of file descriptors (and
1519       few of them active), of course, but this was not subject of this
1520       benchmark.
1521
1522       The "Event" module has a relatively high setup and callback invocation
1523       cost, but overall scores in on the third place.
1524
1525       "IO::Async" performs admirably well, about on par with "Event", even
1526       when using its pure perl backend.
1527
1528       "Glib"'s memory usage is quite a bit higher, but it features a faster
1529       callback invocation and overall ends up in the same class as "Event".
1530       However, Glib scales extremely badly, doubling the number of watchers
1531       increases the processing time by more than a factor of four, making it
1532       completely unusable when using larger numbers of watchers (note that
1533       only a single file descriptor was used in the benchmark, so
1534       inefficiencies of "poll" do not account for this).
1535
1536       The "Tk" adaptor works relatively well. The fact that it crashes with
1537       more than 2000 watchers is a big setback, however, as correctness takes
1538       precedence over speed. Nevertheless, its performance is surprising, as
1539       the file descriptor is dup()ed for each watcher. This shows that the
1540       dup() employed by some adaptors is not a big performance issue (it does
1541       incur a hidden memory cost inside the kernel which is not reflected in
1542       the figures above).
1543
1544       "POE", regardless of underlying event loop (whether using its pure perl
1545       select-based backend or the Event module, the POE-EV backend couldn't
1546       be tested because it wasn't working) shows abysmal performance and
1547       memory usage with AnyEvent: Watchers use almost 30 times as much memory
1548       as EV watchers, and 10 times as much memory as Event (the high memory
1549       requirements are caused by requiring a session for each watcher).
1550       Watcher invocation speed is almost 900 times slower than with
1551       AnyEvent's pure perl implementation.
1552
1553       The design of the POE adaptor class in AnyEvent can not really account
1554       for the performance issues, though, as session creation overhead is
1555       small compared to execution of the state machine, which is coded pretty
1556       optimally within AnyEvent::Impl::POE (and while everybody agrees that
1557       using multiple sessions is not a good approach, especially regarding
1558       memory usage, even the author of POE could not come up with a faster
1559       design).
1560
1561       Summary
1562
1563       ·   Using EV through AnyEvent is faster than any other event loop (even
1564           when used without AnyEvent), but most event loops have acceptable
1565           performance with or without AnyEvent.
1566
1567       ·   The overhead AnyEvent adds is usually much smaller than the
1568           overhead of the actual event loop, only with extremely fast event
1569           loops such as EV adds AnyEvent significant overhead.
1570
1571       ·   You should avoid POE like the plague if you want performance or
1572           reasonable memory usage.
1573
1574   BENCHMARKING THE LARGE SERVER CASE
1575       This benchmark actually benchmarks the event loop itself. It works by
1576       creating a number of "servers": each server consists of a socket pair,
1577       a timeout watcher that gets reset on activity (but never fires), and an
1578       I/O watcher waiting for input on one side of the socket. Each time the
1579       socket watcher reads a byte it will write that byte to a random other
1580       "server".
1581
1582       The effect is that there will be a lot of I/O watchers, only part of
1583       which are active at any one point (so there is a constant number of
1584       active fds for each loop iteration, but which fds these are is random).
1585       The timeout is reset each time something is read because that reflects
1586       how most timeouts work (and puts extra pressure on the event loops).
1587
1588       In this benchmark, we use 10000 socket pairs (20000 sockets), of which
1589       100 (1%) are active. This mirrors the activity of large servers with
1590       many connections, most of which are idle at any one point in time.
1591
1592       Source code for this benchmark is found as eg/bench2 in the AnyEvent
1593       distribution. It uses the AE interface, which makes a real difference
1594       for the EV and Perl backends only.
1595
1596       Explanation of the columns
1597
1598       sockets is the number of sockets, and twice the number of "servers" (as
1599       each server has a read and write socket end).
1600
1601       create is the time it takes to create a socket pair (which is
1602       nontrivial) and two watchers: an I/O watcher and a timeout watcher.
1603
1604       request, the most important value, is the time it takes to handle a
1605       single "request", that is, reading the token from the pipe and
1606       forwarding it to another server. This includes deleting the old timeout
1607       and creating a new one that moves the timeout into the future.
1608
1609       Results
1610
1611            name sockets create  request
1612              EV   20000  62.66     7.99
1613            Perl   20000  68.32    32.64
1614         IOAsync   20000 174.06   101.15 epoll
1615         IOAsync   20000 174.67   610.84 poll
1616           Event   20000 202.69   242.91
1617            Glib   20000 557.01  1689.52
1618             POE   20000 341.54 12086.32 uses POE::Loop::Event
1619
1620       Discussion
1621
1622       This benchmark does measure scalability and overall performance of the
1623       particular event loop.
1624
1625       EV is again fastest. Since it is using epoll on my system, the setup
1626       time is relatively high, though.
1627
1628       Perl surprisingly comes second. It is much faster than the C-based
1629       event loops Event and Glib.
1630
1631       IO::Async performs very well when using its epoll backend, and still
1632       quite good compared to Glib when using its pure perl backend.
1633
1634       Event suffers from high setup time as well (look at its code and you
1635       will understand why). Callback invocation also has a high overhead
1636       compared to the "$_->() for .."-style loop that the Perl event loop
1637       uses. Event uses select or poll in basically all documented
1638       configurations.
1639
1640       Glib is hit hard by its quadratic behaviour w.r.t. many watchers. It
1641       clearly fails to perform with many filehandles or in busy servers.
1642
1643       POE is still completely out of the picture, taking over 1000 times as
1644       long as EV, and over 100 times as long as the Perl implementation, even
1645       though it uses a C-based event loop in this case.
1646
1647       Summary
1648
1649       ·   The pure perl implementation performs extremely well.
1650
1651       ·   Avoid Glib or POE in large projects where performance matters.
1652
1653   BENCHMARKING SMALL SERVERS
1654       While event loops should scale (and select-based ones do not...) even
1655       to large servers, most programs we (or I :) actually write have only a
1656       few I/O watchers.
1657
1658       In this benchmark, I use the same benchmark program as in the large
1659       server case, but it uses only eight "servers", of which three are
1660       active at any one time. This should reflect performance for a small
1661       server relatively well.
1662
1663       The columns are identical to the previous table.
1664
1665       Results
1666
1667           name sockets create request
1668             EV      16  20.00    6.54
1669           Perl      16  25.75   12.62
1670          Event      16  81.27   35.86
1671           Glib      16  32.63   15.48
1672            POE      16 261.87  276.28 uses POE::Loop::Event
1673
1674       Discussion
1675
1676       The benchmark tries to test the performance of a typical small server.
1677       While knowing how various event loops perform is interesting, keep in
1678       mind that their overhead in this case is usually not as important, due
1679       to the small absolute number of watchers (that is, you need efficiency
1680       and speed most when you have lots of watchers, not when you only have a
1681       few of them).
1682
1683       EV is again fastest.
1684
1685       Perl again comes second. It is noticeably faster than the C-based event
1686       loops Event and Glib, although the difference is too small to really
1687       matter.
1688
1689       POE also performs much better in this case, but is is still far behind
1690       the others.
1691
1692       Summary
1693
1694       ·   C-based event loops perform very well with small number of
1695           watchers, as the management overhead dominates.
1696
1697   THE IO::Lambda BENCHMARK
1698       Recently I was told about the benchmark in the IO::Lambda manpage,
1699       which could be misinterpreted to make AnyEvent look bad. In fact, the
1700       benchmark simply compares IO::Lambda with POE, and IO::Lambda looks
1701       better (which shouldn't come as a surprise to anybody). As such, the
1702       benchmark is fine, and mostly shows that the AnyEvent backend from
1703       IO::Lambda isn't very optimal. But how would AnyEvent compare when used
1704       without the extra baggage? To explore this, I wrote the equivalent
1705       benchmark for AnyEvent.
1706
1707       The benchmark itself creates an echo-server, and then, for 500 times,
1708       connects to the echo server, sends a line, waits for the reply, and
1709       then creates the next connection. This is a rather bad benchmark, as it
1710       doesn't test the efficiency of the framework or much non-blocking I/O,
1711       but it is a benchmark nevertheless.
1712
1713          name                    runtime
1714          Lambda/select           0.330 sec
1715             + optimized          0.122 sec
1716          Lambda/AnyEvent         0.327 sec
1717             + optimized          0.138 sec
1718          Raw sockets/select      0.077 sec
1719          POE/select, components  0.662 sec
1720          POE/select, raw sockets 0.226 sec
1721          POE/select, optimized   0.404 sec
1722
1723          AnyEvent/select/nb      0.085 sec
1724          AnyEvent/EV/nb          0.068 sec
1725             +state machine       0.134 sec
1726
1727       The benchmark is also a bit unfair (my fault): the IO::Lambda/POE
1728       benchmarks actually make blocking connects and use 100% blocking I/O,
1729       defeating the purpose of an event-based solution. All of the newly
1730       written AnyEvent benchmarks use 100% non-blocking connects (using
1731       AnyEvent::Socket::tcp_connect and the asynchronous pure perl DNS
1732       resolver), so AnyEvent is at a disadvantage here, as non-blocking
1733       connects generally require a lot more bookkeeping and event handling
1734       than blocking connects (which involve a single syscall only).
1735
1736       The last AnyEvent benchmark additionally uses AnyEvent::Handle, which
1737       offers similar expressive power as POE and IO::Lambda, using
1738       conventional Perl syntax. This means that both the echo server and the
1739       client are 100% non-blocking, further placing it at a disadvantage.
1740
1741       As you can see, the AnyEvent + EV combination even beats the hand-
1742       optimised "raw sockets benchmark", while AnyEvent + its pure perl
1743       backend easily beats IO::Lambda and POE.
1744
1745       And even the 100% non-blocking version written using the high-level
1746       (and slow :) AnyEvent::Handle abstraction beats both POE and IO::Lambda
1747       higher level ("unoptimised") abstractions by a large margin, even
1748       though it does all of DNS, tcp-connect and socket I/O in a non-blocking
1749       way.
1750
1751       The two AnyEvent benchmarks programs can be found as eg/ae0.pl and
1752       eg/ae2.pl in the AnyEvent distribution, the remaining benchmarks are
1753       part of the IO::Lambda distribution and were used without any changes.
1754

SIGNALS

1756       AnyEvent currently installs handlers for these signals:
1757
1758       SIGCHLD
1759           A handler for "SIGCHLD" is installed by AnyEvent's child watcher
1760           emulation for event loops that do not support them natively. Also,
1761           some event loops install a similar handler.
1762
1763           Additionally, when AnyEvent is loaded and SIGCHLD is set to IGNORE,
1764           then AnyEvent will reset it to default, to avoid losing child exit
1765           statuses.
1766
1767       SIGPIPE
1768           A no-op handler is installed for "SIGPIPE" when $SIG{PIPE} is
1769           "undef" when AnyEvent gets loaded.
1770
1771           The rationale for this is that AnyEvent users usually do not really
1772           depend on SIGPIPE delivery (which is purely an optimisation for
1773           shell use, or badly-written programs), but "SIGPIPE" can cause
1774           spurious and rare program exits as a lot of people do not expect
1775           "SIGPIPE" when writing to some random socket.
1776
1777           The rationale for installing a no-op handler as opposed to ignoring
1778           it is that this way, the handler will be restored to defaults on
1779           exec.
1780
1781           Feel free to install your own handler, or reset it to defaults.
1782

RECOMMENDED/OPTIONAL MODULES

1784       One of AnyEvent's main goals is to be 100% Pure-Perl(tm): only perl
1785       (and it's built-in modules) are required to use it.
1786
1787       That does not mean that AnyEvent won't take advantage of some
1788       additional modules if they are installed.
1789
1790       This section explains which additional modules will be used, and how
1791       they affect AnyEvent's operation.
1792
1793       Async::Interrupt
1794           This slightly arcane module is used to implement fast signal
1795           handling: To my knowledge, there is no way to do completely race-
1796           free and quick signal handling in pure perl. To ensure that signals
1797           still get delivered, AnyEvent will start an interval timer to wake
1798           up perl (and catch the signals) with some delay (default is 10
1799           seconds, look for $AnyEvent::MAX_SIGNAL_LATENCY).
1800
1801           If this module is available, then it will be used to implement
1802           signal catching, which means that signals will not be delayed, and
1803           the event loop will not be interrupted regularly, which is more
1804           efficient (and good for battery life on laptops).
1805
1806           This affects not just the pure-perl event loop, but also other
1807           event loops that have no signal handling on their own (e.g. Glib,
1808           Tk, Qt).
1809
1810           Some event loops (POE, Event, Event::Lib) offer signal watchers
1811           natively, and either employ their own workarounds (POE) or use
1812           AnyEvent's workaround (using $AnyEvent::MAX_SIGNAL_LATENCY).
1813           Installing Async::Interrupt does nothing for those backends.
1814
1815       EV  This module isn't really "optional", as it is simply one of the
1816           backend event loops that AnyEvent can use. However, it is simply
1817           the best event loop available in terms of features, speed and
1818           stability: It supports the AnyEvent API optimally, implements all
1819           the watcher types in XS, does automatic timer adjustments even when
1820           no monotonic clock is available, can take avdantage of advanced
1821           kernel interfaces such as "epoll" and "kqueue", and is the fastest
1822           backend by far. You can even embed Glib/Gtk2 in it (or vice versa,
1823           see EV::Glib and Glib::EV).
1824
1825           If you only use backends that rely on another event loop (e.g.
1826           "Tk"), then this module will do nothing for you.
1827
1828       Guard
1829           The guard module, when used, will be used to implement
1830           "AnyEvent::Util::guard". This speeds up guards considerably (and
1831           uses a lot less memory), but otherwise doesn't affect guard
1832           operation much. It is purely used for performance.
1833
1834       JSON and JSON::XS
1835           One of these modules is required when you want to read or write
1836           JSON data via AnyEvent::Handle. JSON is also written in pure-perl,
1837           but can take advantage of the ultra-high-speed JSON::XS module when
1838           it is installed.
1839
1840       Net::SSLeay
1841           Implementing TLS/SSL in Perl is certainly interesting, but not very
1842           worthwhile: If this module is installed, then AnyEvent::Handle
1843           (with the help of AnyEvent::TLS), gains the ability to do TLS/SSL.
1844
1845       Time::HiRes
1846           This module is part of perl since release 5.008. It will be used
1847           when the chosen event library does not come with a timing source on
1848           it's own. The pure-perl event loop (AnyEvent::Impl::Perl) will
1849           additionally use it to try to use a monotonic clock for timing
1850           stability.
1851

FORK

1853       Most event libraries are not fork-safe. The ones who are usually are
1854       because they rely on inefficient but fork-safe "select" or "poll" calls
1855       - higher performance APIs such as BSD's kqueue or the dreaded Linux
1856       epoll are usually badly thought-out hacks that are incompatible with
1857       fork in one way or another. Only EV is fully fork-aware and ensures
1858       that you continue event-processing in both parent and child (or both,
1859       if you know what you are doing).
1860
1861       This means that, in general, you cannot fork and do event processing in
1862       the child if the event library was initialised before the fork (which
1863       usually happens when the first AnyEvent watcher is created, or the
1864       library is loaded).
1865
1866       If you have to fork, you must either do so before creating your first
1867       watcher OR you must not use AnyEvent at all in the child OR you must do
1868       something completely out of the scope of AnyEvent.
1869
1870       The problem of doing event processing in the parent and the child is
1871       much more complicated: even for backends that are fork-aware or fork-
1872       safe, their behaviour is not usually what you want: fork clones all
1873       watchers, that means all timers, I/O watchers etc. are active in both
1874       parent and child, which is almost never what you want. USing "exec" to
1875       start worker children from some kind of manage rprocess is usually
1876       preferred, because it is much easier and cleaner, at the expense of
1877       having to have another binary.
1878

SECURITY CONSIDERATIONS

1880       AnyEvent can be forced to load any event model via
1881       $ENV{PERL_ANYEVENT_MODEL}. While this cannot (to my knowledge) be used
1882       to execute arbitrary code or directly gain access, it can easily be
1883       used to make the program hang or malfunction in subtle ways, as
1884       AnyEvent watchers will not be active when the program uses a different
1885       event model than specified in the variable.
1886
1887       You can make AnyEvent completely ignore this variable by deleting it
1888       before the first watcher gets created, e.g. with a "BEGIN" block:
1889
1890          BEGIN { delete $ENV{PERL_ANYEVENT_MODEL} }
1891
1892          use AnyEvent;
1893
1894       Similar considerations apply to $ENV{PERL_ANYEVENT_VERBOSE}, as that
1895       can be used to probe what backend is used and gain other information
1896       (which is probably even less useful to an attacker than
1897       PERL_ANYEVENT_MODEL), and $ENV{PERL_ANYEVENT_STRICT}.
1898
1899       Note that AnyEvent will remove all environment variables starting with
1900       "PERL_ANYEVENT_" from %ENV when it is loaded while taint mode is
1901       enabled.
1902

BUGS

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

SEE ALSO

1911       Utility functions: AnyEvent::Util.
1912
1913       Event modules: EV, EV::Glib, Glib::EV, Event, Glib::Event, Glib, Tk,
1914       Event::Lib, Qt, POE.
1915
1916       Implementations: AnyEvent::Impl::EV, AnyEvent::Impl::Event,
1917       AnyEvent::Impl::Glib, AnyEvent::Impl::Tk, AnyEvent::Impl::Perl,
1918       AnyEvent::Impl::EventLib, AnyEvent::Impl::Qt, AnyEvent::Impl::POE,
1919       AnyEvent::Impl::IOAsync, Anyevent::Impl::Irssi.
1920
1921       Non-blocking file handles, sockets, TCP clients and servers:
1922       AnyEvent::Handle, AnyEvent::Socket, AnyEvent::TLS.
1923
1924       Asynchronous DNS: AnyEvent::DNS.
1925
1926       Coroutine support: Coro, Coro::AnyEvent, Coro::EV, Coro::Event,
1927
1928       Nontrivial usage examples: AnyEvent::GPSD, AnyEvent::XMPP,
1929       AnyEvent::HTTP.
1930

AUTHOR

1932          Marc Lehmann <schmorp@schmorp.de>
1933          http://home.schmorp.de/
1934
1935
1936
1937perl v5.12.1                      2010-06-08                       AnyEvent(3)
Impressum