ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/README
Revision: 1.45
Committed: Fri Jul 17 14:57:03 2009 UTC (14 years, 10 months ago) by root
Branch: MAIN
CVS Tags: rel-4_83
Changes since 1.44: +28 -31 lines
Log Message:
4.83

File Contents

# User Rev Content
1 root 1.25 NAME
2 root 1.2 AnyEvent - provide framework for multiple event loops
3    
4 root 1.39 EV, Event, Glib, Tk, Perl, Event::Lib, Qt and POE are various supported
5     event loops.
6 root 1.2
7     SYNOPSIS
8 root 1.4 use AnyEvent;
9 root 1.2
10 root 1.38 # file descriptor readable
11     my $w = AnyEvent->io (fh => $fh, poll => "r", cb => sub { ... });
12 root 1.29
13 root 1.38 # one-shot or repeating timers
14 root 1.29 my $w = AnyEvent->timer (after => $seconds, cb => sub { ... });
15     my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ...
16    
17     print AnyEvent->now; # prints current event loop time
18     print AnyEvent->time; # think Time::HiRes::time or simply CORE::time.
19    
20 root 1.38 # POSIX signal
21 root 1.29 my $w = AnyEvent->signal (signal => "TERM", cb => sub { ... });
22 root 1.3
23 root 1.38 # child process exit
24 root 1.29 my $w = AnyEvent->child (pid => $pid, cb => sub {
25     my ($pid, $status) = @_;
26 root 1.2 ...
27     });
28    
29 root 1.38 # called when event loop idle (if applicable)
30     my $w = AnyEvent->idle (cb => sub { ... });
31    
32 root 1.16 my $w = AnyEvent->condvar; # stores whether a condition was flagged
33 root 1.20 $w->send; # wake up current and all future recv's
34     $w->recv; # enters "main loop" till $condvar gets ->send
35 root 1.29 # use a condvar in callback mode:
36     $w->cb (sub { $_[0]->recv });
37 root 1.3
38 root 1.25 INTRODUCTION/TUTORIAL
39     This manpage is mainly a reference manual. If you are interested in a
40     tutorial or some gentle introduction, have a look at the AnyEvent::Intro
41     manpage.
42    
43 root 1.14 WHY YOU SHOULD USE THIS MODULE (OR NOT)
44     Glib, POE, IO::Async, Event... CPAN offers event models by the dozen
45     nowadays. So what is different about AnyEvent?
46    
47     Executive Summary: AnyEvent is *compatible*, AnyEvent is *free of
48     policy* and AnyEvent is *small and efficient*.
49    
50     First and foremost, *AnyEvent is not an event model* itself, it only
51 root 1.28 interfaces to whatever event model the main program happens to use, in a
52 root 1.14 pragmatic way. For event models and certain classes of immortals alike,
53 root 1.16 the statement "there can only be one" is a bitter reality: In general,
54     only one event loop can be active at the same time in a process.
55 root 1.28 AnyEvent cannot change this, but it can hide the differences between
56     those event loops.
57 root 1.14
58     The goal of AnyEvent is to offer module authors the ability to do event
59     programming (waiting for I/O or timer events) without subscribing to a
60     religion, a way of living, and most importantly: without forcing your
61     module users into the same thing by forcing them to use the same event
62     model you use.
63    
64 root 1.16 For modules like POE or IO::Async (which is a total misnomer as it is
65     actually doing all I/O *synchronously*...), using them in your module is
66     like joining a cult: After you joined, you are dependent on them and you
67 root 1.28 cannot use anything else, as they are simply incompatible to everything
68     that isn't them. What's worse, all the potential users of your module
69 root 1.16 are *also* forced to use the same event loop you use.
70    
71     AnyEvent is different: AnyEvent + POE works fine. AnyEvent + Glib works
72     fine. AnyEvent + Tk works fine etc. etc. but none of these work together
73 root 1.24 with the rest: POE + IO::Async? No go. Tk + Event? No go. Again: if your
74 root 1.16 module uses one of those, every user of your module has to use it, too.
75     But if your module uses AnyEvent, it works transparently with all event
76 root 1.28 models it supports (including stuff like IO::Async, as long as those use
77     one of the supported event loops. It is trivial to add new event loops
78     to AnyEvent, too, so it is future-proof).
79 root 1.14
80 root 1.16 In addition to being free of having to use *the one and only true event
81 root 1.14 model*, AnyEvent also is free of bloat and policy: with POE or similar
82 root 1.22 modules, you get an enormous amount of code and strict rules you have to
83     follow. AnyEvent, on the other hand, is lean and up to the point, by
84 root 1.16 only offering the functionality that is necessary, in as thin as a
85     wrapper as technically possible.
86 root 1.14
87 root 1.24 Of course, AnyEvent comes with a big (and fully optional!) toolbox of
88     useful functionality, such as an asynchronous DNS resolver, 100%
89     non-blocking connects (even with TLS/SSL, IPv6 and on broken platforms
90     such as Windows) and lots of real-world knowledge and workarounds for
91     platform bugs and differences.
92    
93     Now, if you *do want* lots of policy (this can arguably be somewhat
94 root 1.14 useful) and you want to force your users to use the one and only event
95     model, you should *not* use this module.
96    
97 root 1.2 DESCRIPTION
98     AnyEvent provides an identical interface to multiple event loops. This
99 root 1.6 allows module authors to utilise an event loop without forcing module
100 root 1.2 users to use the same event loop (as only a single event loop can
101     coexist peacefully at any one time).
102    
103 root 1.16 The interface itself is vaguely similar, but not identical to the Event
104 root 1.2 module.
105    
106 root 1.16 During the first call of any watcher-creation method, the module tries
107     to detect the currently loaded event loop by probing whether one of the
108 root 1.20 following modules is already loaded: EV, Event, Glib,
109     AnyEvent::Impl::Perl, Tk, Event::Lib, Qt, POE. The first one found is
110     used. If none are found, the module tries to load these modules
111 root 1.19 (excluding Tk, Event::Lib, Qt and POE as the pure perl adaptor should
112     always succeed) in the order given. The first one that can be
113     successfully loaded will be used. If, after this, still none could be
114     found, AnyEvent will fall back to a pure-perl event loop, which is not
115     very efficient, but should work everywhere.
116 root 1.6
117     Because AnyEvent first checks for modules that are already loaded,
118 root 1.16 loading an event model explicitly before first using AnyEvent will
119 root 1.6 likely make that model the default. For example:
120    
121     use Tk;
122     use AnyEvent;
123    
124     # .. AnyEvent will likely default to Tk
125    
126 root 1.16 The *likely* means that, if any module loads another event model and
127     starts using it, all bets are off. Maybe you should tell their authors
128     to use AnyEvent so their modules work together with others seamlessly...
129    
130 root 1.6 The pure-perl implementation of AnyEvent is called
131     "AnyEvent::Impl::Perl". Like other event modules you can load it
132 root 1.24 explicitly and enjoy the high availability of that event loop :)
133 root 1.6
134     WATCHERS
135     AnyEvent has the central concept of a *watcher*, which is an object that
136     stores relevant data for each kind of event you are waiting for, such as
137 root 1.22 the callback to call, the file handle to watch, etc.
138 root 1.6
139     These watchers are normal Perl objects with normal Perl lifetime. After
140     creating a watcher it will immediately "watch" for events and invoke the
141 root 1.16 callback when the event occurs (of course, only when the event model is
142     in control).
143    
144 root 1.36 Note that callbacks must not permanently change global variables
145     potentially in use by the event loop (such as $_ or $[) and that
146     callbacks must not "die". The former is good programming practise in
147     Perl and the latter stems from the fact that exception handling differs
148     widely between event loops.
149    
150 root 1.16 To disable the watcher you have to destroy it (e.g. by setting the
151     variable you store it in to "undef" or otherwise deleting all references
152     to it).
153 root 1.6
154     All watchers are created by calling a method on the "AnyEvent" class.
155    
156 root 1.16 Many watchers either are used with "recursion" (repeating timers for
157     example), or need to refer to their watcher object in other ways.
158    
159     An any way to achieve that is this pattern:
160    
161 root 1.25 my $w; $w = AnyEvent->type (arg => value ..., cb => sub {
162     # you can use $w here, for example to undef it
163     undef $w;
164     });
165 root 1.16
166     Note that "my $w; $w =" combination. This is necessary because in Perl,
167     my variables are only visible after the statement in which they are
168     declared.
169    
170 root 1.19 I/O WATCHERS
171 root 1.16 You can create an I/O watcher by calling the "AnyEvent->io" method with
172     the following mandatory key-value pairs as arguments:
173 root 1.6
174 root 1.43 "fh" is the Perl *file handle* (or a naked file descriptor) to watch for
175 root 1.36 events (AnyEvent might or might not keep a reference to this file
176     handle). Note that only file handles pointing to things for which
177     non-blocking operation makes sense are allowed. This includes sockets,
178     most character devices, pipes, fifos and so on, but not for example
179     files or block devices.
180    
181 root 1.16 "poll" must be a string that is either "r" or "w", which creates a
182 root 1.36 watcher waiting for "r"eadable or "w"ritable events, respectively.
183    
184     "cb" is the callback to invoke each time the file handle becomes ready.
185 root 1.16
186 root 1.19 Although the callback might get passed parameters, their value and
187     presence is undefined and you cannot rely on them. Portable AnyEvent
188     callbacks cannot use arguments passed to I/O watcher callbacks.
189    
190     The I/O watcher might use the underlying file descriptor or a copy of
191     it. You must not close a file handle as long as any watcher is active on
192     the underlying file descriptor.
193 root 1.16
194     Some event loops issue spurious readyness notifications, so you should
195     always use non-blocking calls when reading/writing from/to your file
196     handles.
197 root 1.6
198 root 1.28 Example: wait for readability of STDIN, then read a line and disable the
199     watcher.
200 root 1.6
201     my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
202     chomp (my $input = <STDIN>);
203     warn "read: $input\n";
204     undef $w;
205     });
206    
207 root 1.8 TIME WATCHERS
208     You can create a time watcher by calling the "AnyEvent->timer" method
209 root 1.6 with the following mandatory arguments:
210    
211 root 1.16 "after" specifies after how many seconds (fractional values are
212 root 1.19 supported) the callback should be invoked. "cb" is the callback to
213     invoke in that case.
214    
215     Although the callback might get passed parameters, their value and
216     presence is undefined and you cannot rely on them. Portable AnyEvent
217     callbacks cannot use arguments passed to time watcher callbacks.
218 root 1.6
219 root 1.28 The callback will normally be invoked once only. If you specify another
220     parameter, "interval", as a strictly positive number (> 0), then the
221     callback will be invoked regularly at that interval (in fractional
222     seconds) after the first invocation. If "interval" is specified with a
223     false value, then it is treated as if it were missing.
224    
225     The callback will be rescheduled before invoking the callback, but no
226     attempt is done to avoid timer drift in most backends, so the interval
227     is only approximate.
228 root 1.6
229 root 1.28 Example: fire an event after 7.7 seconds.
230 root 1.6
231     my $w = AnyEvent->timer (after => 7.7, cb => sub {
232     warn "timeout\n";
233     });
234    
235     # to cancel the timer:
236 root 1.13 undef $w;
237 root 1.6
238 root 1.28 Example 2: fire an event after 0.5 seconds, then roughly every second.
239 root 1.16
240 root 1.28 my $w = AnyEvent->timer (after => 0.5, interval => 1, cb => sub {
241     warn "timeout\n";
242 root 1.16 };
243    
244     TIMING ISSUES
245     There are two ways to handle timers: based on real time (relative, "fire
246     in 10 seconds") and based on wallclock time (absolute, "fire at 12
247     o'clock").
248    
249     While most event loops expect timers to specified in a relative way,
250     they use absolute time internally. This makes a difference when your
251     clock "jumps", for example, when ntp decides to set your clock backwards
252 root 1.18 from the wrong date of 2014-01-01 to 2008-01-01, a watcher that is
253     supposed to fire "after" a second might actually take six years to
254     finally fire.
255 root 1.16
256     AnyEvent cannot compensate for this. The only event loop that is
257     conscious about these issues is EV, which offers both relative
258 root 1.18 (ev_timer, based on true relative time) and absolute (ev_periodic, based
259     on wallclock time) timers.
260 root 1.16
261     AnyEvent always prefers relative timers, if available, matching the
262     AnyEvent API.
263    
264 root 1.24 AnyEvent has two additional methods that return the "current time":
265    
266     AnyEvent->time
267     This returns the "current wallclock time" as a fractional number of
268     seconds since the Epoch (the same thing as "time" or
269     "Time::HiRes::time" return, and the result is guaranteed to be
270     compatible with those).
271    
272     It progresses independently of any event loop processing, i.e. each
273     call will check the system clock, which usually gets updated
274     frequently.
275    
276     AnyEvent->now
277     This also returns the "current wallclock time", but unlike "time",
278     above, this value might change only once per event loop iteration,
279     depending on the event loop (most return the same time as "time",
280     above). This is the time that AnyEvent's timers get scheduled
281     against.
282    
283     *In almost all cases (in all cases if you don't care), this is the
284     function to call when you want to know the current time.*
285    
286     This function is also often faster then "AnyEvent->time", and thus
287     the preferred method if you want some timestamp (for example,
288     AnyEvent::Handle uses this to update it's activity timeouts).
289    
290     The rest of this section is only of relevance if you try to be very
291     exact with your timing, you can skip it without bad conscience.
292    
293     For a practical example of when these times differ, consider
294     Event::Lib and EV and the following set-up:
295    
296     The event loop is running and has just invoked one of your callback
297     at time=500 (assume no other callbacks delay processing). In your
298     callback, you wait a second by executing "sleep 1" (blocking the
299     process for a second) and then (at time=501) you create a relative
300     timer that fires after three seconds.
301    
302     With Event::Lib, "AnyEvent->time" and "AnyEvent->now" will both
303     return 501, because that is the current time, and the timer will be
304     scheduled to fire at time=504 (501 + 3).
305    
306     With EV, "AnyEvent->time" returns 501 (as that is the current time),
307     but "AnyEvent->now" returns 500, as that is the time the last event
308     processing phase started. With EV, your timer gets scheduled to run
309     at time=503 (500 + 3).
310    
311     In one sense, Event::Lib is more exact, as it uses the current time
312     regardless of any delays introduced by event processing. However,
313     most callbacks do not expect large delays in processing, so this
314     causes a higher drift (and a lot more system calls to get the
315     current time).
316    
317     In another sense, EV is more exact, as your timer will be scheduled
318     at the same time, regardless of how long event processing actually
319     took.
320    
321     In either case, if you care (and in most cases, you don't), then you
322     can get whatever behaviour you want with any event loop, by taking
323     the difference between "AnyEvent->time" and "AnyEvent->now" into
324     account.
325    
326 root 1.37 AnyEvent->now_update
327     Some event loops (such as EV or AnyEvent::Impl::Perl) cache the
328     current time for each loop iteration (see the discussion of
329     AnyEvent->now, above).
330    
331     When a callback runs for a long time (or when the process sleeps),
332     then this "current" time will differ substantially from the real
333     time, which might affect timers and time-outs.
334    
335     When this is the case, you can call this method, which will update
336     the event loop's idea of "current time".
337    
338     Note that updating the time *might* cause some events to be handled.
339    
340 root 1.16 SIGNAL WATCHERS
341     You can watch for signals using a signal watcher, "signal" is the signal
342 root 1.28 *name* in uppercase and without any "SIG" prefix, "cb" is the Perl
343     callback to be invoked whenever a signal occurs.
344 root 1.16
345 root 1.19 Although the callback might get passed parameters, their value and
346     presence is undefined and you cannot rely on them. Portable AnyEvent
347     callbacks cannot use arguments passed to signal watcher callbacks.
348    
349 root 1.22 Multiple signal occurrences can be clumped together into one callback
350     invocation, and callback invocation will be synchronous. Synchronous
351 root 1.16 means that it might take a while until the signal gets handled by the
352 root 1.22 process, but it is guaranteed not to interrupt any other callbacks.
353 root 1.16
354     The main advantage of using these watchers is that you can share a
355     signal between multiple watchers.
356    
357     This watcher might use %SIG, so programs overwriting those signals
358     directly will likely not work correctly.
359    
360     Example: exit on SIGINT
361    
362     my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });
363    
364     CHILD PROCESS WATCHERS
365     You can also watch on a child process exit and catch its exit status.
366    
367     The child process is specified by the "pid" argument (if set to 0, it
368 root 1.30 watches for any child process exit). The watcher will triggered only
369     when the child process has finished and an exit status is available, not
370     on any trace events (stopped/continued).
371    
372     The callback will be called with the pid and exit status (as returned by
373     waitpid), so unlike other watcher types, you *can* rely on child watcher
374     callback arguments.
375    
376     This watcher type works by installing a signal handler for "SIGCHLD",
377     and since it cannot be shared, nothing else should use SIGCHLD or reap
378     random child processes (waiting for specific child processes, e.g.
379     inside "system", is just fine).
380 root 1.19
381     There is a slight catch to child watchers, however: you usually start
382     them *after* the child process was created, and this means the process
383     could have exited already (and no SIGCHLD will be sent anymore).
384    
385 root 1.41 Not all event models handle this correctly (neither POE nor IO::Async
386     do, see their AnyEvent::Impl manpages for details), but even for event
387     models that *do* handle this correctly, they usually need to be loaded
388     before the process exits (i.e. before you fork in the first place).
389     AnyEvent's pure perl event loop handles all cases correctly regardless
390     of when you start the watcher.
391 root 1.19
392     This means you cannot create a child watcher as the very first thing in
393     an AnyEvent program, you *have* to create at least one watcher before
394     you "fork" the child (alternatively, you can call "AnyEvent::detect").
395    
396     Example: fork a process and wait for it
397    
398 root 1.25 my $done = AnyEvent->condvar;
399 root 1.40
400     my $pid = fork or exit 5;
401    
402     my $w = AnyEvent->child (
403 root 1.25 pid => $pid,
404     cb => sub {
405     my ($pid, $status) = @_;
406     warn "pid $pid exited with status $status";
407     $done->send;
408     },
409     );
410 root 1.40
411     # do something else, then wait for process exit
412 root 1.25 $done->recv;
413 root 1.19
414 root 1.38 IDLE WATCHERS
415     Sometimes there is a need to do something, but it is not so important to
416     do it instantly, but only when there is nothing better to do. This
417     "nothing better to do" is usually defined to be "no other events need
418     attention by the event loop".
419    
420     Idle watchers ideally get invoked when the event loop has nothing better
421     to do, just before it would block the process to wait for new events.
422     Instead of blocking, the idle watcher is invoked.
423    
424     Most event loops unfortunately do not really support idle watchers (only
425     EV, Event and Glib do it in a usable fashion) - for the rest, AnyEvent
426     will simply call the callback "from time to time".
427    
428     Example: read lines from STDIN, but only process them when the program
429     is otherwise idle:
430    
431     my @lines; # read data
432     my $idle_w;
433     my $io_w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
434     push @lines, scalar <STDIN>;
435    
436     # start an idle watcher, if not already done
437     $idle_w ||= AnyEvent->idle (cb => sub {
438     # handle only one line, when there are lines left
439     if (my $line = shift @lines) {
440     print "handled when idle: $line";
441     } else {
442     # otherwise disable the idle watcher again
443     undef $idle_w;
444     }
445     });
446     });
447    
448 root 1.16 CONDITION VARIABLES
449 root 1.20 If you are familiar with some event loops you will know that all of them
450     require you to run some blocking "loop", "run" or similar function that
451     will actively watch for new events and call your callbacks.
452    
453 root 1.45 AnyEvent is slightly different: it expects somebody else to run the
454     event loop and will only block when necessary (usually when told by the
455     user).
456 root 1.6
457 root 1.20 The instrument to do that is called a "condition variable", so called
458     because they represent a condition that must become true.
459 root 1.6
460 root 1.45 Now is probably a good time to look at the examples further below.
461    
462 root 1.20 Condition variables can be created by calling the "AnyEvent->condvar"
463     method, usually without arguments. The only argument pair allowed is
464     "cb", which specifies a callback to be called when the condition
465 root 1.29 variable becomes true, with the condition variable as the first argument
466     (but not the results).
467 root 1.20
468 root 1.22 After creation, the condition variable is "false" until it becomes
469     "true" by calling the "send" method (or calling the condition variable
470 root 1.23 as if it were a callback, read about the caveats in the description for
471     the "->send" method).
472 root 1.20
473     Condition variables are similar to callbacks, except that you can
474     optionally wait for them. They can also be called merge points - points
475 root 1.22 in time where multiple outstanding events have been processed. And yet
476     another way to call them is transactions - each condition variable can
477     be used to represent a transaction, which finishes at some point and
478 root 1.20 delivers a result.
479    
480     Condition variables are very useful to signal that something has
481     finished, for example, if you write a module that does asynchronous http
482     requests, then a condition variable would be the ideal candidate to
483     signal the availability of results. The user can either act when the
484     callback is called or can synchronously "->recv" for the results.
485    
486     You can also use them to simulate traditional event loops - for example,
487     you can block your main program until an event occurs - for example, you
488     could "->recv" in your main program until the user clicks the Quit
489     button of your app, which would "->send" the "quit" event.
490 root 1.16
491     Note that condition variables recurse into the event loop - if you have
492 root 1.22 two pieces of code that call "->recv" in a round-robin fashion, you
493 root 1.16 lose. Therefore, condition variables are good to export to your caller,
494     but you should avoid making a blocking wait yourself, at least in
495     callbacks, as this asks for trouble.
496 root 1.14
497 root 1.20 Condition variables are represented by hash refs in perl, and the keys
498     used by AnyEvent itself are all named "_ae_XXX" to make subclassing easy
499     (it is often useful to build your own transaction class on top of
500     AnyEvent). To subclass, use "AnyEvent::CondVar" as base class and call
501     it's "new" method in your own "new" method.
502    
503     There are two "sides" to a condition variable - the "producer side"
504     which eventually calls "-> send", and the "consumer side", which waits
505     for the send to occur.
506 root 1.6
507 root 1.22 Example: wait for a timer.
508 root 1.6
509 root 1.20 # wait till the result is ready
510     my $result_ready = AnyEvent->condvar;
511    
512     # do something such as adding a timer
513     # or socket watcher the calls $result_ready->send
514     # when the "result" is ready.
515     # in this case, we simply use a timer:
516     my $w = AnyEvent->timer (
517     after => 1,
518     cb => sub { $result_ready->send },
519     );
520    
521     # this "blocks" (while handling events) till the callback
522 root 1.45 # calls -<send
523 root 1.20 $result_ready->recv;
524    
525 root 1.22 Example: wait for a timer, but take advantage of the fact that condition
526 root 1.45 variables are also callable directly.
527 root 1.22
528     my $done = AnyEvent->condvar;
529     my $delay = AnyEvent->timer (after => 5, cb => $done);
530     $done->recv;
531    
532 root 1.29 Example: Imagine an API that returns a condvar and doesn't support
533     callbacks. This is how you make a synchronous call, for example from the
534     main program:
535    
536     use AnyEvent::CouchDB;
537    
538     ...
539    
540     my @info = $couchdb->info->recv;
541    
542 root 1.45 And this is how you would just set a callback to be called whenever the
543 root 1.29 results are available:
544    
545     $couchdb->info->cb (sub {
546     my @info = $_[0]->recv;
547     });
548    
549 root 1.20 METHODS FOR PRODUCERS
550     These methods should only be used by the producing side, i.e. the
551     code/module that eventually sends the signal. Note that it is also the
552     producer side which creates the condvar in most cases, but it isn't
553     uncommon for the consumer to create it as well.
554    
555     $cv->send (...)
556     Flag the condition as ready - a running "->recv" and all further
557     calls to "recv" will (eventually) return after this method has been
558     called. If nobody is waiting the send will be remembered.
559    
560     If a callback has been set on the condition variable, it is called
561     immediately from within send.
562    
563     Any arguments passed to the "send" call will be returned by all
564     future "->recv" calls.
565    
566 root 1.22 Condition variables are overloaded so one can call them directly (as
567 root 1.45 if they were a code reference). Calling them directly is the same as
568     calling "send".
569 root 1.22
570 root 1.20 $cv->croak ($error)
571     Similar to send, but causes all call's to "->recv" to invoke
572     "Carp::croak" with the given error message/object/scalar.
573    
574     This can be used to signal any errors to the condition variable
575 root 1.45 user/consumer. Doing it this way instead of calling "croak" directly
576     delays the error detetcion, but has the overwhelmign advantage that
577     it diagnoses the error at the place where the result is expected,
578     and not deep in some event clalback without connection to the actual
579     code causing the problem.
580 root 1.20
581     $cv->begin ([group callback])
582     $cv->end
583     These two methods can be used to combine many transactions/events
584     into one. For example, a function that pings many hosts in parallel
585     might want to use a condition variable for the whole process.
586    
587     Every call to "->begin" will increment a counter, and every call to
588     "->end" will decrement it. If the counter reaches 0 in "->end", the
589     (last) callback passed to "begin" will be executed. That callback is
590     *supposed* to call "->send", but that is not required. If no
591     callback was set, "send" will be called without any arguments.
592    
593 root 1.42 You can think of "$cv->send" giving you an OR condition (one call
594     sends), while "$cv->begin" and "$cv->end" giving you an AND
595     condition (all "begin" calls must be "end"'ed before the condvar
596     sends).
597    
598     Let's start with a simple example: you have two I/O watchers (for
599     example, STDOUT and STDERR for a program), and you want to wait for
600     both streams to close before activating a condvar:
601    
602     my $cv = AnyEvent->condvar;
603    
604     $cv->begin; # first watcher
605     my $w1 = AnyEvent->io (fh => $fh1, cb => sub {
606     defined sysread $fh1, my $buf, 4096
607     or $cv->end;
608     });
609    
610     $cv->begin; # second watcher
611     my $w2 = AnyEvent->io (fh => $fh2, cb => sub {
612     defined sysread $fh2, my $buf, 4096
613     or $cv->end;
614     });
615    
616     $cv->recv;
617    
618     This works because for every event source (EOF on file handle),
619     there is one call to "begin", so the condvar waits for all calls to
620     "end" before sending.
621    
622     The ping example mentioned above is slightly more complicated, as
623     the there are results to be passwd back, and the number of tasks
624     that are begung can potentially be zero:
625 root 1.20
626     my $cv = AnyEvent->condvar;
627    
628     my %result;
629     $cv->begin (sub { $cv->send (\%result) });
630    
631     for my $host (@list_of_hosts) {
632     $cv->begin;
633     ping_host_then_call_callback $host, sub {
634     $result{$host} = ...;
635     $cv->end;
636     };
637     }
638    
639     $cv->end;
640    
641     This code fragment supposedly pings a number of hosts and calls
642     "send" after results for all then have have been gathered - in any
643     order. To achieve this, the code issues a call to "begin" when it
644     starts each ping request and calls "end" when it has received some
645     result for it. Since "begin" and "end" only maintain a counter, the
646     order in which results arrive is not relevant.
647    
648     There is an additional bracketing call to "begin" and "end" outside
649     the loop, which serves two important purposes: first, it sets the
650     callback to be called once the counter reaches 0, and second, it
651     ensures that "send" is called even when "no" hosts are being pinged
652     (the loop doesn't execute once).
653    
654 root 1.42 This is the general pattern when you "fan out" into multiple (but
655     potentially none) subrequests: use an outer "begin"/"end" pair to
656     set the callback and ensure "end" is called at least once, and then,
657     for each subrequest you start, call "begin" and for each subrequest
658     you finish, call "end".
659 root 1.20
660     METHODS FOR CONSUMERS
661     These methods should only be used by the consuming side, i.e. the code
662     awaits the condition.
663    
664     $cv->recv
665     Wait (blocking if necessary) until the "->send" or "->croak" methods
666     have been called on c<$cv>, while servicing other watchers normally.
667    
668     You can only wait once on a condition - additional calls are valid
669     but will return immediately.
670    
671     If an error condition has been set by calling "->croak", then this
672     function will call "croak".
673    
674     In list context, all parameters passed to "send" will be returned,
675     in scalar context only the first one will be returned.
676 root 1.6
677 root 1.45 Note that doing a blocking wait in a callback is not supported by
678     any event loop, that is, recursive invocation of a blocking "->recv"
679     is not allowed, and the "recv" call will "croak" if such a condition
680     is detected. This condition can be slightly loosened by using
681     Coro::AnyEvent, which allows you to do a blocking "->recv" from any
682     thread that doesn't run the event loop itself.
683    
684 root 1.15 Not all event models support a blocking wait - some die in that case
685 root 1.16 (programs might want to do that to stay interactive), so *if you are
686 root 1.45 using this from a module, never require a blocking wait*. Instead,
687     let the caller decide whether the call will block or not (for
688     example, by coupling condition variables with some kind of request
689     results and supporting callbacks so the caller knows that getting
690     the result will not block, while still supporting blocking waits if
691     the caller so desires).
692 root 1.20
693     You can ensure that "-recv" never blocks by setting a callback and
694     only calling "->recv" from within that callback (or at a later
695     time). This will work even when the event loop does not support
696     blocking waits otherwise.
697    
698     $bool = $cv->ready
699     Returns true when the condition is "true", i.e. whether "send" or
700     "croak" have been called.
701    
702 root 1.29 $cb = $cv->cb ($cb->($cv))
703 root 1.20 This is a mutator function that returns the callback set and
704     optionally replaces it before doing so.
705    
706     The callback will be called when the condition becomes "true", i.e.
707 root 1.25 when "send" or "croak" are called, with the only argument being the
708     condition variable itself. Calling "recv" inside the callback or at
709     any later time is guaranteed not to block.
710 root 1.8
711 root 1.43 SUPPORTED EVENT LOOPS/BACKENDS
712     The available backend classes are (every class has its own manpage):
713 root 1.7
714 root 1.43 Backends that are autoprobed when no other event loop can be found.
715     EV is the preferred backend when no other event loop seems to be in
716     use. If EV is not installed, then AnyEvent will try Event, and,
717     failing that, will fall back to its own pure-perl implementation,
718     which is available everywhere as it comes with AnyEvent itself.
719 root 1.7
720 root 1.43 AnyEvent::Impl::EV based on EV (interface to libev, best choice).
721     AnyEvent::Impl::Event based on Event, very stable, few glitches.
722 root 1.20 AnyEvent::Impl::Perl pure-perl implementation, fast and portable.
723 root 1.43
724     Backends that are transparently being picked up when they are used.
725     These will be used when they are currently loaded when the first
726     watcher is created, in which case it is assumed that the application
727     is using them. This means that AnyEvent will automatically pick the
728     right backend when the main program loads an event module before
729     anything starts to create watchers. Nothing special needs to be done
730     by the main program.
731    
732     AnyEvent::Impl::Glib based on Glib, slow but very stable.
733     AnyEvent::Impl::Tk based on Tk, very broken.
734 root 1.18 AnyEvent::Impl::EventLib based on Event::Lib, leaks memory and worse.
735 root 1.43 AnyEvent::Impl::POE based on POE, very slow, some limitations.
736    
737     Backends with special needs.
738     Qt requires the Qt::Application to be instantiated first, but will
739     otherwise be picked up automatically. As long as the main program
740     instantiates the application before any AnyEvent watchers are
741     created, everything should just work.
742    
743     AnyEvent::Impl::Qt based on Qt.
744    
745     Support for IO::Async can only be partial, as it is too broken and
746     architecturally limited to even support the AnyEvent API. It also is
747     the only event loop that needs the loop to be set explicitly, so it
748     can only be used by a main program knowing about AnyEvent. See
749     AnyEvent::Impl::Async for the gory details.
750    
751     AnyEvent::Impl::IOAsync based on IO::Async, cannot be autoprobed.
752 root 1.19
753 root 1.43 Event loops that are indirectly supported via other backends.
754     Some event loops can be supported via other modules:
755 root 1.19
756 root 1.43 There is no direct support for WxWidgets (Wx) or Prima.
757    
758     WxWidgets has no support for watching file handles. However, you can
759     use WxWidgets through the POE adaptor, as POE has a Wx backend that
760     simply polls 20 times per second, which was considered to be too
761     horrible to even consider for AnyEvent.
762    
763     Prima is not supported as nobody seems to be using it, but it has a
764     POE backend, so it can be supported through POE.
765    
766     AnyEvent knows about both Prima and Wx, however, and will try to
767     load POE when detecting them, in the hope that POE will pick them
768     up, in which case everything will be automatic.
769    
770     GLOBAL VARIABLES AND FUNCTIONS
771     These are not normally required to use AnyEvent, but can be useful to
772     write AnyEvent extension modules.
773    
774     $AnyEvent::MODEL
775     Contains "undef" until the first watcher is being created, before
776     the backend has been autodetected.
777    
778     Afterwards it contains the event model that is being used, which is
779     the name of the Perl class implementing the model. This class is
780     usually one of the "AnyEvent::Impl:xxx" modules, but can be any
781     other class in the case AnyEvent has been extended at runtime (e.g.
782     in *rxvt-unicode* it will be "urxvt::anyevent").
783 root 1.7
784 root 1.8 AnyEvent::detect
785     Returns $AnyEvent::MODEL, forcing autodetection of the event model
786     if necessary. You should only call this function right before you
787 root 1.16 would have created an AnyEvent watcher anyway, that is, as late as
788 root 1.43 possible at runtime, and not e.g. while initialising of your module.
789    
790     If you need to do some initialisation before AnyEvent watchers are
791     created, use "post_detect".
792 root 1.8
793 root 1.20 $guard = AnyEvent::post_detect { BLOCK }
794     Arranges for the code block to be executed as soon as the event
795     model is autodetected (or immediately if this has already happened).
796    
797 root 1.43 The block will be executed *after* the actual backend has been
798     detected ($AnyEvent::MODEL is set), but *before* any watchers have
799     been created, so it is possible to e.g. patch @AnyEvent::ISA or do
800     other initialisations - see the sources of AnyEvent::Strict or
801     AnyEvent::AIO to see how this is used.
802    
803     The most common usage is to create some global watchers, without
804     forcing event module detection too early, for example, AnyEvent::AIO
805     creates and installs the global IO::AIO watcher in a "post_detect"
806     block to avoid autodetecting the event module at load time.
807    
808 root 1.20 If called in scalar or list context, then it creates and returns an
809     object that automatically removes the callback again when it is
810     destroyed. See Coro::BDB for a case where this is useful.
811    
812     @AnyEvent::post_detect
813     If there are any code references in this array (you can "push" to it
814     before or after loading AnyEvent), then they will called directly
815     after the event loop has been chosen.
816    
817     You should check $AnyEvent::MODEL before adding to this array,
818 root 1.43 though: if it is defined then the event loop has already been
819     detected, and the array will be ignored.
820    
821     Best use "AnyEvent::post_detect { BLOCK }" when your application
822     allows it,as it takes care of these details.
823 root 1.20
824 root 1.43 This variable is mainly useful for modules that can do something
825     useful when AnyEvent is used and thus want to know when it is
826     initialised, but do not need to even load it by default. This array
827     provides the means to hook into AnyEvent passively, without loading
828     it.
829 root 1.20
830 root 1.6 WHAT TO DO IN A MODULE
831     As a module author, you should "use AnyEvent" and call AnyEvent methods
832     freely, but you should not load a specific event module or rely on it.
833    
834 root 1.16 Be careful when you create watchers in the module body - AnyEvent will
835 root 1.6 decide which event module to use as soon as the first method is called,
836     so by calling AnyEvent in your module body you force the user of your
837     module to load the event module first.
838    
839 root 1.20 Never call "->recv" on a condition variable unless you *know* that the
840     "->send" method has been called on it already. This is because it will
841     stall the whole program, and the whole point of using events is to stay
842     interactive.
843 root 1.16
844 root 1.20 It is fine, however, to call "->recv" when the user of your module
845 root 1.16 requests it (i.e. if you create a http request object ad have a method
846 root 1.20 called "results" that returns the results, it should call "->recv"
847 root 1.16 freely, as the user of your module knows what she is doing. always).
848    
849 root 1.6 WHAT TO DO IN THE MAIN PROGRAM
850     There will always be a single main program - the only place that should
851     dictate which event model to use.
852    
853     If it doesn't care, it can just "use AnyEvent" and use it itself, or not
854 root 1.16 do anything special (it does not need to be event-based) and let
855     AnyEvent decide which implementation to chose if some module relies on
856     it.
857    
858 root 1.23 If the main program relies on a specific event model - for example, in
859     Gtk2 programs you have to rely on the Glib module - you should load the
860 root 1.16 event module before loading AnyEvent or any module that uses it:
861     generally speaking, you should load it as early as possible. The reason
862     is that modules might create watchers when they are loaded, and AnyEvent
863     will decide on the event model to use as soon as it creates watchers,
864     and it might chose the wrong one unless you load the correct one
865     yourself.
866 root 1.6
867 root 1.23 You can chose to use a pure-perl implementation by loading the
868     "AnyEvent::Impl::Perl" module, which gives you similar behaviour
869     everywhere, but letting AnyEvent chose the model is generally better.
870    
871     MAINLOOP EMULATION
872     Sometimes (often for short test scripts, or even standalone programs who
873     only want to use AnyEvent), you do not want to run a specific event
874     loop.
875    
876     In that case, you can use a condition variable like this:
877    
878     AnyEvent->condvar->recv;
879    
880     This has the effect of entering the event loop and looping forever.
881    
882     Note that usually your program has some exit condition, in which case it
883     is better to use the "traditional" approach of storing a condition
884     variable somewhere, waiting for it, and sending it when the program
885     should exit cleanly.
886 root 1.2
887 root 1.19 OTHER MODULES
888     The following is a non-exhaustive list of additional modules that use
889 root 1.43 AnyEvent as a client and can therefore be mixed easily with other
890     AnyEvent modules and other event loops in the same program. Some of the
891     modules come with AnyEvent, most are available via CPAN.
892 root 1.19
893     AnyEvent::Util
894     Contains various utility functions that replace often-used but
895     blocking functions such as "inet_aton" by event-/callback-based
896     versions.
897    
898 root 1.22 AnyEvent::Socket
899     Provides various utility functions for (internet protocol) sockets,
900     addresses and name resolution. Also functions to create non-blocking
901     tcp connections or tcp servers, with IPv6 and SRV record support and
902     more.
903    
904 root 1.28 AnyEvent::Handle
905     Provide read and write buffers, manages watchers for reads and
906     writes, supports raw and formatted I/O, I/O queued and fully
907 root 1.43 transparent and non-blocking SSL/TLS (via AnyEvent::TLS.
908 root 1.28
909 root 1.23 AnyEvent::DNS
910     Provides rich asynchronous DNS resolver capabilities.
911    
912 root 1.26 AnyEvent::HTTP
913     A simple-to-use HTTP library that is capable of making a lot of
914     concurrent HTTP requests.
915    
916 root 1.19 AnyEvent::HTTPD
917     Provides a simple web application server framework.
918    
919     AnyEvent::FastPing
920     The fastest ping in the west.
921    
922 root 1.27 AnyEvent::DBI
923     Executes DBI requests asynchronously in a proxy process.
924    
925 root 1.28 AnyEvent::AIO
926     Truly asynchronous I/O, should be in the toolbox of every event
927     programmer. AnyEvent::AIO transparently fuses IO::AIO and AnyEvent
928     together.
929    
930     AnyEvent::BDB
931     Truly asynchronous Berkeley DB access. AnyEvent::BDB transparently
932     fuses BDB and AnyEvent together.
933    
934     AnyEvent::GPSD
935     A non-blocking interface to gpsd, a daemon delivering GPS
936     information.
937    
938 root 1.31 AnyEvent::IRC
939     AnyEvent based IRC client module family (replacing the older
940     Net::IRC3).
941 root 1.19
942 root 1.43 AnyEvent::XMPP
943     AnyEvent based XMPP (Jabber protocol) module family (replacing the
944     older Net::XMPP2>.
945    
946     AnyEvent::IGS
947     A non-blocking interface to the Internet Go Server protocol (used by
948     App::IGS).
949 root 1.19
950     Net::FCP
951     AnyEvent-based implementation of the Freenet Client Protocol,
952     birthplace of AnyEvent.
953    
954     Event::ExecFlow
955     High level API for event-based execution flow control.
956    
957     Coro
958 root 1.20 Has special support for AnyEvent via Coro::AnyEvent.
959    
960 root 1.30 ERROR AND EXCEPTION HANDLING
961     In general, AnyEvent does not do any error handling - it relies on the
962     caller to do that if required. The AnyEvent::Strict module (see also the
963     "PERL_ANYEVENT_STRICT" environment variable, below) provides strict
964     checking of all AnyEvent methods, however, which is highly useful during
965     development.
966    
967     As for exception handling (i.e. runtime errors and exceptions thrown
968     while executing a callback), this is not only highly event-loop
969     specific, but also not in any way wrapped by this module, as this is the
970     job of the main program.
971    
972     The pure perl event loop simply re-throws the exception (usually within
973     "condvar->recv"), the Event and EV modules call "$Event/EV::DIED->()",
974     Glib uses "install_exception_handler" and so on.
975 root 1.6
976 root 1.4 ENVIRONMENT VARIABLES
977 root 1.30 The following environment variables are used by this module or its
978 root 1.40 submodules.
979    
980     Note that AnyEvent will remove *all* environment variables starting with
981     "PERL_ANYEVENT_" from %ENV when it is loaded while taint mode is
982     enabled.
983 root 1.4
984 root 1.18 "PERL_ANYEVENT_VERBOSE"
985 root 1.19 By default, AnyEvent will be completely silent except in fatal
986     conditions. You can set this environment variable to make AnyEvent
987     more talkative.
988    
989     When set to 1 or higher, causes AnyEvent to warn about unexpected
990     conditions, such as not being able to load the event model specified
991     by "PERL_ANYEVENT_MODEL".
992    
993 root 1.18 When set to 2 or higher, cause AnyEvent to report to STDERR which
994     event model it chooses.
995    
996 root 1.28 "PERL_ANYEVENT_STRICT"
997     AnyEvent does not do much argument checking by default, as thorough
998     argument checking is very costly. Setting this variable to a true
999     value will cause AnyEvent to load "AnyEvent::Strict" and then to
1000     thoroughly check the arguments passed to most method calls. If it
1001 root 1.41 finds any problems, it will croak.
1002 root 1.28
1003     In other words, enables "strict" mode.
1004    
1005 root 1.41 Unlike "use strict", it is definitely recommended to keep it off in
1006 root 1.30 production. Keeping "PERL_ANYEVENT_STRICT=1" in your environment
1007     while developing programs can be very useful, however.
1008 root 1.28
1009 root 1.18 "PERL_ANYEVENT_MODEL"
1010     This can be used to specify the event model to be used by AnyEvent,
1011 root 1.22 before auto detection and -probing kicks in. It must be a string
1012 root 1.18 consisting entirely of ASCII letters. The string "AnyEvent::Impl::"
1013     gets prepended and the resulting module name is loaded and if the
1014     load was successful, used as event model. If it fails to load
1015 root 1.22 AnyEvent will proceed with auto detection and -probing.
1016 root 1.18
1017     This functionality might change in future versions.
1018    
1019     For example, to force the pure perl model (AnyEvent::Impl::Perl) you
1020     could start your program like this:
1021    
1022 root 1.25 PERL_ANYEVENT_MODEL=Perl perl ...
1023 root 1.4
1024 root 1.22 "PERL_ANYEVENT_PROTOCOLS"
1025     Used by both AnyEvent::DNS and AnyEvent::Socket to determine
1026     preferences for IPv4 or IPv6. The default is unspecified (and might
1027     change, or be the result of auto probing).
1028    
1029     Must be set to a comma-separated list of protocols or address
1030     families, current supported: "ipv4" and "ipv6". Only protocols
1031     mentioned will be used, and preference will be given to protocols
1032     mentioned earlier in the list.
1033    
1034     This variable can effectively be used for denial-of-service attacks
1035     against local programs (e.g. when setuid), although the impact is
1036 root 1.35 likely small, as the program has to handle conenction and other
1037     failures anyways.
1038 root 1.22
1039     Examples: "PERL_ANYEVENT_PROTOCOLS=ipv4,ipv6" - prefer IPv4 over
1040     IPv6, but support both and try to use both.
1041     "PERL_ANYEVENT_PROTOCOLS=ipv4" - only support IPv4, never try to
1042     resolve or contact IPv6 addresses.
1043     "PERL_ANYEVENT_PROTOCOLS=ipv6,ipv4" support either IPv4 or IPv6, but
1044     prefer IPv6 over IPv4.
1045    
1046     "PERL_ANYEVENT_EDNS0"
1047     Used by AnyEvent::DNS to decide whether to use the EDNS0 extension
1048     for DNS. This extension is generally useful to reduce DNS traffic,
1049     but some (broken) firewalls drop such DNS packets, which is why it
1050     is off by default.
1051    
1052     Setting this variable to 1 will cause AnyEvent::DNS to announce
1053     EDNS0 in its DNS requests.
1054    
1055 root 1.24 "PERL_ANYEVENT_MAX_FORKS"
1056     The maximum number of child processes that
1057     "AnyEvent::Util::fork_call" will create in parallel.
1058    
1059 root 1.43 "PERL_ANYEVENT_MAX_OUTSTANDING_DNS"
1060     The default value for the "max_outstanding" parameter for the
1061     default DNS resolver - this is the maximum number of parallel DNS
1062     requests that are sent to the DNS server.
1063    
1064     "PERL_ANYEVENT_RESOLV_CONF"
1065     The file to use instead of /etc/resolv.conf (or OS-specific
1066     configuration) in the default resolver. When set to the empty
1067     string, no default config will be used.
1068    
1069     "PERL_ANYEVENT_CA_FILE", "PERL_ANYEVENT_CA_PATH".
1070     When neither "ca_file" nor "ca_path" was specified during
1071     AnyEvent::TLS context creation, and either of these environment
1072     variables exist, they will be used to specify CA certificate
1073     locations instead of a system-dependent default.
1074    
1075 root 1.30 SUPPLYING YOUR OWN EVENT MODEL INTERFACE
1076     This is an advanced topic that you do not normally need to use AnyEvent
1077     in a module. This section is only of use to event loop authors who want
1078     to provide AnyEvent compatibility.
1079    
1080     If you need to support another event library which isn't directly
1081     supported by AnyEvent, you can supply your own interface to it by
1082     pushing, before the first watcher gets created, the package name of the
1083     event module and the package name of the interface to use onto
1084     @AnyEvent::REGISTRY. You can do that before and even without loading
1085     AnyEvent, so it is reasonably cheap.
1086    
1087     Example:
1088    
1089     push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
1090    
1091     This tells AnyEvent to (literally) use the "urxvt::anyevent::"
1092     package/class when it finds the "urxvt" package/module is already
1093     loaded.
1094    
1095     When AnyEvent is loaded and asked to find a suitable event model, it
1096     will first check for the presence of urxvt by trying to "use" the
1097     "urxvt::anyevent" module.
1098    
1099     The class should provide implementations for all watcher types. See
1100     AnyEvent::Impl::EV (source code), AnyEvent::Impl::Glib (Source code) and
1101     so on for actual examples. Use "perldoc -m AnyEvent::Impl::Glib" to see
1102     the sources.
1103    
1104     If you don't provide "signal" and "child" watchers than AnyEvent will
1105     provide suitable (hopefully) replacements.
1106    
1107     The above example isn't fictitious, the *rxvt-unicode* (a.k.a. urxvt)
1108     terminal emulator uses the above line as-is. An interface isn't included
1109     in AnyEvent because it doesn't make sense outside the embedded
1110     interpreter inside *rxvt-unicode*, and it is updated and maintained as
1111     part of the *rxvt-unicode* distribution.
1112    
1113     *rxvt-unicode* also cheats a bit by not providing blocking access to
1114     condition variables: code blocking while waiting for a condition will
1115     "die". This still works with most modules/usages, and blocking calls
1116     must not be done in an interactive application, so it makes sense.
1117    
1118 root 1.16 EXAMPLE PROGRAM
1119 root 1.19 The following program uses an I/O watcher to read data from STDIN, a
1120 root 1.16 timer to display a message once per second, and a condition variable to
1121     quit the program when the user enters quit:
1122 root 1.2
1123     use AnyEvent;
1124    
1125     my $cv = AnyEvent->condvar;
1126    
1127 root 1.16 my $io_watcher = AnyEvent->io (
1128     fh => \*STDIN,
1129     poll => 'r',
1130     cb => sub {
1131     warn "io event <$_[0]>\n"; # will always output <r>
1132     chomp (my $input = <STDIN>); # read a line
1133     warn "read: $input\n"; # output what has been read
1134 root 1.21 $cv->send if $input =~ /^q/i; # quit program if /^q/i
1135 root 1.16 },
1136     );
1137 root 1.2
1138     my $time_watcher; # can only be used once
1139    
1140     sub new_timer {
1141     $timer = AnyEvent->timer (after => 1, cb => sub {
1142     warn "timeout\n"; # print 'timeout' about every second
1143     &new_timer; # and restart the time
1144     });
1145     }
1146    
1147     new_timer; # create first timer
1148    
1149 root 1.21 $cv->recv; # wait until user enters /^q/i
1150 root 1.2
1151 root 1.3 REAL-WORLD EXAMPLE
1152     Consider the Net::FCP module. It features (among others) the following
1153     API calls, which are to freenet what HTTP GET requests are to http:
1154    
1155     my $data = $fcp->client_get ($url); # blocks
1156    
1157     my $transaction = $fcp->txn_client_get ($url); # does not block
1158     $transaction->cb ( sub { ... } ); # set optional result callback
1159     my $data = $transaction->result; # possibly blocks
1160    
1161     The "client_get" method works like "LWP::Simple::get": it requests the
1162     given URL and waits till the data has arrived. It is defined to be:
1163    
1164     sub client_get { $_[0]->txn_client_get ($_[1])->result }
1165    
1166     And in fact is automatically generated. This is the blocking API of
1167     Net::FCP, and it works as simple as in any other, similar, module.
1168    
1169     More complicated is "txn_client_get": It only creates a transaction
1170     (completion, result, ...) object and initiates the transaction.
1171    
1172     my $txn = bless { }, Net::FCP::Txn::;
1173    
1174     It also creates a condition variable that is used to signal the
1175     completion of the request:
1176    
1177     $txn->{finished} = AnyAvent->condvar;
1178    
1179     It then creates a socket in non-blocking mode.
1180    
1181     socket $txn->{fh}, ...;
1182     fcntl $txn->{fh}, F_SETFL, O_NONBLOCK;
1183     connect $txn->{fh}, ...
1184     and !$!{EWOULDBLOCK}
1185     and !$!{EINPROGRESS}
1186     and Carp::croak "unable to connect: $!\n";
1187    
1188 root 1.4 Then it creates a write-watcher which gets called whenever an error
1189 root 1.3 occurs or the connection succeeds:
1190    
1191     $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w });
1192    
1193     And returns this transaction object. The "fh_ready_w" callback gets
1194     called as soon as the event loop detects that the socket is ready for
1195     writing.
1196    
1197     The "fh_ready_w" method makes the socket blocking again, writes the
1198     request data and replaces the watcher by a read watcher (waiting for
1199     reply data). The actual code is more complicated, but that doesn't
1200     matter for this example:
1201    
1202     fcntl $txn->{fh}, F_SETFL, 0;
1203     syswrite $txn->{fh}, $txn->{request}
1204     or die "connection or write error";
1205     $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r });
1206    
1207     Again, "fh_ready_r" waits till all data has arrived, and then stores the
1208 root 1.22 result and signals any possible waiters that the request has finished:
1209 root 1.3
1210     sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf};
1211    
1212     if (end-of-file or data complete) {
1213     $txn->{result} = $txn->{buf};
1214 root 1.21 $txn->{finished}->send;
1215 root 1.4 $txb->{cb}->($txn) of $txn->{cb}; # also call callback
1216 root 1.3 }
1217    
1218     The "result" method, finally, just waits for the finished signal (if the
1219     request was already finished, it doesn't wait, of course, and returns
1220     the data:
1221    
1222 root 1.21 $txn->{finished}->recv;
1223 root 1.4 return $txn->{result};
1224 root 1.3
1225     The actual code goes further and collects all errors ("die"s,
1226 root 1.22 exceptions) that occurred during request processing. The "result" method
1227 root 1.16 detects whether an exception as thrown (it is stored inside the $txn
1228 root 1.3 object) and just throws the exception, which means connection errors and
1229     other problems get reported tot he code that tries to use the result,
1230     not in a random callback.
1231    
1232     All of this enables the following usage styles:
1233    
1234     1. Blocking:
1235    
1236     my $data = $fcp->client_get ($url);
1237    
1238 root 1.15 2. Blocking, but running in parallel:
1239 root 1.3
1240     my @datas = map $_->result,
1241     map $fcp->txn_client_get ($_),
1242     @urls;
1243    
1244     Both blocking examples work without the module user having to know
1245     anything about events.
1246    
1247 root 1.15 3a. Event-based in a main program, using any supported event module:
1248 root 1.3
1249 root 1.15 use EV;
1250 root 1.3
1251     $fcp->txn_client_get ($url)->cb (sub {
1252     my $txn = shift;
1253     my $data = $txn->result;
1254     ...
1255     });
1256    
1257 root 1.15 EV::loop;
1258 root 1.3
1259     3b. The module user could use AnyEvent, too:
1260    
1261     use AnyEvent;
1262    
1263     my $quit = AnyEvent->condvar;
1264    
1265     $fcp->txn_client_get ($url)->cb (sub {
1266     ...
1267 root 1.21 $quit->send;
1268 root 1.3 });
1269    
1270 root 1.21 $quit->recv;
1271 root 1.3
1272 root 1.19 BENCHMARKS
1273     To give you an idea of the performance and overheads that AnyEvent adds
1274     over the event loops themselves and to give you an impression of the
1275     speed of various event loops I prepared some benchmarks.
1276    
1277     BENCHMARKING ANYEVENT OVERHEAD
1278     Here is a benchmark of various supported event models used natively and
1279 root 1.22 through AnyEvent. The benchmark creates a lot of timers (with a zero
1280 root 1.19 timeout) and I/O watchers (watching STDOUT, a pty, to become writable,
1281     which it is), lets them fire exactly once and destroys them again.
1282    
1283     Source code for this benchmark is found as eg/bench in the AnyEvent
1284     distribution.
1285    
1286     Explanation of the columns
1287     *watcher* is the number of event watchers created/destroyed. Since
1288     different event models feature vastly different performances, each event
1289     loop was given a number of watchers so that overall runtime is
1290     acceptable and similar between tested event loop (and keep them from
1291     crashing): Glib would probably take thousands of years if asked to
1292     process the same number of watchers as EV in this benchmark.
1293    
1294     *bytes* is the number of bytes (as measured by the resident set size,
1295     RSS) consumed by each watcher. This method of measuring captures both C
1296     and Perl-based overheads.
1297    
1298     *create* is the time, in microseconds (millionths of seconds), that it
1299     takes to create a single watcher. The callback is a closure shared
1300     between all watchers, to avoid adding memory overhead. That means
1301     closure creation and memory usage is not included in the figures.
1302    
1303     *invoke* is the time, in microseconds, used to invoke a simple callback.
1304     The callback simply counts down a Perl variable and after it was invoked
1305 root 1.21 "watcher" times, it would "->send" a condvar once to signal the end of
1306     this phase.
1307 root 1.19
1308     *destroy* is the time, in microseconds, that it takes to destroy a
1309     single watcher.
1310    
1311     Results
1312     name watchers bytes create invoke destroy comment
1313 root 1.33 EV/EV 400000 224 0.47 0.35 0.27 EV native interface
1314     EV/Any 100000 224 2.88 0.34 0.27 EV + AnyEvent watchers
1315     CoroEV/Any 100000 224 2.85 0.35 0.28 coroutines + Coro::Signal
1316 root 1.34 Perl/Any 100000 452 4.13 0.73 0.95 pure perl implementation
1317 root 1.33 Event/Event 16000 517 32.20 31.80 0.81 Event native interface
1318     Event/Any 16000 590 35.85 31.55 1.06 Event + AnyEvent watchers
1319 root 1.41 IOAsync/Any 16000 989 38.10 32.77 11.13 via IO::Async::Loop::IO_Poll
1320     IOAsync/Any 16000 990 37.59 29.50 10.61 via IO::Async::Loop::Epoll
1321 root 1.33 Glib/Any 16000 1357 102.33 12.31 51.00 quadratic behaviour
1322     Tk/Any 2000 1860 27.20 66.31 14.00 SEGV with >> 2000 watchers
1323     POE/Event 2000 6328 109.99 751.67 14.02 via POE::Loop::Event
1324     POE/Select 2000 6027 94.54 809.13 579.80 via POE::Loop::Select
1325 root 1.19
1326     Discussion
1327     The benchmark does *not* measure scalability of the event loop very
1328     well. For example, a select-based event loop (such as the pure perl one)
1329     can never compete with an event loop that uses epoll when the number of
1330     file descriptors grows high. In this benchmark, all events become ready
1331     at the same time, so select/poll-based implementations get an unnatural
1332     speed boost.
1333    
1334     Also, note that the number of watchers usually has a nonlinear effect on
1335     overall speed, that is, creating twice as many watchers doesn't take
1336     twice the time - usually it takes longer. This puts event loops tested
1337     with a higher number of watchers at a disadvantage.
1338    
1339     To put the range of results into perspective, consider that on the
1340     benchmark machine, handling an event takes roughly 1600 CPU cycles with
1341     EV, 3100 CPU cycles with AnyEvent's pure perl loop and almost 3000000
1342     CPU cycles with POE.
1343    
1344     "EV" is the sole leader regarding speed and memory use, which are both
1345     maximal/minimal, respectively. Even when going through AnyEvent, it uses
1346     far less memory than any other event loop and is still faster than Event
1347     natively.
1348    
1349     The pure perl implementation is hit in a few sweet spots (both the
1350     constant timeout and the use of a single fd hit optimisations in the
1351     perl interpreter and the backend itself). Nevertheless this shows that
1352     it adds very little overhead in itself. Like any select-based backend
1353     its performance becomes really bad with lots of file descriptors (and
1354     few of them active), of course, but this was not subject of this
1355     benchmark.
1356    
1357     The "Event" module has a relatively high setup and callback invocation
1358     cost, but overall scores in on the third place.
1359    
1360 root 1.41 "IO::Async" performs admirably well, about on par with "Event", even
1361     when using its pure perl backend.
1362    
1363 root 1.19 "Glib"'s memory usage is quite a bit higher, but it features a faster
1364     callback invocation and overall ends up in the same class as "Event".
1365     However, Glib scales extremely badly, doubling the number of watchers
1366     increases the processing time by more than a factor of four, making it
1367     completely unusable when using larger numbers of watchers (note that
1368     only a single file descriptor was used in the benchmark, so
1369     inefficiencies of "poll" do not account for this).
1370    
1371     The "Tk" adaptor works relatively well. The fact that it crashes with
1372     more than 2000 watchers is a big setback, however, as correctness takes
1373     precedence over speed. Nevertheless, its performance is surprising, as
1374     the file descriptor is dup()ed for each watcher. This shows that the
1375     dup() employed by some adaptors is not a big performance issue (it does
1376     incur a hidden memory cost inside the kernel which is not reflected in
1377     the figures above).
1378    
1379     "POE", regardless of underlying event loop (whether using its pure perl
1380     select-based backend or the Event module, the POE-EV backend couldn't be
1381     tested because it wasn't working) shows abysmal performance and memory
1382 root 1.20 usage with AnyEvent: Watchers use almost 30 times as much memory as EV
1383     watchers, and 10 times as much memory as Event (the high memory
1384     requirements are caused by requiring a session for each watcher).
1385     Watcher invocation speed is almost 900 times slower than with AnyEvent's
1386     pure perl implementation.
1387    
1388     The design of the POE adaptor class in AnyEvent can not really account
1389     for the performance issues, though, as session creation overhead is
1390     small compared to execution of the state machine, which is coded pretty
1391     optimally within AnyEvent::Impl::POE (and while everybody agrees that
1392     using multiple sessions is not a good approach, especially regarding
1393     memory usage, even the author of POE could not come up with a faster
1394     design).
1395 root 1.19
1396     Summary
1397     * Using EV through AnyEvent is faster than any other event loop (even
1398     when used without AnyEvent), but most event loops have acceptable
1399     performance with or without AnyEvent.
1400    
1401     * The overhead AnyEvent adds is usually much smaller than the overhead
1402     of the actual event loop, only with extremely fast event loops such
1403     as EV adds AnyEvent significant overhead.
1404    
1405     * You should avoid POE like the plague if you want performance or
1406     reasonable memory usage.
1407    
1408     BENCHMARKING THE LARGE SERVER CASE
1409 root 1.22 This benchmark actually benchmarks the event loop itself. It works by
1410     creating a number of "servers": each server consists of a socket pair, a
1411 root 1.19 timeout watcher that gets reset on activity (but never fires), and an
1412     I/O watcher waiting for input on one side of the socket. Each time the
1413     socket watcher reads a byte it will write that byte to a random other
1414     "server".
1415    
1416     The effect is that there will be a lot of I/O watchers, only part of
1417     which are active at any one point (so there is a constant number of
1418 root 1.22 active fds for each loop iteration, but which fds these are is random).
1419 root 1.19 The timeout is reset each time something is read because that reflects
1420     how most timeouts work (and puts extra pressure on the event loops).
1421    
1422 root 1.22 In this benchmark, we use 10000 socket pairs (20000 sockets), of which
1423 root 1.19 100 (1%) are active. This mirrors the activity of large servers with
1424     many connections, most of which are idle at any one point in time.
1425    
1426     Source code for this benchmark is found as eg/bench2 in the AnyEvent
1427     distribution.
1428    
1429     Explanation of the columns
1430     *sockets* is the number of sockets, and twice the number of "servers"
1431     (as each server has a read and write socket end).
1432    
1433 root 1.22 *create* is the time it takes to create a socket pair (which is
1434 root 1.19 nontrivial) and two watchers: an I/O watcher and a timeout watcher.
1435    
1436     *request*, the most important value, is the time it takes to handle a
1437     single "request", that is, reading the token from the pipe and
1438     forwarding it to another server. This includes deleting the old timeout
1439     and creating a new one that moves the timeout into the future.
1440    
1441     Results
1442 root 1.41 name sockets create request
1443     EV 20000 69.01 11.16
1444     Perl 20000 73.32 35.87
1445     IOAsync 20000 157.00 98.14 epoll
1446     IOAsync 20000 159.31 616.06 poll
1447     Event 20000 212.62 257.32
1448     Glib 20000 651.16 1896.30
1449     POE 20000 349.67 12317.24 uses POE::Loop::Event
1450 root 1.19
1451     Discussion
1452     This benchmark *does* measure scalability and overall performance of the
1453     particular event loop.
1454    
1455     EV is again fastest. Since it is using epoll on my system, the setup
1456     time is relatively high, though.
1457    
1458     Perl surprisingly comes second. It is much faster than the C-based event
1459     loops Event and Glib.
1460    
1461 root 1.41 IO::Async performs very well when using its epoll backend, and still
1462     quite good compared to Glib when using its pure perl backend.
1463    
1464 root 1.19 Event suffers from high setup time as well (look at its code and you
1465     will understand why). Callback invocation also has a high overhead
1466     compared to the "$_->() for .."-style loop that the Perl event loop
1467     uses. Event uses select or poll in basically all documented
1468     configurations.
1469    
1470     Glib is hit hard by its quadratic behaviour w.r.t. many watchers. It
1471     clearly fails to perform with many filehandles or in busy servers.
1472    
1473     POE is still completely out of the picture, taking over 1000 times as
1474     long as EV, and over 100 times as long as the Perl implementation, even
1475     though it uses a C-based event loop in this case.
1476    
1477     Summary
1478 root 1.20 * The pure perl implementation performs extremely well.
1479 root 1.19
1480     * Avoid Glib or POE in large projects where performance matters.
1481    
1482     BENCHMARKING SMALL SERVERS
1483     While event loops should scale (and select-based ones do not...) even to
1484     large servers, most programs we (or I :) actually write have only a few
1485     I/O watchers.
1486    
1487     In this benchmark, I use the same benchmark program as in the large
1488     server case, but it uses only eight "servers", of which three are active
1489     at any one time. This should reflect performance for a small server
1490     relatively well.
1491    
1492     The columns are identical to the previous table.
1493    
1494     Results
1495     name sockets create request
1496     EV 16 20.00 6.54
1497     Perl 16 25.75 12.62
1498     Event 16 81.27 35.86
1499     Glib 16 32.63 15.48
1500     POE 16 261.87 276.28 uses POE::Loop::Event
1501    
1502     Discussion
1503     The benchmark tries to test the performance of a typical small server.
1504     While knowing how various event loops perform is interesting, keep in
1505     mind that their overhead in this case is usually not as important, due
1506     to the small absolute number of watchers (that is, you need efficiency
1507     and speed most when you have lots of watchers, not when you only have a
1508     few of them).
1509    
1510     EV is again fastest.
1511    
1512 root 1.22 Perl again comes second. It is noticeably faster than the C-based event
1513 root 1.19 loops Event and Glib, although the difference is too small to really
1514     matter.
1515    
1516     POE also performs much better in this case, but is is still far behind
1517     the others.
1518    
1519     Summary
1520     * C-based event loops perform very well with small number of watchers,
1521     as the management overhead dominates.
1522    
1523 root 1.40 THE IO::Lambda BENCHMARK
1524     Recently I was told about the benchmark in the IO::Lambda manpage, which
1525     could be misinterpreted to make AnyEvent look bad. In fact, the
1526     benchmark simply compares IO::Lambda with POE, and IO::Lambda looks
1527     better (which shouldn't come as a surprise to anybody). As such, the
1528 root 1.41 benchmark is fine, and mostly shows that the AnyEvent backend from
1529     IO::Lambda isn't very optimal. But how would AnyEvent compare when used
1530     without the extra baggage? To explore this, I wrote the equivalent
1531     benchmark for AnyEvent.
1532 root 1.40
1533     The benchmark itself creates an echo-server, and then, for 500 times,
1534     connects to the echo server, sends a line, waits for the reply, and then
1535     creates the next connection. This is a rather bad benchmark, as it
1536 root 1.41 doesn't test the efficiency of the framework or much non-blocking I/O,
1537     but it is a benchmark nevertheless.
1538 root 1.40
1539     name runtime
1540     Lambda/select 0.330 sec
1541     + optimized 0.122 sec
1542     Lambda/AnyEvent 0.327 sec
1543     + optimized 0.138 sec
1544     Raw sockets/select 0.077 sec
1545     POE/select, components 0.662 sec
1546     POE/select, raw sockets 0.226 sec
1547     POE/select, optimized 0.404 sec
1548    
1549     AnyEvent/select/nb 0.085 sec
1550     AnyEvent/EV/nb 0.068 sec
1551     +state machine 0.134 sec
1552    
1553 root 1.41 The benchmark is also a bit unfair (my fault): the IO::Lambda/POE
1554 root 1.40 benchmarks actually make blocking connects and use 100% blocking I/O,
1555     defeating the purpose of an event-based solution. All of the newly
1556     written AnyEvent benchmarks use 100% non-blocking connects (using
1557     AnyEvent::Socket::tcp_connect and the asynchronous pure perl DNS
1558 root 1.41 resolver), so AnyEvent is at a disadvantage here, as non-blocking
1559 root 1.40 connects generally require a lot more bookkeeping and event handling
1560     than blocking connects (which involve a single syscall only).
1561    
1562     The last AnyEvent benchmark additionally uses AnyEvent::Handle, which
1563 root 1.41 offers similar expressive power as POE and IO::Lambda, using
1564     conventional Perl syntax. This means that both the echo server and the
1565     client are 100% non-blocking, further placing it at a disadvantage.
1566    
1567     As you can see, the AnyEvent + EV combination even beats the
1568     hand-optimised "raw sockets benchmark", while AnyEvent + its pure perl
1569     backend easily beats IO::Lambda and POE.
1570 root 1.40
1571     And even the 100% non-blocking version written using the high-level (and
1572 root 1.41 slow :) AnyEvent::Handle abstraction beats both POE and IO::Lambda by a
1573     large margin, even though it does all of DNS, tcp-connect and socket I/O
1574     in a non-blocking way.
1575    
1576     The two AnyEvent benchmarks programs can be found as eg/ae0.pl and
1577     eg/ae2.pl in the AnyEvent distribution, the remaining benchmarks are
1578     part of the IO::lambda distribution and were used without any changes.
1579 root 1.40
1580 root 1.32 SIGNALS
1581     AnyEvent currently installs handlers for these signals:
1582    
1583     SIGCHLD
1584     A handler for "SIGCHLD" is installed by AnyEvent's child watcher
1585     emulation for event loops that do not support them natively. Also,
1586     some event loops install a similar handler.
1587    
1588 root 1.44 Additionally, when AnyEvent is loaded and SIGCHLD is set to IGNORE,
1589     then AnyEvent will reset it to default, to avoid losing child exit
1590     statuses.
1591 root 1.41
1592 root 1.32 SIGPIPE
1593     A no-op handler is installed for "SIGPIPE" when $SIG{PIPE} is
1594     "undef" when AnyEvent gets loaded.
1595    
1596     The rationale for this is that AnyEvent users usually do not really
1597     depend on SIGPIPE delivery (which is purely an optimisation for
1598     shell use, or badly-written programs), but "SIGPIPE" can cause
1599     spurious and rare program exits as a lot of people do not expect
1600     "SIGPIPE" when writing to some random socket.
1601    
1602     The rationale for installing a no-op handler as opposed to ignoring
1603     it is that this way, the handler will be restored to defaults on
1604     exec.
1605    
1606     Feel free to install your own handler, or reset it to defaults.
1607    
1608 root 1.18 FORK
1609     Most event libraries are not fork-safe. The ones who are usually are
1610 root 1.20 because they rely on inefficient but fork-safe "select" or "poll" calls.
1611     Only EV is fully fork-aware.
1612 root 1.18
1613     If you have to fork, you must either do so *before* creating your first
1614     watcher OR you must not use AnyEvent at all in the child.
1615    
1616     SECURITY CONSIDERATIONS
1617     AnyEvent can be forced to load any event model via
1618     $ENV{PERL_ANYEVENT_MODEL}. While this cannot (to my knowledge) be used
1619     to execute arbitrary code or directly gain access, it can easily be used
1620     to make the program hang or malfunction in subtle ways, as AnyEvent
1621     watchers will not be active when the program uses a different event
1622     model than specified in the variable.
1623    
1624     You can make AnyEvent completely ignore this variable by deleting it
1625     before the first watcher gets created, e.g. with a "BEGIN" block:
1626    
1627 root 1.25 BEGIN { delete $ENV{PERL_ANYEVENT_MODEL} }
1628 root 1.40
1629     use AnyEvent;
1630 root 1.18
1631 root 1.20 Similar considerations apply to $ENV{PERL_ANYEVENT_VERBOSE}, as that can
1632     be used to probe what backend is used and gain other information (which
1633 root 1.28 is probably even less useful to an attacker than PERL_ANYEVENT_MODEL),
1634 root 1.40 and $ENV{PERL_ANYEVENT_STRICT}.
1635 root 1.20
1636 root 1.41 Note that AnyEvent will remove *all* environment variables starting with
1637     "PERL_ANYEVENT_" from %ENV when it is loaded while taint mode is
1638     enabled.
1639    
1640 root 1.26 BUGS
1641     Perl 5.8 has numerous memleaks that sometimes hit this module and are
1642     hard to work around. If you suffer from memleaks, first upgrade to Perl
1643     5.10 and check wether the leaks still show up. (Perl 5.10.0 has other
1644 root 1.36 annoying memleaks, such as leaking on "map" and "grep" but it is usually
1645 root 1.26 not as pronounced).
1646    
1647 root 1.2 SEE ALSO
1648 root 1.22 Utility functions: AnyEvent::Util.
1649    
1650 root 1.20 Event modules: EV, EV::Glib, Glib::EV, Event, Glib::Event, Glib, Tk,
1651     Event::Lib, Qt, POE.
1652    
1653     Implementations: AnyEvent::Impl::EV, AnyEvent::Impl::Event,
1654     AnyEvent::Impl::Glib, AnyEvent::Impl::Tk, AnyEvent::Impl::Perl,
1655 root 1.43 AnyEvent::Impl::EventLib, AnyEvent::Impl::Qt, AnyEvent::Impl::POE,
1656     AnyEvent::Impl::IOAsync.
1657 root 1.3
1658 root 1.22 Non-blocking file handles, sockets, TCP clients and servers:
1659 root 1.43 AnyEvent::Handle, AnyEvent::Socket, AnyEvent::TLS.
1660 root 1.22
1661     Asynchronous DNS: AnyEvent::DNS.
1662    
1663 root 1.20 Coroutine support: Coro, Coro::AnyEvent, Coro::EV, Coro::Event,
1664 root 1.3
1665 root 1.43 Nontrivial usage examples: AnyEvent::GPSD, AnyEvent::XMPP,
1666     AnyEvent::HTTP.
1667 root 1.2
1668 root 1.17 AUTHOR
1669 root 1.25 Marc Lehmann <schmorp@schmorp.de>
1670     http://home.schmorp.de/
1671 root 1.2