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.1 by root, Wed Apr 27 01:26:44 2005 UTC vs.
Revision 1.20 by root, Mon Dec 11 01:16:09 2006 UTC

1=head1 NAME 1=head1 NAME
2 2
3AnyEvent - ??? 3AnyEvent - provide framework for multiple event loops
4
5Event, Coro, Glib, Tk, Perl - various supported event loops
4 6
5=head1 SYNOPSIS 7=head1 SYNOPSIS
6 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 wether 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
7=head1 DESCRIPTION 23=head1 DESCRIPTION
8 24
25L<AnyEvent> provides an identical interface to multiple event loops. This
26allows module authors to utilise an event loop without forcing module
27users to use the same event loop (as only a single event loop can coexist
28peacefully at any one time).
29
30The interface itself is vaguely similar but not identical to the Event
31module.
32
33On the first call of any method, the module tries to detect the currently
34loaded event loop by probing wether any of the following modules is
35loaded: L<Coro::Event>, L<Event>, L<Glib>, L<Tk>. The first one found is
36used. If none is found, the module tries to load these modules in the
37order given. The first one that could be successfully loaded will be
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:
125
9=over 4 126=over 4
10 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 callbakc 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 AnyEvent::Impl::Coro based on Coro::Event, best choise.
201 AnyEvent::Impl::Event based on Event, also best choice :)
202 AnyEvent::Impl::Glib based on Glib, second-best choice.
203 AnyEvent::Impl::Tk based on Tk, very bad choice.
204 AnyEvent::Impl::Perl pure-perl implementation, inefficient.
205
206=item AnyEvent::detect
207
208Returns C<$AnyEvent::MODEL>, forcing autodetection of the event model if
209necessary. You should only call this function right before you would have
210created an AnyEvent watcher anyway, that is, very late at runtime.
211
212=back
213
214=head1 WHAT TO DO IN A MODULE
215
216As a module author, you should "use AnyEvent" and call AnyEvent methods
217freely, but you should not load a specific event module or rely on it.
218
219Be careful when you create watchers in the module body - Anyevent will
220decide which event module to use as soon as the first method is called, so
221by calling AnyEvent in your module body you force the user of your module
222to load the event module first.
223
224=head1 WHAT TO DO IN THE MAIN PROGRAM
225
226There will always be a single main program - the only place that should
227dictate which event model to use.
228
229If it doesn't care, it can just "use AnyEvent" and use it itself, or not
230do anything special and let AnyEvent decide which implementation to chose.
231
232If the main program relies on a specific event model (for example, in Gtk2
233programs you have to rely on either Glib or Glib::Event), you should load
234it before loading AnyEvent or any module that uses it, generally, as early
235as possible. The reason is that modules might create watchers when they
236are loaded, and AnyEvent will decide on the event model to use as soon as
237it creates watchers, and it might chose the wrong one unless you load the
238correct one yourself.
239
240You can chose to use a rather inefficient pure-perl implementation by
241loading the C<AnyEvent::Impl::Perl> module, but letting AnyEvent chose is
242generally better.
243
11=cut 244=cut
12 245
13package AnyEvent; 246package AnyEvent;
14 247
248no warnings;
249use strict;
15use Carp; 250use Carp;
16 251
17$VERSION = 0.1; 252our $VERSION = '2.5';
253our $MODEL;
18 254
19no warnings; 255our $AUTOLOAD;
256our @ISA;
257
258our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1;
259
260our @REGISTRY;
20 261
21my @models = ( 262my @models = (
22 [Coro => Coro::Event::], 263 [Coro::Event:: => AnyEvent::Impl::Coro::],
23 [Event => Event::], 264 [Event:: => AnyEvent::Impl::Event::],
24 [Glib => Glib::], 265 [Glib:: => AnyEvent::Impl::Glib::],
25 [Tk => Tk::], 266 [Tk:: => AnyEvent::Impl::Tk::],
267 [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl::],
26); 268);
27 269
270our %method = map +($_ => 1), qw(io timer condvar broadcast wait signal one_event DESTROY);
271
272sub detect() {
273 unless ($MODEL) {
274 no strict 'refs';
275
276 # check for already loaded models
277 for (@REGISTRY, @models) {
278 my ($package, $model) = @$_;
279 if (${"$package\::VERSION"} > 0) {
280 if (eval "require $model") {
281 $MODEL = $model;
282 warn "AnyEvent: found model '$model', using it.\n" if $verbose > 1;
283 last;
284 }
285 }
286 }
287
288 unless ($MODEL) {
289 # try to load a model
290
291 for (@REGISTRY, @models) {
292 my ($package, $model) = @$_;
293 if (eval "require $model") {
294 $MODEL = $model;
295 warn "AnyEvent: autoprobed and loaded model '$model', using it.\n" if $verbose > 1;
296 last;
297 }
298 }
299
300 $MODEL
301 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: Event (or Coro+Event), Glib or Tk.";
302 }
303
304 unshift @ISA, $MODEL;
305 push @{"$MODEL\::ISA"}, "AnyEvent::Base";
306 }
307
308 $MODEL
309}
310
28sub AUTOLOAD { 311sub AUTOLOAD {
29 $AUTOLOAD =~ s/.*://; 312 (my $func = $AUTOLOAD) =~ s/.*://;
30 313
31 for (@models) { 314 $method{$func}
32 my ($model, $package) = @$_; 315 or croak "$func: not a valid method for AnyEvent objects";
33 if (defined ${"$package\::VERSION"}) { 316
34 $EVENT = "AnyEvent::Impl::$model"; 317 detect unless $MODEL;
35 eval "require $EVENT"; die if $@; 318
36 goto &{"$EVENT\::$AUTOLOAD"}; 319 my $class = shift;
37 } 320 $class->$func (@_);
321}
322
323package AnyEvent::Base;
324
325# default implementation for ->condvar, ->wait, ->broadcast
326
327sub condvar {
328 bless \my $flag, "AnyEvent::Base::CondVar"
329}
330
331sub AnyEvent::Base::CondVar::broadcast {
332 ${$_[0]}++;
333}
334
335sub AnyEvent::Base::CondVar::wait {
336 AnyEvent->one_event while !${$_[0]};
337}
338
339# default implementation for ->signal
340
341our %SIG_CB;
342
343sub signal {
344 my (undef, %arg) = @_;
345
346 my $signal = uc $arg{signal}
347 or Carp::croak "required option 'signal' is missing";
348
349 $SIG_CB{$signal}{$arg{cb}} = $arg{cb};
350 $SIG{$signal} ||= sub {
351 $_->() for values %{ $SIG_CB{$signal} || {} };
352 };
353
354 bless [$signal, $arg{cb}], "AnyEvent::Base::Signal"
355}
356
357sub AnyEvent::Base::Signal::DESTROY {
358 my ($signal, $cb) = @{$_[0]};
359
360 delete $SIG_CB{$signal}{$cb};
361
362 $SIG{$signal} = 'DEFAULT' unless keys %{ $SIG_CB{$signal} };
363}
364
365# default implementation for ->child
366
367our %PID_CB;
368our $CHLD_W;
369our $PID_IDLE;
370our $WNOHANG;
371
372sub _child_wait {
373 while (0 < (my $pid = waitpid -1, $WNOHANG)) {
374 $_->() for values %{ (delete $PID_CB{$pid}) || {} };
38 } 375 }
39 376
40 for (@models) { 377 undef $PID_IDLE;
41 my ($model, $package) = @$_; 378}
42 $EVENT = "AnyEvent::Impl::$model"; 379
43 if (eval "require $EVENT") { 380sub child {
44 goto &{"$EVENT\::$AUTOLOAD"}; 381 my (undef, %arg) = @_;
45 } 382
383 my $pid = uc $arg{pid}
384 or Carp::croak "required option 'pid' is missing";
385
386 $PID_CB{$pid}{$arg{cb}} = $arg{cb};
387
388 unless ($WNOHANG) {
389 $CHLD_W = AnyEvent->signal (signal => 'CHLD', cb => \&_child_wait);
390 $WNOHANG = eval { require POSIX; &POSIX::WNOHANG } || 1;
46 } 391 }
47 392
48 die "No event module selected for AnyEvent and autodetect failed. Install any of these: Coro, Event, Glib or Tk."; 393 # child could be a zombie already
49} 394 $PID_IDLE ||= AnyEvent->timer (after => 0, cb => \&_child_wait);
50 395
511; 396 bless [$pid, $arg{cb}], "AnyEvent::Base::Child"
397}
52 398
399sub AnyEvent::Base::Child::DESTROY {
400 my ($pid, $cb) = @{$_[0]};
401
402 delete $PID_CB{$pid}{$cb};
403 delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} };
404
405 undef $CHLD_W unless keys %PID_CB;
406}
407
408=head1 SUPPLYING YOUR OWN EVENT MODEL INTERFACE
409
410If you need to support another event library which isn't directly
411supported by AnyEvent, you can supply your own interface to it by
412pushing, before the first watcher gets created, the package name of
413the event module and the package name of the interface to use onto
414C<@AnyEvent::REGISTRY>. You can do that before and even without loading
415AnyEvent.
416
417Example:
418
419 push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
420
421This tells AnyEvent to (literally) use the C<urxvt::anyevent::>
422package/class when it finds the C<urxvt> package/module is loaded. When
423AnyEvent is loaded and asked to find a suitable event model, it will
424first check for the presence of urxvt.
425
426The class should provide implementations for all watcher types (see
427L<AnyEvent::Impl::Event> (source code), L<AnyEvent::Impl::Glib>
428(Source code) and so on for actual examples, use C<perldoc -m
429AnyEvent::Impl::Glib> to see the sources).
430
431The above isn't fictitious, the I<rxvt-unicode> (a.k.a. urxvt)
432uses the above line as-is. An interface isn't included in AnyEvent
433because it doesn't make sense outside the embedded interpreter inside
434I<rxvt-unicode>, and it is updated and maintained as part of the
435I<rxvt-unicode> distribution.
436
437I<rxvt-unicode> also cheats a bit by not providing blocking access to
438condition variables: code blocking while waiting for a condition will
439C<die>. This still works with most modules/usages, and blocking calls must
440not be in an interactive appliation, so it makes sense.
441
442=head1 ENVIRONMENT VARIABLES
443
444The following environment variables are used by this module:
445
446C<PERL_ANYEVENT_VERBOSE> when set to C<2> or higher, reports which event
447model gets used.
448
449=head1 EXAMPLE
450
451The following program uses an io watcher to read data from stdin, a timer
452to display a message once per second, and a condvar to exit the program
453when the user enters quit:
454
455 use AnyEvent;
456
457 my $cv = AnyEvent->condvar;
458
459 my $io_watcher = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
460 warn "io event <$_[0]>\n"; # will always output <r>
461 chomp (my $input = <STDIN>); # read a line
462 warn "read: $input\n"; # output what has been read
463 $cv->broadcast if $input =~ /^q/i; # quit program if /^q/i
464 });
465
466 my $time_watcher; # can only be used once
467
468 sub new_timer {
469 $timer = AnyEvent->timer (after => 1, cb => sub {
470 warn "timeout\n"; # print 'timeout' about every second
471 &new_timer; # and restart the time
472 });
473 }
474
475 new_timer; # create first timer
476
477 $cv->wait; # wait until user enters /^q/i
478
479=head1 REAL-WORLD EXAMPLE
480
481Consider the L<Net::FCP> module. It features (among others) the following
482API calls, which are to freenet what HTTP GET requests are to http:
483
484 my $data = $fcp->client_get ($url); # blocks
485
486 my $transaction = $fcp->txn_client_get ($url); # does not block
487 $transaction->cb ( sub { ... } ); # set optional result callback
488 my $data = $transaction->result; # possibly blocks
489
490The C<client_get> method works like C<LWP::Simple::get>: it requests the
491given URL and waits till the data has arrived. It is defined to be:
492
493 sub client_get { $_[0]->txn_client_get ($_[1])->result }
494
495And in fact is automatically generated. This is the blocking API of
496L<Net::FCP>, and it works as simple as in any other, similar, module.
497
498More complicated is C<txn_client_get>: It only creates a transaction
499(completion, result, ...) object and initiates the transaction.
500
501 my $txn = bless { }, Net::FCP::Txn::;
502
503It also creates a condition variable that is used to signal the completion
504of the request:
505
506 $txn->{finished} = AnyAvent->condvar;
507
508It then creates a socket in non-blocking mode.
509
510 socket $txn->{fh}, ...;
511 fcntl $txn->{fh}, F_SETFL, O_NONBLOCK;
512 connect $txn->{fh}, ...
513 and !$!{EWOULDBLOCK}
514 and !$!{EINPROGRESS}
515 and Carp::croak "unable to connect: $!\n";
516
517Then it creates a write-watcher which gets called whenever an error occurs
518or the connection succeeds:
519
520 $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w });
521
522And returns this transaction object. The C<fh_ready_w> callback gets
523called as soon as the event loop detects that the socket is ready for
524writing.
525
526The C<fh_ready_w> method makes the socket blocking again, writes the
527request data and replaces the watcher by a read watcher (waiting for reply
528data). The actual code is more complicated, but that doesn't matter for
529this example:
530
531 fcntl $txn->{fh}, F_SETFL, 0;
532 syswrite $txn->{fh}, $txn->{request}
533 or die "connection or write error";
534 $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r });
535
536Again, C<fh_ready_r> waits till all data has arrived, and then stores the
537result and signals any possible waiters that the request ahs finished:
538
539 sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf};
540
541 if (end-of-file or data complete) {
542 $txn->{result} = $txn->{buf};
543 $txn->{finished}->broadcast;
544 $txb->{cb}->($txn) of $txn->{cb}; # also call callback
545 }
546
547The C<result> method, finally, just waits for the finished signal (if the
548request was already finished, it doesn't wait, of course, and returns the
549data:
550
551 $txn->{finished}->wait;
552 return $txn->{result};
553
554The actual code goes further and collects all errors (C<die>s, exceptions)
555that occured during request processing. The C<result> method detects
556wether an exception as thrown (it is stored inside the $txn object)
557and just throws the exception, which means connection errors and other
558problems get reported tot he code that tries to use the result, not in a
559random callback.
560
561All of this enables the following usage styles:
562
5631. Blocking:
564
565 my $data = $fcp->client_get ($url);
566
5672. Blocking, but parallelizing:
568
569 my @datas = map $_->result,
570 map $fcp->txn_client_get ($_),
571 @urls;
572
573Both blocking examples work without the module user having to know
574anything about events.
575
5763a. Event-based in a main program, using any support Event module:
577
578 use Event;
579
580 $fcp->txn_client_get ($url)->cb (sub {
581 my $txn = shift;
582 my $data = $txn->result;
583 ...
584 });
585
586 Event::loop;
587
5883b. The module user could use AnyEvent, too:
589
590 use AnyEvent;
591
592 my $quit = AnyEvent->condvar;
593
594 $fcp->txn_client_get ($url)->cb (sub {
595 ...
596 $quit->broadcast;
597 });
598
599 $quit->wait;
600
601=head1 SEE ALSO
602
603Event modules: L<Coro::Event>, L<Coro>, L<Event>, L<Glib::Event>, L<Glib>.
604
605Implementations: L<AnyEvent::Impl::Coro>, L<AnyEvent::Impl::Event>, L<AnyEvent::Impl::Glib>, L<AnyEvent::Impl::Tk>.
606
607Nontrivial usage example: L<Net::FCP>.
608
609=head1
610
611=cut
612
6131
614

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines