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.1 by root, Wed Apr 27 01:26:44 2005 UTC vs.
Revision 1.17 by root, Fri Nov 24 14:40:13 2006 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines