ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent.pm
(Generate patch)

Comparing AnyEvent/lib/AnyEvent.pm (file contents):
Revision 1.7 by root, Fri Dec 30 01:28:31 2005 UTC vs.
Revision 1.41 by root, Mon Apr 7 19:23:59 2008 UTC

1=head1 NAME 1=head1 NAME
2 2
3AnyEvent - provide framework for multiple event loops 3AnyEvent - provide framework for multiple event loops
4 4
5Event, Coro, Glib, Tk - various supported event loops 5Event, Coro, Glib, Tk, Perl - various supported event loops
6 6
7=head1 SYNOPSIS 7=head1 SYNOPSIS
8 8
9 use AnyEvent; 9 use AnyEvent;
10 10
11 my $w = AnyEvent->io (fh => ..., poll => "[rw]+", cb => sub { 11 my $w = AnyEvent->io (fh => $fh, poll => "r|w", cb => sub {
12 my ($poll_got) = @_;
13 ... 12 ...
14 }); 13 });
15
16* only one io watcher per $fh and $poll type is allowed (i.e. on a socket
17you can have one r + one w or one rw watcher, not any more (limitation by
18Tk).
19
20* the C<$poll_got> passed to the handler needs to be checked by looking
21for single characters (e.g. with a regex), as it can contain more event
22types than were requested (e.g. a 'w' watcher might generate 'rw' events,
23limitation by Glib).
24
25* AnyEvent will keep filehandles alive, so as long as the watcher exists,
26the filehandle exists.
27 14
28 my $w = AnyEvent->timer (after => $seconds, cb => sub { 15 my $w = AnyEvent->timer (after => $seconds, cb => sub {
29 ... 16 ...
30 }); 17 });
31 18
32* io and time watchers get canceled whenever $w is destroyed, so keep a copy 19 my $w = AnyEvent->condvar; # stores wether a condition was flagged
33
34* timers can only be used once and must be recreated for repeated
35operation (limitation by Glib and Tk).
36
37 my $w = AnyEvent->condvar; # kind of main loop replacement
38 $w->wait; # enters main loop till $condvar gets ->broadcast 20 $w->wait; # enters "main loop" till $condvar gets ->broadcast
39 $w->broadcast; # wake up current and all future wait's 21 $w->broadcast; # wake up current and all future wait's
40 22
41* condvars are used to give blocking behaviour when neccessary. Create 23=head1 WHY YOU SHOULD USE THIS MODULE
42a condvar for any "request" or "event" your module might create, C<< 24
43->broadcast >> it when the event happens and provide a function that calls 25Glib, POE, IO::Async, Event... CPAN offers event models by the dozen
44C<< ->wait >> for it. See the examples below. 26nowadays. So what is different about AnyEvent?
27
28Executive Summary: AnyEvent is I<compatible>, AnyEvent is I<free of
29policy> and AnyEvent is I<small and efficient>.
30
31First and foremost, I<AnyEvent is not an event model> itself, it only
32interfaces to whatever event model the main program happens to use in a
33pragmatic way. For event models and certain classes of immortals alike,
34the statement "there can only be one" is a bitter reality, and AnyEvent
35helps hiding the differences.
36
37The goal of AnyEvent is to offer module authors the ability to do event
38programming (waiting for I/O or timer events) without subscribing to a
39religion, a way of living, and most importantly: without forcing your
40module users into the same thing by forcing them to use the same event
41model you use.
42
43For modules like POE or IO::Async (the latter of which is actually
44named confusingly, as it does neither do I/O nor does it do anything
45asynchronously...), using them in your module is like joining a
46cult: After you joined, you are dependent on them and you cannot use
47anything else, as it is simply incompatible to everything that isn't
48itself.
49
50AnyEvent + POE works fine. AnyEvent + Glib works fine. AnyEvent + Tk
51works fine etc. etc. but none of these work together with the rest: POE
52+ IO::Async? no go. Tk + Event? no go. If your module uses one of
53those, every user of your module has to use it, too. If your module
54uses AnyEvent, it works transparently with all event models it supports
55(including stuff like POE and IO::Async).
56
57In addition of being free of having to use I<the one and only true event
58model>, AnyEvent also is free of bloat and policy: with POE or similar
59modules, you get an enourmous amount of code and strict rules you have
60to follow. AnyEvent, on the other hand, is lean and to the point by only
61offering the functionality that is useful, in as thin as a wrapper as
62technically possible.
63
45 64
46=head1 DESCRIPTION 65=head1 DESCRIPTION
47 66
48L<AnyEvent> provides an identical interface to multiple event loops. This 67L<AnyEvent> provides an identical interface to multiple event loops. This
49allows module authors to utilizy an event loop without forcing module 68allows module authors to utilise an event loop without forcing module
50users to use the same event loop (as only a single event loop can coexist 69users to use the same event loop (as only a single event loop can coexist
51peacefully at any one time). 70peacefully at any one time).
52 71
53The interface itself is vaguely similar but not identical to the Event 72The interface itself is vaguely similar but not identical to the Event
54module. 73module.
56On the first call of any method, the module tries to detect the currently 75On the first call of any method, the module tries to detect the currently
57loaded event loop by probing wether any of the following modules is 76loaded event loop by probing wether any of the following modules is
58loaded: L<Coro::Event>, L<Event>, L<Glib>, L<Tk>. The first one found is 77loaded: L<Coro::Event>, L<Event>, L<Glib>, L<Tk>. The first one found is
59used. If none is found, the module tries to load these modules in the 78used. If none is found, the module tries to load these modules in the
60order given. The first one that could be successfully loaded will be 79order given. The first one that could be successfully loaded will be
61used. If still none could be found, it will issue an error. 80used. If still none could be found, AnyEvent will fall back to a pure-perl
81event loop, which is also not very efficient.
82
83Because AnyEvent first checks for modules that are already loaded, loading
84an Event model explicitly before first using AnyEvent will likely make
85that model the default. For example:
86
87 use Tk;
88 use AnyEvent;
89
90 # .. AnyEvent will likely default to Tk
91
92The pure-perl implementation of AnyEvent is called
93C<AnyEvent::Impl::Perl>. Like other event modules you can load it
94explicitly.
95
96=head1 WATCHERS
97
98AnyEvent has the central concept of a I<watcher>, which is an object that
99stores relevant data for each kind of event you are waiting for, such as
100the callback to call, the filehandle to watch, etc.
101
102These watchers are normal Perl objects with normal Perl lifetime. After
103creating a watcher it will immediately "watch" for events and invoke
104the callback. To disable the watcher you have to destroy it (e.g. by
105setting the variable that stores it to C<undef> or otherwise deleting all
106references to it).
107
108All watchers are created by calling a method on the C<AnyEvent> class.
109
110=head2 IO WATCHERS
111
112You can create I/O watcher by calling the C<< AnyEvent->io >> method with
113the following mandatory arguments:
114
115C<fh> the Perl I<filehandle> (not filedescriptor) to watch for
116events. C<poll> must be a string that is either C<r> or C<w>, that creates
117a watcher waiting for "r"eadable or "w"ritable events. C<cb> the callback
118to invoke everytime the filehandle becomes ready.
119
120Only one io watcher per C<fh> and C<poll> combination is allowed (i.e. on
121a socket you can have one r + one w, not any more (limitation comes from
122Tk - if you are sure you are not using Tk this limitation is gone).
123
124Filehandles will be kept alive, so as long as the watcher exists, the
125filehandle exists, too.
126
127Example:
128
129 # wait for readability of STDIN, then read a line and disable the watcher
130 my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
131 chomp (my $input = <STDIN>);
132 warn "read: $input\n";
133 undef $w;
134 });
135
136=head2 TIME WATCHERS
137
138You can create a time watcher by calling the C<< AnyEvent->timer >>
139method with the following mandatory arguments:
140
141C<after> after how many seconds (fractions are supported) should the timer
142activate. C<cb> the callback to invoke.
143
144The timer callback will be invoked at most once: if you want a repeating
145timer you have to create a new watcher (this is a limitation by both Tk
146and Glib).
147
148Example:
149
150 # fire an event after 7.7 seconds
151 my $w = AnyEvent->timer (after => 7.7, cb => sub {
152 warn "timeout\n";
153 });
154
155 # to cancel the timer:
156 undef $w;
157
158=head2 CONDITION WATCHERS
159
160Condition watchers can be created by calling the C<< AnyEvent->condvar >>
161method without any arguments.
162
163A condition watcher watches for a condition - precisely that the C<<
164->broadcast >> method has been called.
165
166Note that condition watchers recurse into the event loop - if you have
167two watchers that call C<< ->wait >> in a round-robbin fashion, you
168lose. Therefore, condition watchers are good to export to your caller, but
169you should avoid making a blocking wait, at least in callbacks, as this
170usually asks for trouble.
171
172The watcher has only two methods:
62 173
63=over 4 174=over 4
64 175
176=item $cv->wait
177
178Wait (blocking if necessary) until the C<< ->broadcast >> method has been
179called on c<$cv>, while servicing other watchers normally.
180
181Not all event models support a blocking wait - some die in that case, so
182if you are using this from a module, never require a blocking wait, but
183let the caller decide wether the call will block or not (for example,
184by coupling condition variables with some kind of request results and
185supporting callbacks so the caller knows that getting the result will not
186block, while still suppporting blockign waits if the caller so desires).
187
188You can only wait once on a condition - additional calls will return
189immediately.
190
191=item $cv->broadcast
192
193Flag the condition as ready - a running C<< ->wait >> and all further
194calls to C<wait> will return after this method has been called. If nobody
195is waiting the broadcast will be remembered..
196
197Example:
198
199 # wait till the result is ready
200 my $result_ready = AnyEvent->condvar;
201
202 # do something such as adding a timer
203 # or socket watcher the calls $result_ready->broadcast
204 # when the "result" is ready.
205
206 $result_ready->wait;
207
208=back
209
210=head2 SIGNAL WATCHERS
211
212You can listen for signals using a signal watcher, C<signal> is the signal
213I<name> without any C<SIG> prefix. Multiple signals events can be clumped
214together into one callback invocation, and callback invocation might or
215might not be asynchronous.
216
217These watchers might use C<%SIG>, so programs overwriting those signals
218directly will likely not work correctly.
219
220Example: exit on SIGINT
221
222 my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });
223
224=head2 CHILD PROCESS WATCHERS
225
226You can also listen for the status of a child process specified by the
227C<pid> argument (or any child if the pid argument is 0). The watcher will
228trigger as often as status change for the child are received. This works
229by installing a signal handler for C<SIGCHLD>. The callback will be called with
230the pid and exit status (as returned by waitpid).
231
232Example: wait for pid 1333
233
234 my $w = AnyEvent->child (pid => 1333, cb => sub { warn "exit status $?" });
235
236=head1 GLOBALS
237
238=over 4
239
240=item $AnyEvent::MODEL
241
242Contains C<undef> until the first watcher is being created. Then it
243contains the event model that is being used, which is the name of the
244Perl class implementing the model. This class is usually one of the
245C<AnyEvent::Impl:xxx> modules, but can be any other class in the case
246AnyEvent has been extended at runtime (e.g. in I<rxvt-unicode>).
247
248The known classes so far are:
249
250 AnyEvent::Impl::CoroEV based on Coro::EV, best choice.
251 AnyEvent::Impl::EV based on EV (an interface to libev, also best choice).
252 AnyEvent::Impl::CoroEvent based on Coro::Event, second best choice.
253 AnyEvent::Impl::Event based on Event, also second best choice :)
254 AnyEvent::Impl::Glib based on Glib, second-best choice.
255 AnyEvent::Impl::Tk based on Tk, very bad choice.
256 AnyEvent::Impl::Perl pure-perl implementation, inefficient.
257
258=item AnyEvent::detect
259
260Returns C<$AnyEvent::MODEL>, forcing autodetection of the event model if
261necessary. You should only call this function right before you would have
262created an AnyEvent watcher anyway, that is, very late at runtime.
263
264=back
265
266=head1 WHAT TO DO IN A MODULE
267
268As a module author, you should "use AnyEvent" and call AnyEvent methods
269freely, but you should not load a specific event module or rely on it.
270
271Be careful when you create watchers in the module body - Anyevent will
272decide which event module to use as soon as the first method is called, so
273by calling AnyEvent in your module body you force the user of your module
274to load the event module first.
275
276=head1 WHAT TO DO IN THE MAIN PROGRAM
277
278There will always be a single main program - the only place that should
279dictate which event model to use.
280
281If it doesn't care, it can just "use AnyEvent" and use it itself, or not
282do anything special and let AnyEvent decide which implementation to chose.
283
284If the main program relies on a specific event model (for example, in Gtk2
285programs you have to rely on either Glib or Glib::Event), you should load
286it before loading AnyEvent or any module that uses it, generally, as early
287as possible. The reason is that modules might create watchers when they
288are loaded, and AnyEvent will decide on the event model to use as soon as
289it creates watchers, and it might chose the wrong one unless you load the
290correct one yourself.
291
292You can chose to use a rather inefficient pure-perl implementation by
293loading the C<AnyEvent::Impl::Perl> module, but letting AnyEvent chose is
294generally better.
295
65=cut 296=cut
66 297
67package AnyEvent; 298package AnyEvent;
68 299
69no warnings; 300no warnings;
70use strict 'vars'; 301use strict;
302
71use Carp; 303use Carp;
72 304
73our $VERSION = '0.4'; 305our $VERSION = '3.0';
74our $MODEL; 306our $MODEL;
75 307
76our $AUTOLOAD; 308our $AUTOLOAD;
77our @ISA; 309our @ISA;
78 310
79our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1; 311our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1;
80 312
313our @REGISTRY;
314
81my @models = ( 315my @models = (
82 [Coro => Coro::Event::], 316 [Coro::EV:: => AnyEvent::Impl::CoroEV::],
83 [Event => Event::], 317 [EV:: => AnyEvent::Impl::EV::],
84 [Glib => Glib::], 318 [Coro::Event:: => AnyEvent::Impl::CoroEvent::],
85 [Tk => Tk::], 319 [Event:: => AnyEvent::Impl::Event::],
320 [Glib:: => AnyEvent::Impl::Glib::],
321 [Tk:: => AnyEvent::Impl::Tk::],
322 [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl::],
86); 323);
87 324
88our %method = map +($_ => 1), qw(io timer condvar broadcast wait cancel DESTROY); 325our %method = map +($_ => 1), qw(io timer condvar broadcast wait signal one_event DESTROY);
89 326
90sub AUTOLOAD { 327sub detect() {
91 $AUTOLOAD =~ s/.*://;
92
93 $method{$AUTOLOAD}
94 or croak "$AUTOLOAD: not a valid method for AnyEvent objects";
95
96 unless ($MODEL) { 328 unless ($MODEL) {
329 no strict 'refs';
330
97 # check for already loaded models 331 # check for already loaded models
98 for (@models) { 332 for (@REGISTRY, @models) {
99 my ($model, $package) = @$_; 333 my ($package, $model) = @$_;
100 if (${"$package\::VERSION"} > 0) { 334 if (${"$package\::VERSION"} > 0) {
101 eval "require AnyEvent::Impl::$model"; 335 if (eval "require $model") {
336 $MODEL = $model;
102 warn "AnyEvent: found model '$model', using it.\n" if $MODEL && $verbose > 1; 337 warn "AnyEvent: found model '$model', using it.\n" if $verbose > 1;
103 last if $MODEL; 338 last;
339 }
104 } 340 }
105 } 341 }
106 342
107 unless ($MODEL) { 343 unless ($MODEL) {
108 # try to load a model 344 # try to load a model
109 345
110 for (@models) { 346 for (@REGISTRY, @models) {
111 my ($model, $package) = @$_; 347 my ($package, $model) = @$_;
112 eval "require AnyEvent::Impl::$model"; 348 if (eval "require $package"
349 and ${"$package\::VERSION"} > 0
350 and eval "require $model") {
351 $MODEL = $model;
113 warn "AnyEvent: autprobed and loaded model '$model', using it.\n" if $MODEL && $verbose > 1; 352 warn "AnyEvent: autoprobed and loaded model '$model', using it.\n" if $verbose > 1;
114 last if $MODEL; 353 last;
354 }
115 } 355 }
116 356
117 $MODEL 357 $MODEL
118 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: Coro, Event, Glib or Tk."; 358 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), Glib or Tk.";
119 } 359 }
360
361 unshift @ISA, $MODEL;
362 push @{"$MODEL\::ISA"}, "AnyEvent::Base";
120 } 363 }
121 364
122 @ISA = $MODEL; 365 $MODEL
366}
367
368sub AUTOLOAD {
369 (my $func = $AUTOLOAD) =~ s/.*://;
370
371 $method{$func}
372 or croak "$func: not a valid method for AnyEvent objects";
373
374 detect unless $MODEL;
123 375
124 my $class = shift; 376 my $class = shift;
125 $class->$AUTOLOAD (@_); 377 $class->$func (@_);
126} 378}
127 379
128=back 380package AnyEvent::Base;
381
382# default implementation for ->condvar, ->wait, ->broadcast
383
384sub condvar {
385 bless \my $flag, "AnyEvent::Base::CondVar"
386}
387
388sub AnyEvent::Base::CondVar::broadcast {
389 ${$_[0]}++;
390}
391
392sub AnyEvent::Base::CondVar::wait {
393 AnyEvent->one_event while !${$_[0]};
394}
395
396# default implementation for ->signal
397
398our %SIG_CB;
399
400sub signal {
401 my (undef, %arg) = @_;
402
403 my $signal = uc $arg{signal}
404 or Carp::croak "required option 'signal' is missing";
405
406 $SIG_CB{$signal}{$arg{cb}} = $arg{cb};
407 $SIG{$signal} ||= sub {
408 $_->() for values %{ $SIG_CB{$signal} || {} };
409 };
410
411 bless [$signal, $arg{cb}], "AnyEvent::Base::Signal"
412}
413
414sub AnyEvent::Base::Signal::DESTROY {
415 my ($signal, $cb) = @{$_[0]};
416
417 delete $SIG_CB{$signal}{$cb};
418
419 $SIG{$signal} = 'DEFAULT' unless keys %{ $SIG_CB{$signal} };
420}
421
422# default implementation for ->child
423
424our %PID_CB;
425our $CHLD_W;
426our $CHLD_DELAY_W;
427our $PID_IDLE;
428our $WNOHANG;
429
430sub _child_wait {
431 while (0 < (my $pid = waitpid -1, $WNOHANG)) {
432 $_->($pid, $?) for (values %{ $PID_CB{$pid} || {} }),
433 (values %{ $PID_CB{0} || {} });
434 }
435
436 undef $PID_IDLE;
437}
438
439sub _sigchld {
440 # make sure we deliver these changes "synchronous" with the event loop.
441 $CHLD_DELAY_W ||= AnyEvent->timer (after => 0, cb => sub {
442 undef $CHLD_DELAY_W;
443 &_child_wait;
444 });
445}
446
447sub child {
448 my (undef, %arg) = @_;
449
450 defined (my $pid = $arg{pid} + 0)
451 or Carp::croak "required option 'pid' is missing";
452
453 $PID_CB{$pid}{$arg{cb}} = $arg{cb};
454
455 unless ($WNOHANG) {
456 $WNOHANG = eval { require POSIX; &POSIX::WNOHANG } || 1;
457 }
458
459 unless ($CHLD_W) {
460 $CHLD_W = AnyEvent->signal (signal => 'CHLD', cb => \&_sigchld);
461 # child could be a zombie already, so make at least one round
462 &_sigchld;
463 }
464
465 bless [$pid, $arg{cb}], "AnyEvent::Base::Child"
466}
467
468sub AnyEvent::Base::Child::DESTROY {
469 my ($pid, $cb) = @{$_[0]};
470
471 delete $PID_CB{$pid}{$cb};
472 delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} };
473
474 undef $CHLD_W unless keys %PID_CB;
475}
476
477=head1 SUPPLYING YOUR OWN EVENT MODEL INTERFACE
478
479If you need to support another event library which isn't directly
480supported by AnyEvent, you can supply your own interface to it by
481pushing, before the first watcher gets created, the package name of
482the event module and the package name of the interface to use onto
483C<@AnyEvent::REGISTRY>. You can do that before and even without loading
484AnyEvent.
485
486Example:
487
488 push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
489
490This tells AnyEvent to (literally) use the C<urxvt::anyevent::>
491package/class when it finds the C<urxvt> package/module is loaded. When
492AnyEvent is loaded and asked to find a suitable event model, it will
493first check for the presence of urxvt.
494
495The class should provide implementations for all watcher types (see
496L<AnyEvent::Impl::Event> (source code), L<AnyEvent::Impl::Glib>
497(Source code) and so on for actual examples, use C<perldoc -m
498AnyEvent::Impl::Glib> to see the sources).
499
500The above isn't fictitious, the I<rxvt-unicode> (a.k.a. urxvt)
501uses the above line as-is. An interface isn't included in AnyEvent
502because it doesn't make sense outside the embedded interpreter inside
503I<rxvt-unicode>, and it is updated and maintained as part of the
504I<rxvt-unicode> distribution.
505
506I<rxvt-unicode> also cheats a bit by not providing blocking access to
507condition variables: code blocking while waiting for a condition will
508C<die>. This still works with most modules/usages, and blocking calls must
509not be in an interactive application, so it makes sense.
129 510
130=head1 ENVIRONMENT VARIABLES 511=head1 ENVIRONMENT VARIABLES
131 512
132The following environment variables are used by this module: 513The following environment variables are used by this module:
133 514

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines