ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent.pm
Revision: 1.82
Committed: Fri Apr 25 13:32:39 2008 UTC (16 years, 2 months ago) by root
Branch: MAIN
Changes since 1.81: +25 -5 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 =head1 NAME
2
3 AnyEvent - provide framework for multiple event loops
4
5 EV, Event, Coro::EV, Coro::Event, Glib, Tk, Perl, Event::Lib, Qt, POE - various supported event loops
6
7 =head1 SYNOPSIS
8
9 use AnyEvent;
10
11 my $w = AnyEvent->io (fh => $fh, poll => "r|w", cb => sub {
12 ...
13 });
14
15 my $w = AnyEvent->timer (after => $seconds, cb => sub {
16 ...
17 });
18
19 my $w = AnyEvent->condvar; # stores whether a condition was flagged
20 $w->wait; # enters "main loop" till $condvar gets ->broadcast
21 $w->broadcast; # wake up current and all future wait's
22
23 =head1 WHY YOU SHOULD USE THIS MODULE (OR NOT)
24
25 Glib, POE, IO::Async, Event... CPAN offers event models by the dozen
26 nowadays. So what is different about AnyEvent?
27
28 Executive Summary: AnyEvent is I<compatible>, AnyEvent is I<free of
29 policy> and AnyEvent is I<small and efficient>.
30
31 First and foremost, I<AnyEvent is not an event model> itself, it only
32 interfaces to whatever event model the main program happens to use in a
33 pragmatic way. For event models and certain classes of immortals alike,
34 the statement "there can only be one" is a bitter reality: In general,
35 only one event loop can be active at the same time in a process. AnyEvent
36 helps hiding the differences between those event loops.
37
38 The goal of AnyEvent is to offer module authors the ability to do event
39 programming (waiting for I/O or timer events) without subscribing to a
40 religion, a way of living, and most importantly: without forcing your
41 module users into the same thing by forcing them to use the same event
42 model you use.
43
44 For modules like POE or IO::Async (which is a total misnomer as it is
45 actually doing all I/O I<synchronously>...), using them in your module is
46 like joining a cult: After you joined, you are dependent on them and you
47 cannot use anything else, as it is simply incompatible to everything that
48 isn't itself. What's worse, all the potential users of your module are
49 I<also> forced to use the same event loop you use.
50
51 AnyEvent is different: AnyEvent + POE works fine. AnyEvent + Glib works
52 fine. AnyEvent + Tk works fine etc. etc. but none of these work together
53 with the rest: POE + IO::Async? no go. Tk + Event? no go. Again: if
54 your module uses one of those, every user of your module has to use it,
55 too. But if your module uses AnyEvent, it works transparently with all
56 event models it supports (including stuff like POE and IO::Async, as long
57 as those use one of the supported event loops. It is trivial to add new
58 event loops to AnyEvent, too, so it is future-proof).
59
60 In addition to being free of having to use I<the one and only true event
61 model>, AnyEvent also is free of bloat and policy: with POE or similar
62 modules, you get an enourmous amount of code and strict rules you have to
63 follow. AnyEvent, on the other hand, is lean and up to the point, by only
64 offering the functionality that is necessary, in as thin as a wrapper as
65 technically possible.
66
67 Of course, if you want lots of policy (this can arguably be somewhat
68 useful) and you want to force your users to use the one and only event
69 model, you should I<not> use this module.
70
71
72 =head1 DESCRIPTION
73
74 L<AnyEvent> provides an identical interface to multiple event loops. This
75 allows module authors to utilise an event loop without forcing module
76 users to use the same event loop (as only a single event loop can coexist
77 peacefully at any one time).
78
79 The interface itself is vaguely similar, but not identical to the L<Event>
80 module.
81
82 During the first call of any watcher-creation method, the module tries
83 to detect the currently loaded event loop by probing whether one of the
84 following modules is already loaded: L<Coro::EV>, L<Coro::Event>, L<EV>,
85 L<Event>, L<Glib>, L<AnyEvent::Impl::Perl>, L<Tk>, L<Event::Lib>, L<Qt>,
86 L<POE>. The first one found is used. If none are found, the module tries
87 to load these modules (excluding Tk, Event::Lib, Qt and POE as the pure perl
88 adaptor should always succeed) in the order given. The first one that can
89 be successfully loaded will be used. If, after this, still none could be
90 found, AnyEvent will fall back to a pure-perl event loop, which is not
91 very efficient, but should work everywhere.
92
93 Because AnyEvent first checks for modules that are already loaded, loading
94 an event model explicitly before first using AnyEvent will likely make
95 that model the default. For example:
96
97 use Tk;
98 use AnyEvent;
99
100 # .. AnyEvent will likely default to Tk
101
102 The I<likely> means that, if any module loads another event model and
103 starts using it, all bets are off. Maybe you should tell their authors to
104 use AnyEvent so their modules work together with others seamlessly...
105
106 The pure-perl implementation of AnyEvent is called
107 C<AnyEvent::Impl::Perl>. Like other event modules you can load it
108 explicitly.
109
110 =head1 WATCHERS
111
112 AnyEvent has the central concept of a I<watcher>, which is an object that
113 stores relevant data for each kind of event you are waiting for, such as
114 the callback to call, the filehandle to watch, etc.
115
116 These watchers are normal Perl objects with normal Perl lifetime. After
117 creating a watcher it will immediately "watch" for events and invoke the
118 callback when the event occurs (of course, only when the event model
119 is in control).
120
121 To disable the watcher you have to destroy it (e.g. by setting the
122 variable you store it in to C<undef> or otherwise deleting all references
123 to it).
124
125 All watchers are created by calling a method on the C<AnyEvent> class.
126
127 Many watchers either are used with "recursion" (repeating timers for
128 example), or need to refer to their watcher object in other ways.
129
130 An any way to achieve that is this pattern:
131
132 my $w; $w = AnyEvent->type (arg => value ..., cb => sub {
133 # you can use $w here, for example to undef it
134 undef $w;
135 });
136
137 Note that C<my $w; $w => combination. This is necessary because in Perl,
138 my variables are only visible after the statement in which they are
139 declared.
140
141 =head2 I/O WATCHERS
142
143 You can create an I/O watcher by calling the C<< AnyEvent->io >> method
144 with the following mandatory key-value pairs as arguments:
145
146 C<fh> the Perl I<file handle> (I<not> file descriptor) to watch for
147 events. C<poll> must be a string that is either C<r> or C<w>, which
148 creates a watcher waiting for "r"eadable or "w"ritable events,
149 respectively. C<cb> is the callback to invoke each time the file handle
150 becomes ready.
151
152 The I/O watcher might use the underlying file descriptor or a copy of it.
153 It is not allowed to close a file handle as long as any watcher is active
154 on the underlying file descriptor.
155
156 Some event loops issue spurious readyness notifications, so you should
157 always use non-blocking calls when reading/writing from/to your file
158 handles.
159
160 Example:
161
162 # wait for readability of STDIN, then read a line and disable the watcher
163 my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
164 chomp (my $input = <STDIN>);
165 warn "read: $input\n";
166 undef $w;
167 });
168
169 =head2 TIME WATCHERS
170
171 You can create a time watcher by calling the C<< AnyEvent->timer >>
172 method with the following mandatory arguments:
173
174 C<after> specifies after how many seconds (fractional values are
175 supported) should the timer activate. C<cb> the callback to invoke in that
176 case.
177
178 The timer callback will be invoked at most once: if you want a repeating
179 timer you have to create a new watcher (this is a limitation by both Tk
180 and Glib).
181
182 Example:
183
184 # fire an event after 7.7 seconds
185 my $w = AnyEvent->timer (after => 7.7, cb => sub {
186 warn "timeout\n";
187 });
188
189 # to cancel the timer:
190 undef $w;
191
192 Example 2:
193
194 # fire an event after 0.5 seconds, then roughly every second
195 my $w;
196
197 my $cb = sub {
198 # cancel the old timer while creating a new one
199 $w = AnyEvent->timer (after => 1, cb => $cb);
200 };
201
202 # start the "loop" by creating the first watcher
203 $w = AnyEvent->timer (after => 0.5, cb => $cb);
204
205 =head3 TIMING ISSUES
206
207 There are two ways to handle timers: based on real time (relative, "fire
208 in 10 seconds") and based on wallclock time (absolute, "fire at 12
209 o'clock").
210
211 While most event loops expect timers to specified in a relative way, they
212 use absolute time internally. This makes a difference when your clock
213 "jumps", for example, when ntp decides to set your clock backwards from
214 the wrong date of 2014-01-01 to 2008-01-01, a watcher that is supposed to
215 fire "after" a second might actually take six years to finally fire.
216
217 AnyEvent cannot compensate for this. The only event loop that is conscious
218 about these issues is L<EV>, which offers both relative (ev_timer, based
219 on true relative time) and absolute (ev_periodic, based on wallclock time)
220 timers.
221
222 AnyEvent always prefers relative timers, if available, matching the
223 AnyEvent API.
224
225 =head2 SIGNAL WATCHERS
226
227 You can watch for signals using a signal watcher, C<signal> is the signal
228 I<name> without any C<SIG> prefix, C<cb> is the Perl callback to
229 be invoked whenever a signal occurs.
230
231 Multiple signal occurances can be clumped together into one callback
232 invocation, and callback invocation will be synchronous. synchronous means
233 that it might take a while until the signal gets handled by the process,
234 but it is guarenteed not to interrupt any other callbacks.
235
236 The main advantage of using these watchers is that you can share a signal
237 between multiple watchers.
238
239 This watcher might use C<%SIG>, so programs overwriting those signals
240 directly will likely not work correctly.
241
242 Example: exit on SIGINT
243
244 my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });
245
246 =head2 CHILD PROCESS WATCHERS
247
248 You can also watch on a child process exit and catch its exit status.
249
250 The child process is specified by the C<pid> argument (if set to C<0>, it
251 watches for any child process exit). The watcher will trigger as often
252 as status change for the child are received. This works by installing a
253 signal handler for C<SIGCHLD>. The callback will be called with the pid
254 and exit status (as returned by waitpid).
255
256 There is a slight catch to child watchers, however: you usually start them
257 I<after> the child process was created, and this means the process could
258 have exited already (and no SIGCHLD will be sent anymore).
259
260 Not all event models handle this correctly (POE doesn't), but even for
261 event models that I<do> handle this correctly, they usually need to be
262 loaded before the process exits (i.e. before you fork in the first place).
263
264 This means you cannot create a child watcher as the very first thing in an
265 AnyEvent program, you I<have> to create at least one watcher before you
266 C<fork> the child (alternatively, you can call C<AnyEvent::detect>).
267
268 Example: fork a process and wait for it
269
270 my $done = AnyEvent->condvar;
271
272 AnyEvent::detect; # force event module to be initialised
273
274 my $pid = fork or exit 5;
275
276 my $w = AnyEvent->child (
277 pid => $pid,
278 cb => sub {
279 my ($pid, $status) = @_;
280 warn "pid $pid exited with status $status";
281 $done->broadcast;
282 },
283 );
284
285 # do something else, then wait for process exit
286 $done->wait;
287
288 =head2 CONDITION VARIABLES
289
290 Condition variables can be created by calling the C<< AnyEvent->condvar >>
291 method without any arguments.
292
293 A condition variable waits for a condition - precisely that the C<<
294 ->broadcast >> method has been called.
295
296 They are very useful to signal that a condition has been fulfilled, for
297 example, if you write a module that does asynchronous http requests,
298 then a condition variable would be the ideal candidate to signal the
299 availability of results.
300
301 You can also use condition variables to block your main program until
302 an event occurs - for example, you could C<< ->wait >> in your main
303 program until the user clicks the Quit button in your app, which would C<<
304 ->broadcast >> the "quit" event.
305
306 Note that condition variables recurse into the event loop - if you have
307 two pirces of code that call C<< ->wait >> in a round-robbin fashion, you
308 lose. Therefore, condition variables are good to export to your caller, but
309 you should avoid making a blocking wait yourself, at least in callbacks,
310 as this asks for trouble.
311
312 This object has two methods:
313
314 =over 4
315
316 =item $cv->wait
317
318 Wait (blocking if necessary) until the C<< ->broadcast >> method has been
319 called on c<$cv>, while servicing other watchers normally.
320
321 You can only wait once on a condition - additional calls will return
322 immediately.
323
324 Not all event models support a blocking wait - some die in that case
325 (programs might want to do that to stay interactive), so I<if you are
326 using this from a module, never require a blocking wait>, but let the
327 caller decide whether the call will block or not (for example, by coupling
328 condition variables with some kind of request results and supporting
329 callbacks so the caller knows that getting the result will not block,
330 while still suppporting blocking waits if the caller so desires).
331
332 Another reason I<never> to C<< ->wait >> in a module is that you cannot
333 sensibly have two C<< ->wait >>'s in parallel, as that would require
334 multiple interpreters or coroutines/threads, none of which C<AnyEvent>
335 can supply (the coroutine-aware backends L<AnyEvent::Impl::CoroEV> and
336 L<AnyEvent::Impl::CoroEvent> explicitly support concurrent C<< ->wait >>'s
337 from different coroutines, however).
338
339 =item $cv->broadcast
340
341 Flag the condition as ready - a running C<< ->wait >> and all further
342 calls to C<wait> will (eventually) return after this method has been
343 called. If nobody is waiting the broadcast will be remembered..
344
345 =back
346
347 Example:
348
349 # wait till the result is ready
350 my $result_ready = AnyEvent->condvar;
351
352 # do something such as adding a timer
353 # or socket watcher the calls $result_ready->broadcast
354 # when the "result" is ready.
355 # in this case, we simply use a timer:
356 my $w = AnyEvent->timer (
357 after => 1,
358 cb => sub { $result_ready->broadcast },
359 );
360
361 # this "blocks" (while handling events) till the watcher
362 # calls broadcast
363 $result_ready->wait;
364
365 =head1 GLOBAL VARIABLES AND FUNCTIONS
366
367 =over 4
368
369 =item $AnyEvent::MODEL
370
371 Contains C<undef> until the first watcher is being created. Then it
372 contains the event model that is being used, which is the name of the
373 Perl class implementing the model. This class is usually one of the
374 C<AnyEvent::Impl:xxx> modules, but can be any other class in the case
375 AnyEvent has been extended at runtime (e.g. in I<rxvt-unicode>).
376
377 The known classes so far are:
378
379 AnyEvent::Impl::CoroEV based on Coro::EV, best choice.
380 AnyEvent::Impl::CoroEvent based on Coro::Event, second best choice.
381 AnyEvent::Impl::EV based on EV (an interface to libev, best choice).
382 AnyEvent::Impl::Event based on Event, second best choice.
383 AnyEvent::Impl::Glib based on Glib, third-best choice.
384 AnyEvent::Impl::Perl pure-perl implementation, inefficient but portable.
385 AnyEvent::Impl::Tk based on Tk, very bad choice.
386 AnyEvent::Impl::Qt based on Qt, cannot be autoprobed (see its docs).
387 AnyEvent::Impl::EventLib based on Event::Lib, leaks memory and worse.
388 AnyEvent::Impl::POE based on POE, not generic enough for full support.
389
390 There is no support for WxWidgets, as WxWidgets has no support for
391 watching file handles. However, you can use WxWidgets through the
392 POE Adaptor, as POE has a Wx backend that simply polls 20 times per
393 second, which was considered to be too horrible to even consider for
394 AnyEvent. Likewise, other POE backends can be used by AnyEvent by using
395 it's adaptor.
396
397 AnyEvent knows about L<Prima> and L<Wx> and will try to use L<POE> when
398 autodetecting them.
399
400 =item AnyEvent::detect
401
402 Returns C<$AnyEvent::MODEL>, forcing autodetection of the event model
403 if necessary. You should only call this function right before you would
404 have created an AnyEvent watcher anyway, that is, as late as possible at
405 runtime.
406
407 =back
408
409 =head1 WHAT TO DO IN A MODULE
410
411 As a module author, you should C<use AnyEvent> and call AnyEvent methods
412 freely, but you should not load a specific event module or rely on it.
413
414 Be careful when you create watchers in the module body - AnyEvent will
415 decide which event module to use as soon as the first method is called, so
416 by calling AnyEvent in your module body you force the user of your module
417 to load the event module first.
418
419 Never call C<< ->wait >> on a condition variable unless you I<know> that
420 the C<< ->broadcast >> method has been called on it already. This is
421 because it will stall the whole program, and the whole point of using
422 events is to stay interactive.
423
424 It is fine, however, to call C<< ->wait >> when the user of your module
425 requests it (i.e. if you create a http request object ad have a method
426 called C<results> that returns the results, it should call C<< ->wait >>
427 freely, as the user of your module knows what she is doing. always).
428
429 =head1 WHAT TO DO IN THE MAIN PROGRAM
430
431 There will always be a single main program - the only place that should
432 dictate which event model to use.
433
434 If it doesn't care, it can just "use AnyEvent" and use it itself, or not
435 do anything special (it does not need to be event-based) and let AnyEvent
436 decide which implementation to chose if some module relies on it.
437
438 If the main program relies on a specific event model. For example, in
439 Gtk2 programs you have to rely on the Glib module. You should load the
440 event module before loading AnyEvent or any module that uses it: generally
441 speaking, you should load it as early as possible. The reason is that
442 modules might create watchers when they are loaded, and AnyEvent will
443 decide on the event model to use as soon as it creates watchers, and it
444 might chose the wrong one unless you load the correct one yourself.
445
446 You can chose to use a rather inefficient pure-perl implementation by
447 loading the C<AnyEvent::Impl::Perl> module, which gives you similar
448 behaviour everywhere, but letting AnyEvent chose is generally better.
449
450 =cut
451
452 package AnyEvent;
453
454 no warnings;
455 use strict;
456
457 use Carp;
458
459 our $VERSION = '3.3';
460 our $MODEL;
461
462 our $AUTOLOAD;
463 our @ISA;
464
465 our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1;
466
467 our @REGISTRY;
468
469 my @models = (
470 [Coro::EV:: => AnyEvent::Impl::CoroEV::],
471 [Coro::Event:: => AnyEvent::Impl::CoroEvent::],
472 [EV:: => AnyEvent::Impl::EV::],
473 [Event:: => AnyEvent::Impl::Event::],
474 [Glib:: => AnyEvent::Impl::Glib::],
475 [Tk:: => AnyEvent::Impl::Tk::],
476 [Wx:: => AnyEvent::Impl::POE::],
477 [Prima:: => AnyEvent::Impl::POE::],
478 [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl::],
479 # everything below here will not be autoprobed as the pureperl backend should work everywhere
480 [Event::Lib:: => AnyEvent::Impl::EventLib::], # too buggy
481 [Qt:: => AnyEvent::Impl::Qt::], # requires special main program
482 [POE::Kernel:: => AnyEvent::Impl::POE::], # lasciate ogni speranza
483 );
484
485 our %method = map +($_ => 1), qw(io timer signal child condvar broadcast wait one_event DESTROY);
486
487 sub detect() {
488 unless ($MODEL) {
489 no strict 'refs';
490
491 if ($ENV{PERL_ANYEVENT_MODEL} =~ /^([a-zA-Z]+)$/) {
492 my $model = "AnyEvent::Impl::$1";
493 if (eval "require $model") {
494 $MODEL = $model;
495 warn "AnyEvent: loaded model '$model' (forced by \$PERL_ANYEVENT_MODEL), using it.\n" if $verbose > 1;
496 } else {
497 warn "AnyEvent: unable to load model '$model' (from \$PERL_ANYEVENT_MODEL):\n$@" if $verbose;
498 }
499 }
500
501 # check for already loaded models
502 unless ($MODEL) {
503 for (@REGISTRY, @models) {
504 my ($package, $model) = @$_;
505 if (${"$package\::VERSION"} > 0) {
506 if (eval "require $model") {
507 $MODEL = $model;
508 warn "AnyEvent: autodetected model '$model', using it.\n" if $verbose > 1;
509 last;
510 }
511 }
512 }
513
514 unless ($MODEL) {
515 # try to load a model
516
517 for (@REGISTRY, @models) {
518 my ($package, $model) = @$_;
519 if (eval "require $package"
520 and ${"$package\::VERSION"} > 0
521 and eval "require $model") {
522 $MODEL = $model;
523 warn "AnyEvent: autoprobed model '$model', using it.\n" if $verbose > 1;
524 last;
525 }
526 }
527
528 $MODEL
529 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: EV (or Coro+EV), Event (or Coro+Event) or Glib.";
530 }
531 }
532
533 unshift @ISA, $MODEL;
534 push @{"$MODEL\::ISA"}, "AnyEvent::Base";
535 }
536
537 $MODEL
538 }
539
540 sub AUTOLOAD {
541 (my $func = $AUTOLOAD) =~ s/.*://;
542
543 $method{$func}
544 or croak "$func: not a valid method for AnyEvent objects";
545
546 detect unless $MODEL;
547
548 my $class = shift;
549 $class->$func (@_);
550 }
551
552 package AnyEvent::Base;
553
554 # default implementation for ->condvar, ->wait, ->broadcast
555
556 sub condvar {
557 bless \my $flag, "AnyEvent::Base::CondVar"
558 }
559
560 sub AnyEvent::Base::CondVar::broadcast {
561 ${$_[0]}++;
562 }
563
564 sub AnyEvent::Base::CondVar::wait {
565 AnyEvent->one_event while !${$_[0]};
566 }
567
568 # default implementation for ->signal
569
570 our %SIG_CB;
571
572 sub signal {
573 my (undef, %arg) = @_;
574
575 my $signal = uc $arg{signal}
576 or Carp::croak "required option 'signal' is missing";
577
578 $SIG_CB{$signal}{$arg{cb}} = $arg{cb};
579 $SIG{$signal} ||= sub {
580 $_->() for values %{ $SIG_CB{$signal} || {} };
581 };
582
583 bless [$signal, $arg{cb}], "AnyEvent::Base::Signal"
584 }
585
586 sub AnyEvent::Base::Signal::DESTROY {
587 my ($signal, $cb) = @{$_[0]};
588
589 delete $SIG_CB{$signal}{$cb};
590
591 $SIG{$signal} = 'DEFAULT' unless keys %{ $SIG_CB{$signal} };
592 }
593
594 # default implementation for ->child
595
596 our %PID_CB;
597 our $CHLD_W;
598 our $CHLD_DELAY_W;
599 our $PID_IDLE;
600 our $WNOHANG;
601
602 sub _child_wait {
603 while (0 < (my $pid = waitpid -1, $WNOHANG)) {
604 $_->($pid, $?) for (values %{ $PID_CB{$pid} || {} }),
605 (values %{ $PID_CB{0} || {} });
606 }
607
608 undef $PID_IDLE;
609 }
610
611 sub _sigchld {
612 # make sure we deliver these changes "synchronous" with the event loop.
613 $CHLD_DELAY_W ||= AnyEvent->timer (after => 0, cb => sub {
614 undef $CHLD_DELAY_W;
615 &_child_wait;
616 });
617 }
618
619 sub child {
620 my (undef, %arg) = @_;
621
622 defined (my $pid = $arg{pid} + 0)
623 or Carp::croak "required option 'pid' is missing";
624
625 $PID_CB{$pid}{$arg{cb}} = $arg{cb};
626
627 unless ($WNOHANG) {
628 $WNOHANG = eval { require POSIX; &POSIX::WNOHANG } || 1;
629 }
630
631 unless ($CHLD_W) {
632 $CHLD_W = AnyEvent->signal (signal => 'CHLD', cb => \&_sigchld);
633 # child could be a zombie already, so make at least one round
634 &_sigchld;
635 }
636
637 bless [$pid, $arg{cb}], "AnyEvent::Base::Child"
638 }
639
640 sub AnyEvent::Base::Child::DESTROY {
641 my ($pid, $cb) = @{$_[0]};
642
643 delete $PID_CB{$pid}{$cb};
644 delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} };
645
646 undef $CHLD_W unless keys %PID_CB;
647 }
648
649 =head1 SUPPLYING YOUR OWN EVENT MODEL INTERFACE
650
651 This is an advanced topic that you do not normally need to use AnyEvent in
652 a module. This section is only of use to event loop authors who want to
653 provide AnyEvent compatibility.
654
655 If you need to support another event library which isn't directly
656 supported by AnyEvent, you can supply your own interface to it by
657 pushing, before the first watcher gets created, the package name of
658 the event module and the package name of the interface to use onto
659 C<@AnyEvent::REGISTRY>. You can do that before and even without loading
660 AnyEvent, so it is reasonably cheap.
661
662 Example:
663
664 push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
665
666 This tells AnyEvent to (literally) use the C<urxvt::anyevent::>
667 package/class when it finds the C<urxvt> package/module is already loaded.
668
669 When AnyEvent is loaded and asked to find a suitable event model, it
670 will first check for the presence of urxvt by trying to C<use> the
671 C<urxvt::anyevent> module.
672
673 The class should provide implementations for all watcher types. See
674 L<AnyEvent::Impl::EV> (source code), L<AnyEvent::Impl::Glib> (Source code)
675 and so on for actual examples. Use C<perldoc -m AnyEvent::Impl::Glib> to
676 see the sources.
677
678 If you don't provide C<signal> and C<child> watchers than AnyEvent will
679 provide suitable (hopefully) replacements.
680
681 The above example isn't fictitious, the I<rxvt-unicode> (a.k.a. urxvt)
682 terminal emulator uses the above line as-is. An interface isn't included
683 in AnyEvent because it doesn't make sense outside the embedded interpreter
684 inside I<rxvt-unicode>, and it is updated and maintained as part of the
685 I<rxvt-unicode> distribution.
686
687 I<rxvt-unicode> also cheats a bit by not providing blocking access to
688 condition variables: code blocking while waiting for a condition will
689 C<die>. This still works with most modules/usages, and blocking calls must
690 not be done in an interactive application, so it makes sense.
691
692 =head1 ENVIRONMENT VARIABLES
693
694 The following environment variables are used by this module:
695
696 =over 4
697
698 =item C<PERL_ANYEVENT_VERBOSE>
699
700 By default, AnyEvent will be completely silent except in fatal
701 conditions. You can set this environment variable to make AnyEvent more
702 talkative.
703
704 When set to C<1> or higher, causes AnyEvent to warn about unexpected
705 conditions, such as not being able to load the event model specified by
706 C<PERL_ANYEVENT_MODEL>.
707
708 When set to C<2> or higher, cause AnyEvent to report to STDERR which event
709 model it chooses.
710
711 =item C<PERL_ANYEVENT_MODEL>
712
713 This can be used to specify the event model to be used by AnyEvent, before
714 autodetection and -probing kicks in. It must be a string consisting
715 entirely of ASCII letters. The string C<AnyEvent::Impl::> gets prepended
716 and the resulting module name is loaded and if the load was successful,
717 used as event model. If it fails to load AnyEvent will proceed with
718 autodetection and -probing.
719
720 This functionality might change in future versions.
721
722 For example, to force the pure perl model (L<AnyEvent::Impl::Perl>) you
723 could start your program like this:
724
725 PERL_ANYEVENT_MODEL=Perl perl ...
726
727 =back
728
729 =head1 EXAMPLE PROGRAM
730
731 The following program uses an I/O watcher to read data from STDIN, a timer
732 to display a message once per second, and a condition variable to quit the
733 program when the user enters quit:
734
735 use AnyEvent;
736
737 my $cv = AnyEvent->condvar;
738
739 my $io_watcher = AnyEvent->io (
740 fh => \*STDIN,
741 poll => 'r',
742 cb => sub {
743 warn "io event <$_[0]>\n"; # will always output <r>
744 chomp (my $input = <STDIN>); # read a line
745 warn "read: $input\n"; # output what has been read
746 $cv->broadcast if $input =~ /^q/i; # quit program if /^q/i
747 },
748 );
749
750 my $time_watcher; # can only be used once
751
752 sub new_timer {
753 $timer = AnyEvent->timer (after => 1, cb => sub {
754 warn "timeout\n"; # print 'timeout' about every second
755 &new_timer; # and restart the time
756 });
757 }
758
759 new_timer; # create first timer
760
761 $cv->wait; # wait until user enters /^q/i
762
763 =head1 REAL-WORLD EXAMPLE
764
765 Consider the L<Net::FCP> module. It features (among others) the following
766 API calls, which are to freenet what HTTP GET requests are to http:
767
768 my $data = $fcp->client_get ($url); # blocks
769
770 my $transaction = $fcp->txn_client_get ($url); # does not block
771 $transaction->cb ( sub { ... } ); # set optional result callback
772 my $data = $transaction->result; # possibly blocks
773
774 The C<client_get> method works like C<LWP::Simple::get>: it requests the
775 given URL and waits till the data has arrived. It is defined to be:
776
777 sub client_get { $_[0]->txn_client_get ($_[1])->result }
778
779 And in fact is automatically generated. This is the blocking API of
780 L<Net::FCP>, and it works as simple as in any other, similar, module.
781
782 More complicated is C<txn_client_get>: It only creates a transaction
783 (completion, result, ...) object and initiates the transaction.
784
785 my $txn = bless { }, Net::FCP::Txn::;
786
787 It also creates a condition variable that is used to signal the completion
788 of the request:
789
790 $txn->{finished} = AnyAvent->condvar;
791
792 It then creates a socket in non-blocking mode.
793
794 socket $txn->{fh}, ...;
795 fcntl $txn->{fh}, F_SETFL, O_NONBLOCK;
796 connect $txn->{fh}, ...
797 and !$!{EWOULDBLOCK}
798 and !$!{EINPROGRESS}
799 and Carp::croak "unable to connect: $!\n";
800
801 Then it creates a write-watcher which gets called whenever an error occurs
802 or the connection succeeds:
803
804 $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w });
805
806 And returns this transaction object. The C<fh_ready_w> callback gets
807 called as soon as the event loop detects that the socket is ready for
808 writing.
809
810 The C<fh_ready_w> method makes the socket blocking again, writes the
811 request data and replaces the watcher by a read watcher (waiting for reply
812 data). The actual code is more complicated, but that doesn't matter for
813 this example:
814
815 fcntl $txn->{fh}, F_SETFL, 0;
816 syswrite $txn->{fh}, $txn->{request}
817 or die "connection or write error";
818 $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r });
819
820 Again, C<fh_ready_r> waits till all data has arrived, and then stores the
821 result and signals any possible waiters that the request ahs finished:
822
823 sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf};
824
825 if (end-of-file or data complete) {
826 $txn->{result} = $txn->{buf};
827 $txn->{finished}->broadcast;
828 $txb->{cb}->($txn) of $txn->{cb}; # also call callback
829 }
830
831 The C<result> method, finally, just waits for the finished signal (if the
832 request was already finished, it doesn't wait, of course, and returns the
833 data:
834
835 $txn->{finished}->wait;
836 return $txn->{result};
837
838 The actual code goes further and collects all errors (C<die>s, exceptions)
839 that occured during request processing. The C<result> method detects
840 whether an exception as thrown (it is stored inside the $txn object)
841 and just throws the exception, which means connection errors and other
842 problems get reported tot he code that tries to use the result, not in a
843 random callback.
844
845 All of this enables the following usage styles:
846
847 1. Blocking:
848
849 my $data = $fcp->client_get ($url);
850
851 2. Blocking, but running in parallel:
852
853 my @datas = map $_->result,
854 map $fcp->txn_client_get ($_),
855 @urls;
856
857 Both blocking examples work without the module user having to know
858 anything about events.
859
860 3a. Event-based in a main program, using any supported event module:
861
862 use EV;
863
864 $fcp->txn_client_get ($url)->cb (sub {
865 my $txn = shift;
866 my $data = $txn->result;
867 ...
868 });
869
870 EV::loop;
871
872 3b. The module user could use AnyEvent, too:
873
874 use AnyEvent;
875
876 my $quit = AnyEvent->condvar;
877
878 $fcp->txn_client_get ($url)->cb (sub {
879 ...
880 $quit->broadcast;
881 });
882
883 $quit->wait;
884
885
886 =head1 BENCHMARK
887
888 To give you an idea of the performance and overheads that AnyEvent adds
889 over the event loops themselves (and to give you an impression of the
890 speed of various event loops), here is a benchmark of various supported
891 event models natively and with anyevent. The benchmark creates a lot of
892 timers (with a zero timeout) and I/O watchers (watching STDOUT, a pty, to
893 become writable, which it is), lets them fire exactly once and destroys
894 them again.
895
896 Rewriting the benchmark to use many different sockets instead of using
897 the same filehandle for all I/O watchers results in a much longer runtime
898 (socket creation is expensive), but qualitatively the same figures, so it
899 was not used.
900
901 =head2 Explanation of the columns
902
903 I<watcher> is the number of event watchers created/destroyed. Since
904 different event models feature vastly different performances, each event
905 loop was given a number of watchers so that overall runtime is acceptable
906 and similar between tested event loop (and keep them from crashing): Glib
907 would probably take thousands of years if asked to process the same number
908 of watchers as EV in this benchmark.
909
910 I<bytes> is the number of bytes (as measured by the resident set size,
911 RSS) consumed by each watcher. This method of measuring captures both C
912 and Perl-based overheads.
913
914 I<create> is the time, in microseconds (millionths of seconds), that it
915 takes to create a single watcher. The callback is a closure shared between
916 all watchers, to avoid adding memory overhead. That means closure creation
917 and memory usage is not included in the figures.
918
919 I<invoke> is the time, in microseconds, used to invoke a simple
920 callback. The callback simply counts down a Perl variable and after it was
921 invoked "watcher" times, it would C<< ->broadcast >> a condvar once to
922 signal the end of this phase.
923
924 I<destroy> is the time, in microseconds, that it takes to destroy a single
925 watcher.
926
927 =head2 Results
928
929 name watchers bytes create invoke destroy comment
930 EV/EV 400000 244 0.56 0.46 0.31 EV native interface
931 EV/Any 100000 610 3.52 0.91 0.75 EV + AnyEvent watchers
932 CoroEV/Any 100000 610 3.49 0.92 0.75 coroutines + Coro::Signal
933 Perl/Any 100000 513 4.91 0.92 1.15 pure perl implementation
934 Event/Event 16000 523 28.05 21.38 0.86 Event native interface
935 Event/Any 16000 943 34.43 20.48 1.39 Event + AnyEvent watchers
936 Glib/Any 16000 1357 96.99 12.55 55.51 quadratic behaviour
937 Tk/Any 2000 1855 27.01 66.61 14.03 SEGV with >> 2000 watchers
938 POE/Event 2000 6644 108.15 768.19 14.33 via POE::Loop::Event
939 POE/Select 2000 6343 94.69 807.65 562.69 via POE::Loop::Select
940
941 =head2 Discussion
942
943 The benchmark does I<not> measure scalability of the event loop very
944 well. For example, a select-based event loop (such as the pure perl one)
945 can never compete with an event loop that uses epoll when the number of
946 file descriptors grows high. In this benchmark, all events become ready at
947 the same time, so select/poll-based implementations get an unnatural speed
948 boost.
949
950 C<EV> is the sole leader regarding speed and memory use, which are both
951 maximal/minimal, respectively. Even when going through AnyEvent, there are
952 only two event loops that use slightly less memory (the C<Event> module
953 natively and the pure perl backend), and no faster event models, not even
954 C<Event> natively.
955
956 The pure perl implementation is hit in a few sweet spots (both the
957 zero timeout and the use of a single fd hit optimisations in the perl
958 interpreter and the backend itself, and all watchers become ready at the
959 same time). Nevertheless this shows that it adds very little overhead in
960 itself. Like any select-based backend its performance becomes really bad
961 with lots of file descriptors (and few of them active), of course, but
962 this was not subject of this benchmark.
963
964 The C<Event> module has a relatively high setup and callback invocation cost,
965 but overall scores on the third place.
966
967 C<Glib>'s memory usage is quite a bit bit higher, but it features a
968 faster callback invocation and overall ends up in the same class as
969 C<Event>. However, Glib scales extremely badly, doubling the number of
970 watchers increases the processing time by more than a factor of four,
971 making it completely unusable when using larger numbers of watchers
972 (note that only a single file descriptor was used in the benchmark, so
973 inefficiencies of C<poll> do not account for this).
974
975 The C<Tk> adaptor works relatively well. The fact that it crashes with
976 more than 2000 watchers is a big setback, however, as correctness takes
977 precedence over speed. Nevertheless, its performance is surprising, as the
978 file descriptor is dup()ed for each watcher. This shows that the dup()
979 employed by some adaptors is not a big performance issue (it does incur a
980 hidden memory cost inside the kernel, though, that is not reflected in the
981 figures above).
982
983 C<POE>, regardless of underlying event loop (wether using its pure perl
984 select-based backend or the Event module) shows abysmal performance and
985 memory usage: Watchers use almost 30 times as much memory as EV watchers,
986 and 10 times as much memory as both Event or EV via AnyEvent. Watcher
987 invocation is almost 900 times slower than with AnyEvent's pure perl
988 implementation. The design of the POE adaptor class in AnyEvent can not
989 really account for this, as session creation overhead is small compared
990 to execution of the state machine, which is coded pretty optimally within
991 L<AnyEvent::Impl::POE>. POE simply seems to be abysmally slow.
992
993 =head2 Summary
994
995 Using EV through AnyEvent is faster than any other event loop, but most
996 event loops have acceptable performance with or without AnyEvent.
997
998 The overhead AnyEvent adds is usually much smaller than the overhead of
999 the actual event loop, only with extremely fast event loops such as the EV
1000 adds AnyEvent significant overhead.
1001
1002 And you should simply avoid POE like the plague if you want performance or
1003 reasonable memory usage.
1004
1005
1006 =head1 FORK
1007
1008 Most event libraries are not fork-safe. The ones who are usually are
1009 because they are so inefficient. Only L<EV> is fully fork-aware.
1010
1011 If you have to fork, you must either do so I<before> creating your first
1012 watcher OR you must not use AnyEvent at all in the child.
1013
1014
1015 =head1 SECURITY CONSIDERATIONS
1016
1017 AnyEvent can be forced to load any event model via
1018 $ENV{PERL_ANYEVENT_MODEL}. While this cannot (to my knowledge) be used to
1019 execute arbitrary code or directly gain access, it can easily be used to
1020 make the program hang or malfunction in subtle ways, as AnyEvent watchers
1021 will not be active when the program uses a different event model than
1022 specified in the variable.
1023
1024 You can make AnyEvent completely ignore this variable by deleting it
1025 before the first watcher gets created, e.g. with a C<BEGIN> block:
1026
1027 BEGIN { delete $ENV{PERL_ANYEVENT_MODEL} }
1028
1029 use AnyEvent;
1030
1031
1032 =head1 SEE ALSO
1033
1034 Event modules: L<Coro::EV>, L<EV>, L<EV::Glib>, L<Glib::EV>,
1035 L<Coro::Event>, L<Event>, L<Glib::Event>, L<Glib>, L<Coro>, L<Tk>,
1036 L<Event::Lib>, L<Qt>, L<POE>.
1037
1038 Implementations: L<AnyEvent::Impl::CoroEV>, L<AnyEvent::Impl::EV>,
1039 L<AnyEvent::Impl::CoroEvent>, L<AnyEvent::Impl::Event>, L<AnyEvent::Impl::Glib>,
1040 L<AnyEvent::Impl::Tk>, L<AnyEvent::Impl::Perl>, L<AnyEvent::Impl::EventLib>,
1041 L<AnyEvent::Impl::Qt>, L<AnyEvent::Impl::POE>.
1042
1043 Nontrivial usage examples: L<Net::FCP>, L<Net::XMPP2>.
1044
1045
1046 =head1 AUTHOR
1047
1048 Marc Lehmann <schmorp@schmorp.de>
1049 http://home.schmorp.de/
1050
1051 =cut
1052
1053 1
1054