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