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.11 by root, Thu Jul 20 01:32:11 2006 UTC vs.
Revision 1.30 by root, Fri Nov 2 19:12:02 2007 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
42a condvar for any "request" or "event" your module might create, C<<
43->broadcast >> it when the event happens and provide a function that calls
44C<< ->wait >> for it. See the examples below.
45
46=head1 DESCRIPTION 23=head1 DESCRIPTION
47 24
48L<AnyEvent> provides an identical interface to multiple event loops. This 25L<AnyEvent> provides an identical interface to multiple event loops. This
49allows module authors to utilizy an event loop without forcing module 26allows 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 27users to use the same event loop (as only a single event loop can coexist
51peacefully at any one time). 28peacefully at any one time).
52 29
53The interface itself is vaguely similar but not identical to the Event 30The interface itself is vaguely similar but not identical to the Event
54module. 31module.
56On the first call of any method, the module tries to detect the currently 33On 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 34loaded 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 35loaded: 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 36used. 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 37order given. The first one that could be successfully loaded will be
61used. If still none could be found, it will issue an error. 38used. If still none could be found, AnyEvent will fall back to a pure-perl
39event loop, which is also not very efficient.
40
41Because AnyEvent first checks for modules that are already loaded, loading
42an Event model explicitly before first using AnyEvent will likely make
43that model the default. For example:
44
45 use Tk;
46 use AnyEvent;
47
48 # .. AnyEvent will likely default to Tk
49
50The pure-perl implementation of AnyEvent is called
51C<AnyEvent::Impl::Perl>. Like other event modules you can load it
52explicitly.
53
54=head1 WATCHERS
55
56AnyEvent has the central concept of a I<watcher>, which is an object that
57stores relevant data for each kind of event you are waiting for, such as
58the callback to call, the filehandle to watch, etc.
59
60These watchers are normal Perl objects with normal Perl lifetime. After
61creating a watcher it will immediately "watch" for events and invoke
62the callback. To disable the watcher you have to destroy it (e.g. by
63setting the variable that stores it to C<undef> or otherwise deleting all
64references to it).
65
66All watchers are created by calling a method on the C<AnyEvent> class.
67
68=head2 IO WATCHERS
69
70You can create I/O watcher by calling the C<< AnyEvent->io >> method with
71the following mandatory arguments:
72
73C<fh> the Perl I<filehandle> (not filedescriptor) to watch for
74events. C<poll> must be a string that is either C<r> or C<w>, that creates
75a watcher waiting for "r"eadable or "w"ritable events. C<cb> teh callback
76to invoke everytime the filehandle becomes ready.
77
78Only one io watcher per C<fh> and C<poll> combination is allowed (i.e. on
79a socket you can have one r + one w, not any more (limitation comes from
80Tk - if you are sure you are not using Tk this limitation is gone).
81
82Filehandles will be kept alive, so as long as the watcher exists, the
83filehandle exists, too.
84
85Example:
86
87 # wait for readability of STDIN, then read a line and disable the watcher
88 my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
89 chomp (my $input = <STDIN>);
90 warn "read: $input\n";
91 undef $w;
92 });
93
94=head2 TIME WATCHERS
95
96You can create a time watcher by calling the C<< AnyEvent->timer >>
97method with the following mandatory arguments:
98
99C<after> after how many seconds (fractions are supported) should the timer
100activate. C<cb> the callback to invoke.
101
102The timer callback will be invoked at most once: if you want a repeating
103timer you have to create a new watcher (this is a limitation by both Tk
104and Glib).
105
106Example:
107
108 # fire an event after 7.7 seconds
109 my $w = AnyEvent->timer (after => 7.7, cb => sub {
110 warn "timeout\n";
111 });
112
113 # to cancel the timer:
114 undef $w
115
116=head2 CONDITION WATCHERS
117
118Condition watchers can be created by calling the C<< AnyEvent->condvar >>
119method without any arguments.
120
121A condition watcher watches for a condition - precisely that the C<<
122->broadcast >> method has been called.
123
124The watcher has only two methods:
62 125
63=over 4 126=over 4
64 127
128=item $cv->wait
129
130Wait (blocking if necessary) until the C<< ->broadcast >> method has been
131called on c<$cv>, while servicing other watchers normally.
132
133Not all event models support a blocking wait - some die in that case, so
134if you are using this from a module, never require a blocking wait, but
135let the caller decide wether the call will block or not (for example,
136by coupling condition variables with some kind of request results and
137supporting callbacks so the caller knows that getting the result will not
138block, while still suppporting blockign waits if the caller so desires).
139
140You can only wait once on a condition - additional calls will return
141immediately.
142
143=item $cv->broadcast
144
145Flag the condition as ready - a running C<< ->wait >> and all further
146calls to C<wait> will return after this method has been called. If nobody
147is waiting the broadcast will be remembered..
148
149Example:
150
151 # wait till the result is ready
152 my $result_ready = AnyEvent->condvar;
153
154 # do something such as adding a timer
155 # or socket watcher the calls $result_ready->broadcast
156 # when the "result" is ready.
157
158 $result_ready->wait;
159
160=back
161
162=head2 SIGNAL WATCHERS
163
164You can listen for signals using a signal watcher, C<signal> is the signal
165I<name> without any C<SIG> prefix. Multiple signals events can be clumped
166together into one callback invocation, and callback invocation might or
167might not be asynchronous.
168
169These watchers might use C<%SIG>, so programs overwriting those signals
170directly will likely not work correctly.
171
172Example: exit on SIGINT
173
174 my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });
175
176=head2 CHILD PROCESS WATCHERS
177
178You can also listen for the status of a child process specified by the
179C<pid> argument. The watcher will only trigger once. This works by
180installing a signal handler for C<SIGCHLD>.
181
182Example: wait for pid 1333
183
184 my $w = AnyEvent->child (pid => 1333, cb => sub { warn "exit status $?" });
185
186=head1 GLOBALS
187
188=over 4
189
190=item $AnyEvent::MODEL
191
192Contains C<undef> until the first watcher is being created. Then it
193contains the event model that is being used, which is the name of the
194Perl class implementing the model. This class is usually one of the
195C<AnyEvent::Impl:xxx> modules, but can be any other class in the case
196AnyEvent has been extended at runtime (e.g. in I<rxvt-unicode>).
197
198The known classes so far are:
199
200 EV::AnyEvent based on EV (an interface to libev, best choice)
201 AnyEvent::Impl::Coro based on Coro::Event, second best choice.
202 AnyEvent::Impl::Event based on Event, also second best choice :)
203 AnyEvent::Impl::Glib based on Glib, second-best choice.
204 AnyEvent::Impl::Tk based on Tk, very bad choice.
205 AnyEvent::Impl::Perl pure-perl implementation, inefficient.
206
207=item AnyEvent::detect
208
209Returns C<$AnyEvent::MODEL>, forcing autodetection of the event model if
210necessary. You should only call this function right before you would have
211created an AnyEvent watcher anyway, that is, very late at runtime.
212
213=back
214
215=head1 WHAT TO DO IN A MODULE
216
217As a module author, you should "use AnyEvent" and call AnyEvent methods
218freely, but you should not load a specific event module or rely on it.
219
220Be careful when you create watchers in the module body - Anyevent will
221decide which event module to use as soon as the first method is called, so
222by calling AnyEvent in your module body you force the user of your module
223to load the event module first.
224
225=head1 WHAT TO DO IN THE MAIN PROGRAM
226
227There will always be a single main program - the only place that should
228dictate which event model to use.
229
230If it doesn't care, it can just "use AnyEvent" and use it itself, or not
231do anything special and let AnyEvent decide which implementation to chose.
232
233If the main program relies on a specific event model (for example, in Gtk2
234programs you have to rely on either Glib or Glib::Event), you should load
235it before loading AnyEvent or any module that uses it, generally, as early
236as possible. The reason is that modules might create watchers when they
237are loaded, and AnyEvent will decide on the event model to use as soon as
238it creates watchers, and it might chose the wrong one unless you load the
239correct one yourself.
240
241You can chose to use a rather inefficient pure-perl implementation by
242loading the C<AnyEvent::Impl::Perl> module, but letting AnyEvent chose is
243generally better.
244
65=cut 245=cut
66 246
67package AnyEvent; 247package AnyEvent;
68 248
69no warnings; 249no warnings;
70use strict 'vars'; 250use strict;
251
71use Carp; 252use Carp;
72 253
73our $VERSION = '1.02'; 254our $VERSION = '2.55';
74our $MODEL; 255our $MODEL;
75 256
76our $AUTOLOAD; 257our $AUTOLOAD;
77our @ISA; 258our @ISA;
78 259
79our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1; 260our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1;
80 261
81our @REGISTRY; 262our @REGISTRY;
82 263
83my @models = ( 264my @models = (
84 [Coro::Event:: => AnyEvent::Impl::Coro::], 265 [Coro::Event:: => AnyEvent::Impl::Coro::],
266 [EV:: => EV::AnyEvent::],
85 [Event:: => AnyEvent::Impl::Event::], 267 [Event:: => AnyEvent::Impl::Event::],
86 [Glib:: => AnyEvent::Impl::Glib::], 268 [Glib:: => AnyEvent::Impl::Glib::],
87 [Tk:: => AnyEvent::Impl::Tk::], 269 [Tk:: => AnyEvent::Impl::Tk::],
270 [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl::],
88); 271);
89 272
90our %method = map +($_ => 1), qw(io timer condvar broadcast wait cancel DESTROY); 273our %method = map +($_ => 1), qw(io timer condvar broadcast wait signal one_event DESTROY);
91 274
92sub AUTOLOAD { 275sub detect() {
93 $AUTOLOAD =~ s/.*://;
94
95 $method{$AUTOLOAD}
96 or croak "$AUTOLOAD: not a valid method for AnyEvent objects";
97
98 unless ($MODEL) { 276 unless ($MODEL) {
277 no strict 'refs';
278
99 # check for already loaded models 279 # check for already loaded models
100 for (@REGISTRY, @models) { 280 for (@REGISTRY, @models) {
101 my ($package, $model) = @$_; 281 my ($package, $model) = @$_;
102 if (${"$package\::VERSION"} > 0) { 282 if (${"$package\::VERSION"} > 0) {
103 if (eval "require $model") { 283 if (eval "require $model") {
111 unless ($MODEL) { 291 unless ($MODEL) {
112 # try to load a model 292 # try to load a model
113 293
114 for (@REGISTRY, @models) { 294 for (@REGISTRY, @models) {
115 my ($package, $model) = @$_; 295 my ($package, $model) = @$_;
296 if (eval "require $package"
297 and ${"$package\::VERSION"} > 0
116 if (eval "require $model") { 298 and eval "require $model") {
117 $MODEL = $model; 299 $MODEL = $model;
118 warn "AnyEvent: autoprobed and loaded model '$model', using it.\n" if $verbose > 1; 300 warn "AnyEvent: autoprobed and loaded model '$model', using it.\n" if $verbose > 1;
119 last; 301 last;
120 } 302 }
121 } 303 }
122 304
123 $MODEL 305 $MODEL
124 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: Coro, Event, Glib or Tk."; 306 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: Event (or Coro+Event), Glib or Tk.";
125 } 307 }
308
309 unshift @ISA, $MODEL;
310 push @{"$MODEL\::ISA"}, "AnyEvent::Base";
126 } 311 }
127 312
128 @ISA = $MODEL; 313 $MODEL
314}
315
316sub AUTOLOAD {
317 (my $func = $AUTOLOAD) =~ s/.*://;
318
319 $method{$func}
320 or croak "$func: not a valid method for AnyEvent objects";
321
322 detect unless $MODEL;
129 323
130 my $class = shift; 324 my $class = shift;
131 $class->$AUTOLOAD (@_); 325 $class->$func (@_);
132} 326}
133 327
134=back 328package AnyEvent::Base;
329
330# default implementation for ->condvar, ->wait, ->broadcast
331
332sub condvar {
333 bless \my $flag, "AnyEvent::Base::CondVar"
334}
335
336sub AnyEvent::Base::CondVar::broadcast {
337 ${$_[0]}++;
338}
339
340sub AnyEvent::Base::CondVar::wait {
341 AnyEvent->one_event while !${$_[0]};
342}
343
344# default implementation for ->signal
345
346our %SIG_CB;
347
348sub signal {
349 my (undef, %arg) = @_;
350
351 my $signal = uc $arg{signal}
352 or Carp::croak "required option 'signal' is missing";
353
354 $SIG_CB{$signal}{$arg{cb} += 0} = $arg{cb};
355 $SIG{$signal} ||= sub {
356 $_->() for values %{ $SIG_CB{$signal} || {} };
357 };
358
359 bless [$signal, $arg{cb}], "AnyEvent::Base::Signal"
360}
361
362sub AnyEvent::Base::Signal::DESTROY {
363 my ($signal, $cb) = @{$_[0]};
364
365 delete $SIG_CB{$signal}{$cb};
366
367 $SIG{$signal} = 'DEFAULT' unless keys %{ $SIG_CB{$signal} };
368}
369
370# default implementation for ->child
371
372our %PID_CB;
373our $CHLD_W;
374our $PID_IDLE;
375our $WNOHANG;
376
377sub _child_wait {
378 while (0 < (my $pid = waitpid -1, $WNOHANG)) {
379 $_->() for values %{ $PID_CB{$pid} || {} }, %{ $PID_CB{0} || {} };
380 }
381
382 undef $PID_IDLE;
383}
384
385sub child {
386 my (undef, %arg) = @_;
387
388 my $pid = uc $arg{pid}
389 or Carp::croak "required option 'pid' is missing";
390
391 $PID_CB{$pid}{$arg{cb}} = $arg{cb};
392
393 unless ($WNOHANG) {
394 $WNOHANG = eval { require POSIX; &POSIX::WNOHANG } || 1;
395 }
396
397 unless ($CHLD_W) {
398 $CHLD_W = AnyEvent->signal (signal => 'CHLD', cb => \&_child_wait);
399 # child could be a zombie already
400 $PID_IDLE ||= AnyEvent->timer (after => 0, cb => \&_child_wait);
401 }
402
403 bless [$pid, $arg{cb}], "AnyEvent::Base::Child"
404}
405
406sub AnyEvent::Base::Child::DESTROY {
407 my ($pid, $cb) = @{$_[0]};
408
409 delete $PID_CB{$pid}{$cb};
410 delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} };
411
412 undef $CHLD_W unless keys %PID_CB;
413}
135 414
136=head1 SUPPLYING YOUR OWN EVENT MODEL INTERFACE 415=head1 SUPPLYING YOUR OWN EVENT MODEL INTERFACE
137 416
138If you need to support another event library which isn't directly 417If you need to support another event library which isn't directly
139supported by AnyEvent, you can supply your own interface to it by 418supported by AnyEvent, you can supply your own interface to it by
144 423
145Example: 424Example:
146 425
147 push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::]; 426 push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
148 427
149This tells AnyEvent to (literally) use the C<urxvt::anyevent::> module 428This tells AnyEvent to (literally) use the C<urxvt::anyevent::>
150when it finds the C<urxvt> module is loaded. When AnyEvent is loaded and 429package/class when it finds the C<urxvt> package/module is loaded. When
151requested to find a suitable event model, it will first check for the 430AnyEvent is loaded and asked to find a suitable event model, it will
152urxvt module. 431first check for the presence of urxvt.
153 432
433The class should provide implementations for all watcher types (see
434L<AnyEvent::Impl::Event> (source code), L<AnyEvent::Impl::Glib>
435(Source code) and so on for actual examples, use C<perldoc -m
436AnyEvent::Impl::Glib> to see the sources).
437
154The above isn't fictitious, the I<rxvt-unicode> (a.k.a. urxvt) uses 438The above isn't fictitious, the I<rxvt-unicode> (a.k.a. urxvt)
155the above line exactly. An interface isn't included in AnyEvent 439uses the above line as-is. An interface isn't included in AnyEvent
156because it doesn't make sense outside the embedded interpreter inside 440because it doesn't make sense outside the embedded interpreter inside
157I<rxvt-unicode>, and it is updated and maintained as part of the 441I<rxvt-unicode>, and it is updated and maintained as part of the
158I<rxvt-unicode> distribution. 442I<rxvt-unicode> distribution.
443
444I<rxvt-unicode> also cheats a bit by not providing blocking access to
445condition variables: code blocking while waiting for a condition will
446C<die>. This still works with most modules/usages, and blocking calls must
447not be in an interactive application, so it makes sense.
159 448
160=head1 ENVIRONMENT VARIABLES 449=head1 ENVIRONMENT VARIABLES
161 450
162The following environment variables are used by this module: 451The following environment variables are used by this module:
163 452

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines