ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent.pm
Revision: 1.14
Committed: Mon Oct 30 20:52:24 2006 UTC (17 years, 8 months ago) by root
Branch: MAIN
Changes since 1.13: +161 -35 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3 root 1.2 AnyEvent - provide framework for multiple event loops
4    
5 root 1.14 Event, Coro, Glib, Tk, Perl - various supported event loops
6 root 1.1
7     =head1 SYNOPSIS
8    
9 root 1.7 use AnyEvent;
10 root 1.2
11 root 1.14 my $w = AnyEvent->io (fh => $fh, poll => "r|w", cb => sub {
12 root 1.2 ...
13     });
14 root 1.5
15     my $w = AnyEvent->timer (after => $seconds, cb => sub {
16 root 1.2 ...
17     });
18    
19 root 1.14 my $w = AnyEvent->condvar; # stores wether a condition was flagged
20     $w->wait; # enters "main loop" till $condvar gets ->broadcast
21 root 1.5 $w->broadcast; # wake up current and all future wait's
22    
23 root 1.1 =head1 DESCRIPTION
24    
25 root 1.2 L<AnyEvent> provides an identical interface to multiple event loops. This
26 root 1.13 allows module authors to utilise an event loop without forcing module
27 root 1.2 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 root 1.14 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 TIMER WATCHERS
95    
96     You can create a timer 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 root 1.2
126 root 1.1 =over 4
127    
128 root 1.14 =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     =head1 WHAT TO DO IN A MODULE
163    
164     As a module author, you should "use AnyEvent" and call AnyEvent methods
165     freely, but you should not load a specific event module or rely on it.
166    
167     Be careful when you create watchers in the module body - Anyevent will
168     decide which event module to use as soon as the first method is called, so
169     by calling AnyEvent in your module body you force the user of your module
170     to load the event module first.
171    
172     =head1 WHAT TO DO IN THE MAIN PROGRAM
173    
174     There will always be a single main program - the only place that should
175     dictate which event model to use.
176    
177     If it doesn't care, it can just "use AnyEvent" and use it itself, or not
178     do anything special and let AnyEvent decide which implementation to chose.
179    
180     If the main program relies on a specific event model (for example, in Gtk2
181     programs you have to rely on either Glib or Glib::Event), you should load
182     it before loading AnyEvent or any module that uses it, generally, as early
183     as possible. The reason is that modules might create watchers when they
184     are loaded, and AnyEvent will decide on the event model to use as soon as
185     it creates watchers, and it might chose the wrong one unless you load the
186     correct one yourself.
187    
188     You can chose to use a rather inefficient pure-perl implementation by
189     loading the C<AnyEvent::Impl::Perl> module, but letting AnyEvent chose is
190     generally better.
191    
192 root 1.1 =cut
193    
194     package AnyEvent;
195    
196 root 1.2 no warnings;
197     use strict 'vars';
198 root 1.1 use Carp;
199    
200 root 1.10 our $VERSION = '1.02';
201 root 1.2 our $MODEL;
202 root 1.1
203 root 1.2 our $AUTOLOAD;
204     our @ISA;
205 root 1.1
206 root 1.7 our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1;
207    
208 root 1.8 our @REGISTRY;
209    
210 root 1.1 my @models = (
211 root 1.14 [Coro::Event:: => AnyEvent::Impl::Coro::],
212     [Event:: => AnyEvent::Impl::Event::],
213     [Glib:: => AnyEvent::Impl::Glib::],
214     [Tk:: => AnyEvent::Impl::Tk::],
215     [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl::],
216 root 1.1 );
217    
218 root 1.14 our %method = map +($_ => 1), qw(io timer condvar broadcast wait DESTROY);
219 root 1.3
220 root 1.1 sub AUTOLOAD {
221     $AUTOLOAD =~ s/.*://;
222    
223 root 1.3 $method{$AUTOLOAD}
224     or croak "$AUTOLOAD: not a valid method for AnyEvent objects";
225    
226 root 1.2 unless ($MODEL) {
227     # check for already loaded models
228 root 1.8 for (@REGISTRY, @models) {
229     my ($package, $model) = @$_;
230 root 1.7 if (${"$package\::VERSION"} > 0) {
231 root 1.8 if (eval "require $model") {
232     $MODEL = $model;
233     warn "AnyEvent: found model '$model', using it.\n" if $verbose > 1;
234     last;
235     }
236 root 1.2 }
237 root 1.1 }
238    
239 root 1.2 unless ($MODEL) {
240     # try to load a model
241    
242 root 1.8 for (@REGISTRY, @models) {
243     my ($package, $model) = @$_;
244     if (eval "require $model") {
245     $MODEL = $model;
246     warn "AnyEvent: autoprobed and loaded model '$model', using it.\n" if $verbose > 1;
247     last;
248     }
249 root 1.2 }
250    
251     $MODEL
252     or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: Coro, Event, Glib or Tk.";
253 root 1.1 }
254     }
255    
256 root 1.2 @ISA = $MODEL;
257    
258     my $class = shift;
259     $class->$AUTOLOAD (@_);
260 root 1.1 }
261    
262 root 1.8 =head1 SUPPLYING YOUR OWN EVENT MODEL INTERFACE
263    
264     If you need to support another event library which isn't directly
265     supported by AnyEvent, you can supply your own interface to it by
266 root 1.11 pushing, before the first watcher gets created, the package name of
267 root 1.8 the event module and the package name of the interface to use onto
268     C<@AnyEvent::REGISTRY>. You can do that before and even without loading
269     AnyEvent.
270    
271     Example:
272    
273     push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
274    
275 root 1.12 This tells AnyEvent to (literally) use the C<urxvt::anyevent::>
276     package/class when it finds the C<urxvt> package/module is loaded. When
277     AnyEvent is loaded and asked to find a suitable event model, it will
278     first check for the presence of urxvt.
279    
280     The class should prove implementations for all watcher types (see
281     L<AnyEvent::Impl::Event> (source code), L<AnyEvent::Impl::Glib>
282     (Source code) and so on for actual examples, use C<perldoc -m
283     AnyEvent::Impl::Glib> to see the sources).
284 root 1.8
285 root 1.12 The above isn't fictitious, the I<rxvt-unicode> (a.k.a. urxvt)
286     uses the above line as-is. An interface isn't included in AnyEvent
287 root 1.8 because it doesn't make sense outside the embedded interpreter inside
288     I<rxvt-unicode>, and it is updated and maintained as part of the
289     I<rxvt-unicode> distribution.
290    
291 root 1.12 I<rxvt-unicode> also cheats a bit by not providing blocking access to
292     condition variables: code blocking while waiting for a condition will
293     C<die>. This still works with most modules/usages, and blocking calls must
294     not be in an interactive appliation, so it makes sense.
295    
296 root 1.7 =head1 ENVIRONMENT VARIABLES
297    
298     The following environment variables are used by this module:
299    
300     C<PERL_ANYEVENT_VERBOSE> when set to C<2> or higher, reports which event
301     model gets used.
302    
303 root 1.2 =head1 EXAMPLE
304    
305     The following program uses an io watcher to read data from stdin, a timer
306     to display a message once per second, and a condvar to exit the program
307     when the user enters quit:
308    
309     use AnyEvent;
310    
311     my $cv = AnyEvent->condvar;
312    
313     my $io_watcher = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
314     warn "io event <$_[0]>\n"; # will always output <r>
315     chomp (my $input = <STDIN>); # read a line
316     warn "read: $input\n"; # output what has been read
317     $cv->broadcast if $input =~ /^q/i; # quit program if /^q/i
318     });
319    
320     my $time_watcher; # can only be used once
321    
322     sub new_timer {
323     $timer = AnyEvent->timer (after => 1, cb => sub {
324     warn "timeout\n"; # print 'timeout' about every second
325     &new_timer; # and restart the time
326     });
327     }
328    
329     new_timer; # create first timer
330    
331     $cv->wait; # wait until user enters /^q/i
332    
333 root 1.5 =head1 REAL-WORLD EXAMPLE
334    
335     Consider the L<Net::FCP> module. It features (among others) the following
336     API calls, which are to freenet what HTTP GET requests are to http:
337    
338     my $data = $fcp->client_get ($url); # blocks
339    
340     my $transaction = $fcp->txn_client_get ($url); # does not block
341     $transaction->cb ( sub { ... } ); # set optional result callback
342     my $data = $transaction->result; # possibly blocks
343    
344     The C<client_get> method works like C<LWP::Simple::get>: it requests the
345     given URL and waits till the data has arrived. It is defined to be:
346    
347     sub client_get { $_[0]->txn_client_get ($_[1])->result }
348    
349     And in fact is automatically generated. This is the blocking API of
350     L<Net::FCP>, and it works as simple as in any other, similar, module.
351    
352     More complicated is C<txn_client_get>: It only creates a transaction
353     (completion, result, ...) object and initiates the transaction.
354    
355     my $txn = bless { }, Net::FCP::Txn::;
356    
357     It also creates a condition variable that is used to signal the completion
358     of the request:
359    
360     $txn->{finished} = AnyAvent->condvar;
361    
362     It then creates a socket in non-blocking mode.
363    
364     socket $txn->{fh}, ...;
365     fcntl $txn->{fh}, F_SETFL, O_NONBLOCK;
366     connect $txn->{fh}, ...
367     and !$!{EWOULDBLOCK}
368     and !$!{EINPROGRESS}
369     and Carp::croak "unable to connect: $!\n";
370    
371 root 1.6 Then it creates a write-watcher which gets called whenever an error occurs
372 root 1.5 or the connection succeeds:
373    
374     $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w });
375    
376     And returns this transaction object. The C<fh_ready_w> callback gets
377     called as soon as the event loop detects that the socket is ready for
378     writing.
379    
380     The C<fh_ready_w> method makes the socket blocking again, writes the
381     request data and replaces the watcher by a read watcher (waiting for reply
382     data). The actual code is more complicated, but that doesn't matter for
383     this example:
384    
385     fcntl $txn->{fh}, F_SETFL, 0;
386     syswrite $txn->{fh}, $txn->{request}
387     or die "connection or write error";
388     $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r });
389    
390     Again, C<fh_ready_r> waits till all data has arrived, and then stores the
391     result and signals any possible waiters that the request ahs finished:
392    
393     sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf};
394    
395     if (end-of-file or data complete) {
396     $txn->{result} = $txn->{buf};
397     $txn->{finished}->broadcast;
398 root 1.6 $txb->{cb}->($txn) of $txn->{cb}; # also call callback
399 root 1.5 }
400    
401     The C<result> method, finally, just waits for the finished signal (if the
402     request was already finished, it doesn't wait, of course, and returns the
403     data:
404    
405     $txn->{finished}->wait;
406 root 1.6 return $txn->{result};
407 root 1.5
408     The actual code goes further and collects all errors (C<die>s, exceptions)
409     that occured during request processing. The C<result> method detects
410     wether an exception as thrown (it is stored inside the $txn object)
411     and just throws the exception, which means connection errors and other
412     problems get reported tot he code that tries to use the result, not in a
413     random callback.
414    
415     All of this enables the following usage styles:
416    
417     1. Blocking:
418    
419     my $data = $fcp->client_get ($url);
420    
421     2. Blocking, but parallelizing:
422    
423     my @datas = map $_->result,
424     map $fcp->txn_client_get ($_),
425     @urls;
426    
427     Both blocking examples work without the module user having to know
428     anything about events.
429    
430     3a. Event-based in a main program, using any support Event module:
431    
432     use Event;
433    
434     $fcp->txn_client_get ($url)->cb (sub {
435     my $txn = shift;
436     my $data = $txn->result;
437     ...
438     });
439    
440     Event::loop;
441    
442     3b. The module user could use AnyEvent, too:
443    
444     use AnyEvent;
445    
446     my $quit = AnyEvent->condvar;
447    
448     $fcp->txn_client_get ($url)->cb (sub {
449     ...
450     $quit->broadcast;
451     });
452    
453     $quit->wait;
454    
455 root 1.2 =head1 SEE ALSO
456    
457 root 1.5 Event modules: L<Coro::Event>, L<Coro>, L<Event>, L<Glib::Event>, L<Glib>.
458    
459     Implementations: L<AnyEvent::Impl::Coro>, L<AnyEvent::Impl::Event>, L<AnyEvent::Impl::Glib>, L<AnyEvent::Impl::Tk>.
460    
461     Nontrivial usage example: L<Net::FCP>.
462 root 1.2
463     =head1
464    
465     =cut
466    
467     1
468 root 1.1