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