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.4 by root, Thu Dec 1 22:04:50 2005 UTC vs.
Revision 1.12 by root, Thu Jul 20 01:39:40 2006 UTC

4 4
5Event, Coro, Glib, Tk - various supported event loops 5Event, Coro, Glib, Tk - 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 => ..., poll => "[rw]+", cb => sub {
12 my ($poll_got) = @_; 12 my ($poll_got) = @_;
13 ... 13 ...
14 }); 14 });
15
16* only one io watcher per $fh and $poll type is allowed (i.e. on a socket
17you can have one r + one w or one rw watcher, not any more (limitation by
18Tk).
19
20* the C<$poll_got> passed to the handler needs to be checked by looking
21for single characters (e.g. with a regex), as it can contain more event
22types than were requested (e.g. a 'w' watcher might generate 'rw' events,
23limitation by Glib).
24
25* AnyEvent will keep filehandles alive, so as long as the watcher exists,
26the filehandle exists.
27
15 my $w = AnyEvent->io (after => $seconds, cb => sub { 28 my $w = AnyEvent->timer (after => $seconds, cb => sub {
16 ... 29 ...
17 }); 30 });
18 31
19 # watchers get canceled whenever $w is destroyed 32* io and time watchers get canceled whenever $w is destroyed, so keep a copy
20 # only one watcher per $fh and $poll type is allowed 33
21 # (i.e. on a socket you cna have one r + one w or one rw 34* timers can only be used once and must be recreated for repeated
22 # watcher, not any more. 35operation (limitation by Glib and Tk).
23 # timers can only be used once
24 36
25 my $w = AnyEvent->condvar; # kind of main loop replacement 37 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 38 $w->wait; # enters main loop till $condvar gets ->broadcast
28 $w->broadcast; # wake up waiting and future wait's 39 $w->broadcast; # wake up current and all future wait's
40
41* condvars are used to give blocking behaviour when neccessary. Create
42a condvar for any "request" or "event" your module might create, C<<
43->broadcast >> it when the event happens and provide a function that calls
44C<< ->wait >> for it. See the examples below.
29 45
30=head1 DESCRIPTION 46=head1 DESCRIPTION
31 47
32L<AnyEvent> provides an identical interface to multiple event loops. This 48L<AnyEvent> provides an identical interface to multiple event loops. This
33allows module authors to utilizy an event loop without forcing module 49allows module authors to utilizy an event loop without forcing module
52 68
53no warnings; 69no warnings;
54use strict 'vars'; 70use strict 'vars';
55use Carp; 71use Carp;
56 72
57our $VERSION = 0.2; 73our $VERSION = '1.02';
58our $MODEL; 74our $MODEL;
59 75
60our $AUTOLOAD; 76our $AUTOLOAD;
61our @ISA; 77our @ISA;
62 78
79our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1;
80
81our @REGISTRY;
82
63my @models = ( 83my @models = (
64 [Coro => Coro::Event::], 84 [Coro::Event:: => AnyEvent::Impl::Coro::],
65 [Event => Event::], 85 [Event:: => AnyEvent::Impl::Event::],
66 [Glib => Glib::], 86 [Glib:: => AnyEvent::Impl::Glib::],
67 [Tk => Tk::], 87 [Tk:: => AnyEvent::Impl::Tk::],
68); 88);
69 89
70our %method = map +($_ => 1), qw(io timer condvar broadcast wait cancel DESTROY); 90our %method = map +($_ => 1), qw(io timer condvar broadcast wait cancel DESTROY);
71 91
72sub AUTOLOAD { 92sub AUTOLOAD {
75 $method{$AUTOLOAD} 95 $method{$AUTOLOAD}
76 or croak "$AUTOLOAD: not a valid method for AnyEvent objects"; 96 or croak "$AUTOLOAD: not a valid method for AnyEvent objects";
77 97
78 unless ($MODEL) { 98 unless ($MODEL) {
79 # check for already loaded models 99 # check for already loaded models
80 for (@models) { 100 for (@REGISTRY, @models) {
81 my ($model, $package) = @$_; 101 my ($package, $model) = @$_;
82 if (scalar keys %{ *{"$package\::"} }) { 102 if (${"$package\::VERSION"} > 0) {
83 eval "require AnyEvent::Impl::$model"; 103 if (eval "require $model") {
84 last if $MODEL; 104 $MODEL = $model;
105 warn "AnyEvent: found model '$model', using it.\n" if $verbose > 1;
106 last;
107 }
85 } 108 }
86 } 109 }
87 110
88 unless ($MODEL) { 111 unless ($MODEL) {
89 # try to load a model 112 # try to load a model
90 113
91 for (@models) { 114 for (@REGISTRY, @models) {
92 my ($model, $package) = @$_; 115 my ($package, $model) = @$_;
93 eval "require AnyEvent::Impl::$model"; 116 if (eval "require $model") {
94 last if $MODEL; 117 $MODEL = $model;
118 warn "AnyEvent: autoprobed and loaded model '$model', using it.\n" if $verbose > 1;
119 last;
120 }
95 } 121 }
96 122
97 $MODEL 123 $MODEL
98 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: Coro, Event, Glib or Tk."; 124 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: Coro, Event, Glib or Tk.";
99 } 125 }
104 my $class = shift; 130 my $class = shift;
105 $class->$AUTOLOAD (@_); 131 $class->$AUTOLOAD (@_);
106} 132}
107 133
108=back 134=back
135
136=head1 SUPPLYING YOUR OWN EVENT MODEL INTERFACE
137
138If you need to support another event library which isn't directly
139supported by AnyEvent, you can supply your own interface to it by
140pushing, before the first watcher gets created, the package name of
141the event module and the package name of the interface to use onto
142C<@AnyEvent::REGISTRY>. You can do that before and even without loading
143AnyEvent.
144
145Example:
146
147 push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
148
149This tells AnyEvent to (literally) use the C<urxvt::anyevent::>
150package/class when it finds the C<urxvt> package/module is loaded. When
151AnyEvent is loaded and asked to find a suitable event model, it will
152first check for the presence of urxvt.
153
154The class should prove implementations for all watcher types (see
155L<AnyEvent::Impl::Event> (source code), L<AnyEvent::Impl::Glib>
156(Source code) and so on for actual examples, use C<perldoc -m
157AnyEvent::Impl::Glib> to see the sources).
158
159The above isn't fictitious, the I<rxvt-unicode> (a.k.a. urxvt)
160uses the above line as-is. An interface isn't included in AnyEvent
161because it doesn't make sense outside the embedded interpreter inside
162I<rxvt-unicode>, and it is updated and maintained as part of the
163I<rxvt-unicode> distribution.
164
165I<rxvt-unicode> also cheats a bit by not providing blocking access to
166condition variables: code blocking while waiting for a condition will
167C<die>. This still works with most modules/usages, and blocking calls must
168not be in an interactive appliation, so it makes sense.
169
170=head1 ENVIRONMENT VARIABLES
171
172The following environment variables are used by this module:
173
174C<PERL_ANYEVENT_VERBOSE> when set to C<2> or higher, reports which event
175model gets used.
109 176
110=head1 EXAMPLE 177=head1 EXAMPLE
111 178
112The following program uses an io watcher to read data from stdin, a timer 179The following program uses an io watcher to read data from stdin, a timer
113to display a message once per second, and a condvar to exit the program 180to display a message once per second, and a condvar to exit the program
135 202
136 new_timer; # create first timer 203 new_timer; # create first timer
137 204
138 $cv->wait; # wait until user enters /^q/i 205 $cv->wait; # wait until user enters /^q/i
139 206
207=head1 REAL-WORLD EXAMPLE
208
209Consider the L<Net::FCP> module. It features (among others) the following
210API calls, which are to freenet what HTTP GET requests are to http:
211
212 my $data = $fcp->client_get ($url); # blocks
213
214 my $transaction = $fcp->txn_client_get ($url); # does not block
215 $transaction->cb ( sub { ... } ); # set optional result callback
216 my $data = $transaction->result; # possibly blocks
217
218The C<client_get> method works like C<LWP::Simple::get>: it requests the
219given URL and waits till the data has arrived. It is defined to be:
220
221 sub client_get { $_[0]->txn_client_get ($_[1])->result }
222
223And in fact is automatically generated. This is the blocking API of
224L<Net::FCP>, and it works as simple as in any other, similar, module.
225
226More complicated is C<txn_client_get>: It only creates a transaction
227(completion, result, ...) object and initiates the transaction.
228
229 my $txn = bless { }, Net::FCP::Txn::;
230
231It also creates a condition variable that is used to signal the completion
232of the request:
233
234 $txn->{finished} = AnyAvent->condvar;
235
236It then creates a socket in non-blocking mode.
237
238 socket $txn->{fh}, ...;
239 fcntl $txn->{fh}, F_SETFL, O_NONBLOCK;
240 connect $txn->{fh}, ...
241 and !$!{EWOULDBLOCK}
242 and !$!{EINPROGRESS}
243 and Carp::croak "unable to connect: $!\n";
244
245Then it creates a write-watcher which gets called whenever an error occurs
246or the connection succeeds:
247
248 $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w });
249
250And returns this transaction object. The C<fh_ready_w> callback gets
251called as soon as the event loop detects that the socket is ready for
252writing.
253
254The C<fh_ready_w> method makes the socket blocking again, writes the
255request data and replaces the watcher by a read watcher (waiting for reply
256data). The actual code is more complicated, but that doesn't matter for
257this example:
258
259 fcntl $txn->{fh}, F_SETFL, 0;
260 syswrite $txn->{fh}, $txn->{request}
261 or die "connection or write error";
262 $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r });
263
264Again, C<fh_ready_r> waits till all data has arrived, and then stores the
265result and signals any possible waiters that the request ahs finished:
266
267 sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf};
268
269 if (end-of-file or data complete) {
270 $txn->{result} = $txn->{buf};
271 $txn->{finished}->broadcast;
272 $txb->{cb}->($txn) of $txn->{cb}; # also call callback
273 }
274
275The C<result> method, finally, just waits for the finished signal (if the
276request was already finished, it doesn't wait, of course, and returns the
277data:
278
279 $txn->{finished}->wait;
280 return $txn->{result};
281
282The actual code goes further and collects all errors (C<die>s, exceptions)
283that occured during request processing. The C<result> method detects
284wether an exception as thrown (it is stored inside the $txn object)
285and just throws the exception, which means connection errors and other
286problems get reported tot he code that tries to use the result, not in a
287random callback.
288
289All of this enables the following usage styles:
290
2911. Blocking:
292
293 my $data = $fcp->client_get ($url);
294
2952. Blocking, but parallelizing:
296
297 my @datas = map $_->result,
298 map $fcp->txn_client_get ($_),
299 @urls;
300
301Both blocking examples work without the module user having to know
302anything about events.
303
3043a. Event-based in a main program, using any support Event module:
305
306 use Event;
307
308 $fcp->txn_client_get ($url)->cb (sub {
309 my $txn = shift;
310 my $data = $txn->result;
311 ...
312 });
313
314 Event::loop;
315
3163b. The module user could use AnyEvent, too:
317
318 use AnyEvent;
319
320 my $quit = AnyEvent->condvar;
321
322 $fcp->txn_client_get ($url)->cb (sub {
323 ...
324 $quit->broadcast;
325 });
326
327 $quit->wait;
328
140=head1 SEE ALSO 329=head1 SEE ALSO
141 330
142L<Coro::Event>, L<Coro>, L<Event>, L<Glib::Event>, L<Glib>, 331Event modules: L<Coro::Event>, L<Coro>, L<Event>, L<Glib::Event>, L<Glib>.
143L<AnyEvent::Impl::Coro>, 332
144L<AnyEvent::Impl::Event>, 333Implementations: L<AnyEvent::Impl::Coro>, L<AnyEvent::Impl::Event>, L<AnyEvent::Impl::Glib>, L<AnyEvent::Impl::Tk>.
145L<AnyEvent::Impl::Glib>, 334
146L<AnyEvent::Impl::Tk>. 335Nontrivial usage example: L<Net::FCP>.
147 336
148=head1 337=head1
149 338
150=cut 339=cut
151 340

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines