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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines