ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent.pm
Revision: 1.41
Committed: Mon Apr 7 19:23:59 2008 UTC (16 years, 2 months ago) by root
Branch: MAIN
Changes since 1.40: +49 -1 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 =head1 NAME
2
3 AnyEvent - provide framework for multiple event loops
4
5 Event, Coro, Glib, Tk, Perl - 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 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
23 =head1 WHY YOU SHOULD USE THIS MODULE
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, and AnyEvent
35 helps hiding the differences.
36
37 The goal of AnyEvent is to offer module authors the ability to do event
38 programming (waiting for I/O or timer events) without subscribing to a
39 religion, a way of living, and most importantly: without forcing your
40 module users into the same thing by forcing them to use the same event
41 model you use.
42
43 For modules like POE or IO::Async (the latter of which is actually
44 named confusingly, as it does neither do I/O nor does it do anything
45 asynchronously...), using them in your module is like joining a
46 cult: After you joined, you are dependent on them and you cannot use
47 anything else, as it is simply incompatible to everything that isn't
48 itself.
49
50 AnyEvent + POE works fine. AnyEvent + Glib works fine. AnyEvent + Tk
51 works 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
53 those, every user of your module has to use it, too. If your module
54 uses AnyEvent, it works transparently with all event models it supports
55 (including stuff like POE and IO::Async).
56
57 In addition of being free of having to use I<the one and only true event
58 model>, AnyEvent also is free of bloat and policy: with POE or similar
59 modules, you get an enourmous amount of code and strict rules you have
60 to follow. AnyEvent, on the other hand, is lean and to the point by only
61 offering the functionality that is useful, in as thin as a wrapper as
62 technically possible.
63
64
65 =head1 DESCRIPTION
66
67 L<AnyEvent> provides an identical interface to multiple event loops. This
68 allows module authors to utilise an event loop without forcing module
69 users to use the same event loop (as only a single event loop can coexist
70 peacefully at any one time).
71
72 The interface itself is vaguely similar but not identical to the Event
73 module.
74
75 On the first call of any method, the module tries to detect the currently
76 loaded event loop by probing wether any of the following modules is
77 loaded: L<Coro::Event>, L<Event>, L<Glib>, L<Tk>. The first one found is
78 used. If none is found, the module tries to load these modules in the
79 order given. The first one that could be successfully loaded will be
80 used. If still none could be found, AnyEvent will fall back to a pure-perl
81 event loop, which is also not very efficient.
82
83 Because AnyEvent first checks for modules that are already loaded, loading
84 an Event model explicitly before first using AnyEvent will likely make
85 that model the default. For example:
86
87 use Tk;
88 use AnyEvent;
89
90 # .. AnyEvent will likely default to Tk
91
92 The pure-perl implementation of AnyEvent is called
93 C<AnyEvent::Impl::Perl>. Like other event modules you can load it
94 explicitly.
95
96 =head1 WATCHERS
97
98 AnyEvent has the central concept of a I<watcher>, which is an object that
99 stores relevant data for each kind of event you are waiting for, such as
100 the callback to call, the filehandle to watch, etc.
101
102 These watchers are normal Perl objects with normal Perl lifetime. After
103 creating a watcher it will immediately "watch" for events and invoke
104 the callback. To disable the watcher you have to destroy it (e.g. by
105 setting the variable that stores it to C<undef> or otherwise deleting all
106 references to it).
107
108 All watchers are created by calling a method on the C<AnyEvent> class.
109
110 =head2 IO WATCHERS
111
112 You can create I/O watcher by calling the C<< AnyEvent->io >> method with
113 the following mandatory arguments:
114
115 C<fh> the Perl I<filehandle> (not filedescriptor) to watch for
116 events. C<poll> must be a string that is either C<r> or C<w>, that creates
117 a watcher waiting for "r"eadable or "w"ritable events. C<cb> the callback
118 to invoke everytime the filehandle becomes ready.
119
120 Only one io watcher per C<fh> and C<poll> combination is allowed (i.e. on
121 a socket you can have one r + one w, not any more (limitation comes from
122 Tk - if you are sure you are not using Tk this limitation is gone).
123
124 Filehandles will be kept alive, so as long as the watcher exists, the
125 filehandle exists, too.
126
127 Example:
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
138 You can create a time watcher by calling the C<< AnyEvent->timer >>
139 method with the following mandatory arguments:
140
141 C<after> after how many seconds (fractions are supported) should the timer
142 activate. C<cb> the callback to invoke.
143
144 The timer callback will be invoked at most once: if you want a repeating
145 timer you have to create a new watcher (this is a limitation by both Tk
146 and Glib).
147
148 Example:
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
160 Condition watchers can be created by calling the C<< AnyEvent->condvar >>
161 method without any arguments.
162
163 A condition watcher watches for a condition - precisely that the C<<
164 ->broadcast >> method has been called.
165
166 Note that condition watchers recurse into the event loop - if you have
167 two watchers that call C<< ->wait >> in a round-robbin fashion, you
168 lose. Therefore, condition watchers are good to export to your caller, but
169 you should avoid making a blocking wait, at least in callbacks, as this
170 usually asks for trouble.
171
172 The watcher has only two methods:
173
174 =over 4
175
176 =item $cv->wait
177
178 Wait (blocking if necessary) until the C<< ->broadcast >> method has been
179 called on c<$cv>, while servicing other watchers normally.
180
181 Not all event models support a blocking wait - some die in that case, so
182 if you are using this from a module, never require a blocking wait, but
183 let the caller decide wether the call will block or not (for example,
184 by coupling condition variables with some kind of request results and
185 supporting callbacks so the caller knows that getting the result will not
186 block, while still suppporting blockign waits if the caller so desires).
187
188 You can only wait once on a condition - additional calls will return
189 immediately.
190
191 =item $cv->broadcast
192
193 Flag the condition as ready - a running C<< ->wait >> and all further
194 calls to C<wait> will return after this method has been called. If nobody
195 is waiting the broadcast will be remembered..
196
197 Example:
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
212 You can listen for signals using a signal watcher, C<signal> is the signal
213 I<name> without any C<SIG> prefix. Multiple signals events can be clumped
214 together into one callback invocation, and callback invocation might or
215 might not be asynchronous.
216
217 These watchers might use C<%SIG>, so programs overwriting those signals
218 directly will likely not work correctly.
219
220 Example: exit on SIGINT
221
222 my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });
223
224 =head2 CHILD PROCESS WATCHERS
225
226 You can also listen for the status of a child process specified by the
227 C<pid> argument (or any child if the pid argument is 0). The watcher will
228 trigger as often as status change for the child are received. This works
229 by installing a signal handler for C<SIGCHLD>. The callback will be called with
230 the pid and exit status (as returned by waitpid).
231
232 Example: 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
242 Contains C<undef> until the first watcher is being created. Then it
243 contains the event model that is being used, which is the name of the
244 Perl class implementing the model. This class is usually one of the
245 C<AnyEvent::Impl:xxx> modules, but can be any other class in the case
246 AnyEvent has been extended at runtime (e.g. in I<rxvt-unicode>).
247
248 The 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
260 Returns C<$AnyEvent::MODEL>, forcing autodetection of the event model if
261 necessary. You should only call this function right before you would have
262 created an AnyEvent watcher anyway, that is, very late at runtime.
263
264 =back
265
266 =head1 WHAT TO DO IN A MODULE
267
268 As a module author, you should "use AnyEvent" and call AnyEvent methods
269 freely, but you should not load a specific event module or rely on it.
270
271 Be careful when you create watchers in the module body - Anyevent will
272 decide which event module to use as soon as the first method is called, so
273 by calling AnyEvent in your module body you force the user of your module
274 to load the event module first.
275
276 =head1 WHAT TO DO IN THE MAIN PROGRAM
277
278 There will always be a single main program - the only place that should
279 dictate which event model to use.
280
281 If it doesn't care, it can just "use AnyEvent" and use it itself, or not
282 do anything special and let AnyEvent decide which implementation to chose.
283
284 If the main program relies on a specific event model (for example, in Gtk2
285 programs you have to rely on either Glib or Glib::Event), you should load
286 it before loading AnyEvent or any module that uses it, generally, as early
287 as possible. The reason is that modules might create watchers when they
288 are loaded, and AnyEvent will decide on the event model to use as soon as
289 it creates watchers, and it might chose the wrong one unless you load the
290 correct one yourself.
291
292 You can chose to use a rather inefficient pure-perl implementation by
293 loading the C<AnyEvent::Impl::Perl> module, but letting AnyEvent chose is
294 generally better.
295
296 =cut
297
298 package AnyEvent;
299
300 no warnings;
301 use strict;
302
303 use Carp;
304
305 our $VERSION = '3.0';
306 our $MODEL;
307
308 our $AUTOLOAD;
309 our @ISA;
310
311 our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1;
312
313 our @REGISTRY;
314
315 my @models = (
316 [Coro::EV:: => AnyEvent::Impl::CoroEV::],
317 [EV:: => AnyEvent::Impl::EV::],
318 [Coro::Event:: => AnyEvent::Impl::CoroEvent::],
319 [Event:: => AnyEvent::Impl::Event::],
320 [Glib:: => AnyEvent::Impl::Glib::],
321 [Tk:: => AnyEvent::Impl::Tk::],
322 [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl::],
323 );
324
325 our %method = map +($_ => 1), qw(io timer condvar broadcast wait signal one_event DESTROY);
326
327 sub detect() {
328 unless ($MODEL) {
329 no strict 'refs';
330
331 # check for already loaded models
332 for (@REGISTRY, @models) {
333 my ($package, $model) = @$_;
334 if (${"$package\::VERSION"} > 0) {
335 if (eval "require $model") {
336 $MODEL = $model;
337 warn "AnyEvent: found model '$model', using it.\n" if $verbose > 1;
338 last;
339 }
340 }
341 }
342
343 unless ($MODEL) {
344 # try to load a model
345
346 for (@REGISTRY, @models) {
347 my ($package, $model) = @$_;
348 if (eval "require $package"
349 and ${"$package\::VERSION"} > 0
350 and eval "require $model") {
351 $MODEL = $model;
352 warn "AnyEvent: autoprobed and loaded model '$model', using it.\n" if $verbose > 1;
353 last;
354 }
355 }
356
357 $MODEL
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.";
359 }
360
361 unshift @ISA, $MODEL;
362 push @{"$MODEL\::ISA"}, "AnyEvent::Base";
363 }
364
365 $MODEL
366 }
367
368 sub 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;
375
376 my $class = shift;
377 $class->$func (@_);
378 }
379
380 package AnyEvent::Base;
381
382 # default implementation for ->condvar, ->wait, ->broadcast
383
384 sub condvar {
385 bless \my $flag, "AnyEvent::Base::CondVar"
386 }
387
388 sub AnyEvent::Base::CondVar::broadcast {
389 ${$_[0]}++;
390 }
391
392 sub AnyEvent::Base::CondVar::wait {
393 AnyEvent->one_event while !${$_[0]};
394 }
395
396 # default implementation for ->signal
397
398 our %SIG_CB;
399
400 sub 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
414 sub 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
424 our %PID_CB;
425 our $CHLD_W;
426 our $CHLD_DELAY_W;
427 our $PID_IDLE;
428 our $WNOHANG;
429
430 sub _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
439 sub _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
447 sub 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
468 sub 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
479 If you need to support another event library which isn't directly
480 supported by AnyEvent, you can supply your own interface to it by
481 pushing, before the first watcher gets created, the package name of
482 the event module and the package name of the interface to use onto
483 C<@AnyEvent::REGISTRY>. You can do that before and even without loading
484 AnyEvent.
485
486 Example:
487
488 push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
489
490 This tells AnyEvent to (literally) use the C<urxvt::anyevent::>
491 package/class when it finds the C<urxvt> package/module is loaded. When
492 AnyEvent is loaded and asked to find a suitable event model, it will
493 first check for the presence of urxvt.
494
495 The class should provide implementations for all watcher types (see
496 L<AnyEvent::Impl::Event> (source code), L<AnyEvent::Impl::Glib>
497 (Source code) and so on for actual examples, use C<perldoc -m
498 AnyEvent::Impl::Glib> to see the sources).
499
500 The above isn't fictitious, the I<rxvt-unicode> (a.k.a. urxvt)
501 uses the above line as-is. An interface isn't included in AnyEvent
502 because it doesn't make sense outside the embedded interpreter inside
503 I<rxvt-unicode>, and it is updated and maintained as part of the
504 I<rxvt-unicode> distribution.
505
506 I<rxvt-unicode> also cheats a bit by not providing blocking access to
507 condition variables: code blocking while waiting for a condition will
508 C<die>. This still works with most modules/usages, and blocking calls must
509 not be in an interactive application, so it makes sense.
510
511 =head1 ENVIRONMENT VARIABLES
512
513 The following environment variables are used by this module:
514
515 C<PERL_ANYEVENT_VERBOSE> when set to C<2> or higher, reports which event
516 model gets used.
517
518 =head1 EXAMPLE
519
520 The following program uses an io watcher to read data from stdin, a timer
521 to display a message once per second, and a condvar to exit the program
522 when the user enters quit:
523
524 use AnyEvent;
525
526 my $cv = AnyEvent->condvar;
527
528 my $io_watcher = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
529 warn "io event <$_[0]>\n"; # will always output <r>
530 chomp (my $input = <STDIN>); # read a line
531 warn "read: $input\n"; # output what has been read
532 $cv->broadcast if $input =~ /^q/i; # quit program if /^q/i
533 });
534
535 my $time_watcher; # can only be used once
536
537 sub new_timer {
538 $timer = AnyEvent->timer (after => 1, cb => sub {
539 warn "timeout\n"; # print 'timeout' about every second
540 &new_timer; # and restart the time
541 });
542 }
543
544 new_timer; # create first timer
545
546 $cv->wait; # wait until user enters /^q/i
547
548 =head1 REAL-WORLD EXAMPLE
549
550 Consider the L<Net::FCP> module. It features (among others) the following
551 API calls, which are to freenet what HTTP GET requests are to http:
552
553 my $data = $fcp->client_get ($url); # blocks
554
555 my $transaction = $fcp->txn_client_get ($url); # does not block
556 $transaction->cb ( sub { ... } ); # set optional result callback
557 my $data = $transaction->result; # possibly blocks
558
559 The C<client_get> method works like C<LWP::Simple::get>: it requests the
560 given URL and waits till the data has arrived. It is defined to be:
561
562 sub client_get { $_[0]->txn_client_get ($_[1])->result }
563
564 And in fact is automatically generated. This is the blocking API of
565 L<Net::FCP>, and it works as simple as in any other, similar, module.
566
567 More complicated is C<txn_client_get>: It only creates a transaction
568 (completion, result, ...) object and initiates the transaction.
569
570 my $txn = bless { }, Net::FCP::Txn::;
571
572 It also creates a condition variable that is used to signal the completion
573 of the request:
574
575 $txn->{finished} = AnyAvent->condvar;
576
577 It then creates a socket in non-blocking mode.
578
579 socket $txn->{fh}, ...;
580 fcntl $txn->{fh}, F_SETFL, O_NONBLOCK;
581 connect $txn->{fh}, ...
582 and !$!{EWOULDBLOCK}
583 and !$!{EINPROGRESS}
584 and Carp::croak "unable to connect: $!\n";
585
586 Then it creates a write-watcher which gets called whenever an error occurs
587 or the connection succeeds:
588
589 $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w });
590
591 And returns this transaction object. The C<fh_ready_w> callback gets
592 called as soon as the event loop detects that the socket is ready for
593 writing.
594
595 The C<fh_ready_w> method makes the socket blocking again, writes the
596 request data and replaces the watcher by a read watcher (waiting for reply
597 data). The actual code is more complicated, but that doesn't matter for
598 this example:
599
600 fcntl $txn->{fh}, F_SETFL, 0;
601 syswrite $txn->{fh}, $txn->{request}
602 or die "connection or write error";
603 $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r });
604
605 Again, C<fh_ready_r> waits till all data has arrived, and then stores the
606 result and signals any possible waiters that the request ahs finished:
607
608 sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf};
609
610 if (end-of-file or data complete) {
611 $txn->{result} = $txn->{buf};
612 $txn->{finished}->broadcast;
613 $txb->{cb}->($txn) of $txn->{cb}; # also call callback
614 }
615
616 The C<result> method, finally, just waits for the finished signal (if the
617 request was already finished, it doesn't wait, of course, and returns the
618 data:
619
620 $txn->{finished}->wait;
621 return $txn->{result};
622
623 The actual code goes further and collects all errors (C<die>s, exceptions)
624 that occured during request processing. The C<result> method detects
625 wether an exception as thrown (it is stored inside the $txn object)
626 and just throws the exception, which means connection errors and other
627 problems get reported tot he code that tries to use the result, not in a
628 random callback.
629
630 All of this enables the following usage styles:
631
632 1. Blocking:
633
634 my $data = $fcp->client_get ($url);
635
636 2. Blocking, but parallelizing:
637
638 my @datas = map $_->result,
639 map $fcp->txn_client_get ($_),
640 @urls;
641
642 Both blocking examples work without the module user having to know
643 anything about events.
644
645 3a. Event-based in a main program, using any support Event module:
646
647 use Event;
648
649 $fcp->txn_client_get ($url)->cb (sub {
650 my $txn = shift;
651 my $data = $txn->result;
652 ...
653 });
654
655 Event::loop;
656
657 3b. The module user could use AnyEvent, too:
658
659 use AnyEvent;
660
661 my $quit = AnyEvent->condvar;
662
663 $fcp->txn_client_get ($url)->cb (sub {
664 ...
665 $quit->broadcast;
666 });
667
668 $quit->wait;
669
670 =head1 SEE ALSO
671
672 Event modules: L<Coro::Event>, L<Coro>, L<Event>, L<Glib::Event>, L<Glib>.
673
674 Implementations: L<AnyEvent::Impl::Coro>, L<AnyEvent::Impl::Event>, L<AnyEvent::Impl::Glib>, L<AnyEvent::Impl::Tk>.
675
676 Nontrivial usage example: L<Net::FCP>.
677
678 =head1
679
680 =cut
681
682 1
683