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.6 by root, Mon Dec 19 17:03:29 2005 UTC vs.
Revision 1.19 by root, Sun Dec 10 23:59:15 2006 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->io (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 });
15
16- only one io watcher per $fh and $poll type is allowed
17(i.e. on a socket you can have one r + one w or one rw
18watcher, not any more.
19
20- AnyEvent will keep filehandles alive, so as long as the watcher exists,
21the filehandle exists.
22 14
23 my $w = AnyEvent->timer (after => $seconds, cb => sub { 15 my $w = AnyEvent->timer (after => $seconds, cb => sub {
24 ... 16 ...
25 }); 17 });
26 18
27- io and time watchers get canceled whenever $w is destroyed, so keep a copy 19 my $w = AnyEvent->condvar; # stores wether a condition was flagged
28
29- timers can only be used once and must be recreated for repeated operation
30
31 my $w = AnyEvent->condvar; # kind of main loop replacement
32 $w->wait; # enters main loop till $condvar gets ->broadcast 20 $w->wait; # enters "main loop" till $condvar gets ->broadcast
33 $w->broadcast; # wake up current and all future wait's 21 $w->broadcast; # wake up current and all future wait's
34 22
35- condvars are used to give blocking behaviour when neccessary. Create
36a condvar for any "request" or "event" your module might create, C<<
37->broadcast >> it when the event happens and provide a function that calls
38C<< ->wait >> for it. See the examples below.
39
40=head1 DESCRIPTION 23=head1 DESCRIPTION
41 24
42L<AnyEvent> provides an identical interface to multiple event loops. This 25L<AnyEvent> provides an identical interface to multiple event loops. This
43allows module authors to utilizy an event loop without forcing module 26allows module authors to utilise an event loop without forcing module
44users 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
45peacefully at any one time). 28peacefully at any one time).
46 29
47The interface itself is vaguely similar but not identical to the Event 30The interface itself is vaguely similar but not identical to the Event
48module. 31module.
50On 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
51loaded event loop by probing wether any of the following modules is 34loaded event loop by probing wether any of the following modules is
52loaded: 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
53used. 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
54order given. The first one that could be successfully loaded will be 37order given. The first one that could be successfully loaded will be
55used. 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:
56 125
57=over 4 126=over 4
58 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.
166
167These watchers might use C<%SIG>, so programs overwriting those signals
168directly will likely not work correctly.
169
170Example: exit on SIGINT
171
172 my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });
173
174=head1 GLOBALS
175
176=over 4
177
178=item $AnyEvent::MODEL
179
180Contains C<undef> until the first watcher is being created. Then it
181contains the event model that is being used, which is the name of the
182Perl class implementing the model. This class is usually one of the
183C<AnyEvent::Impl:xxx> modules, but can be any other class in the case
184AnyEvent has been extended at runtime (e.g. in I<rxvt-unicode>).
185
186The known classes so far are:
187
188 AnyEvent::Impl::Coro based on Coro::Event, best choise.
189 AnyEvent::Impl::Event based on Event, also best choice :)
190 AnyEvent::Impl::Glib based on Glib, second-best choice.
191 AnyEvent::Impl::Tk based on Tk, very bad choice.
192 AnyEvent::Impl::Perl pure-perl implementation, inefficient.
193
194=item AnyEvent::detect
195
196Returns C<$AnyEvent::MODEL>, forcing autodetection of the event model if
197necessary. You should only call this function right before you would have
198created an AnyEvent watcher anyway, that is, very late at runtime.
199
200=back
201
202=head1 WHAT TO DO IN A MODULE
203
204As a module author, you should "use AnyEvent" and call AnyEvent methods
205freely, but you should not load a specific event module or rely on it.
206
207Be careful when you create watchers in the module body - Anyevent will
208decide which event module to use as soon as the first method is called, so
209by calling AnyEvent in your module body you force the user of your module
210to load the event module first.
211
212=head1 WHAT TO DO IN THE MAIN PROGRAM
213
214There will always be a single main program - the only place that should
215dictate which event model to use.
216
217If it doesn't care, it can just "use AnyEvent" and use it itself, or not
218do anything special and let AnyEvent decide which implementation to chose.
219
220If the main program relies on a specific event model (for example, in Gtk2
221programs you have to rely on either Glib or Glib::Event), you should load
222it before loading AnyEvent or any module that uses it, generally, as early
223as possible. The reason is that modules might create watchers when they
224are loaded, and AnyEvent will decide on the event model to use as soon as
225it creates watchers, and it might chose the wrong one unless you load the
226correct one yourself.
227
228You can chose to use a rather inefficient pure-perl implementation by
229loading the C<AnyEvent::Impl::Perl> module, but letting AnyEvent chose is
230generally better.
231
59=cut 232=cut
60 233
61package AnyEvent; 234package AnyEvent;
62 235
63no warnings; 236no warnings;
64use strict 'vars'; 237use strict;
65use Carp; 238use Carp;
66 239
67our $VERSION = 0.3; 240our $VERSION = '2.5';
68our $MODEL; 241our $MODEL;
69 242
70our $AUTOLOAD; 243our $AUTOLOAD;
71our @ISA; 244our @ISA;
72 245
246our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1;
247
248our @REGISTRY;
249
73my @models = ( 250my @models = (
74 [Coro => Coro::Event::], 251 [Coro::Event:: => AnyEvent::Impl::Coro::],
75 [Event => Event::], 252 [Event:: => AnyEvent::Impl::Event::],
76 [Glib => Glib::], 253 [Glib:: => AnyEvent::Impl::Glib::],
77 [Tk => Tk::], 254 [Tk:: => AnyEvent::Impl::Tk::],
255 [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl::],
78); 256);
79 257
80our %method = map +($_ => 1), qw(io timer condvar broadcast wait cancel DESTROY); 258our %method = map +($_ => 1), qw(io timer condvar broadcast wait signal one_event DESTROY);
81 259
82sub AUTOLOAD { 260sub detect() {
83 $AUTOLOAD =~ s/.*://;
84
85 $method{$AUTOLOAD}
86 or croak "$AUTOLOAD: not a valid method for AnyEvent objects";
87
88 unless ($MODEL) { 261 unless ($MODEL) {
262 no strict 'refs';
263
89 # check for already loaded models 264 # check for already loaded models
90 for (@models) { 265 for (@REGISTRY, @models) {
91 my ($model, $package) = @$_; 266 my ($package, $model) = @$_;
92 if (scalar keys %{ *{"$package\::"} }) { 267 if (${"$package\::VERSION"} > 0) {
93 eval "require AnyEvent::Impl::$model"; 268 if (eval "require $model") {
94 last if $MODEL; 269 $MODEL = $model;
270 warn "AnyEvent: found model '$model', using it.\n" if $verbose > 1;
271 last;
272 }
95 } 273 }
96 } 274 }
97 275
98 unless ($MODEL) { 276 unless ($MODEL) {
99 # try to load a model 277 # try to load a model
100 278
101 for (@models) { 279 for (@REGISTRY, @models) {
102 my ($model, $package) = @$_; 280 my ($package, $model) = @$_;
103 eval "require AnyEvent::Impl::$model"; 281 if (eval "require $model") {
104 last if $MODEL; 282 $MODEL = $model;
283 warn "AnyEvent: autoprobed and loaded model '$model', using it.\n" if $verbose > 1;
284 last;
285 }
105 } 286 }
106 287
107 $MODEL 288 $MODEL
108 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: Coro, Event, Glib or Tk."; 289 or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: Event (or Coro+Event), Glib or Tk.";
109 } 290 }
291
292 unshift @ISA, $MODEL;
293 push @{"$MODEL\::ISA"}, "AnyEvent::Base";
110 } 294 }
111 295
112 @ISA = $MODEL; 296 $MODEL
297}
298
299sub AUTOLOAD {
300 (my $func = $AUTOLOAD) =~ s/.*://;
301
302 $method{$func}
303 or croak "$func: not a valid method for AnyEvent objects";
304
305 detect unless $MODEL;
113 306
114 my $class = shift; 307 my $class = shift;
115 $class->$AUTOLOAD (@_); 308 $class->$func (@_);
116} 309}
117 310
118=back 311package AnyEvent::Base;
312
313# default implementation for signal
314
315our %SIG_CB;
316
317sub signal {
318 my (undef, %arg) = @_;
319
320 my $signal = uc $arg{signal}
321 or Carp::croak "required option 'signal' is missing";
322
323 my $w = bless [$signal, $arg{cb}], "AnyEvent::Base::Signal";
324
325 $SIG_CB{$signal}{$arg{cb}} = $arg{cb};
326 $SIG{$signal} ||= sub {
327 $_->() for values %{ $SIG_CB{$signal} };
328 };
329
330 $w
331}
332
333sub AnyEvent::Base::Signal::DESTROY {
334 my ($signal, $cb) = @{$_[0]};
335
336 delete $SIG_CB{$signal}{$cb};
337
338 $SIG{$signal} = 'DEFAULT' unless keys %{ $SIG_CB{$signal} };
339}
340
341=head1 SUPPLYING YOUR OWN EVENT MODEL INTERFACE
342
343If you need to support another event library which isn't directly
344supported by AnyEvent, you can supply your own interface to it by
345pushing, before the first watcher gets created, the package name of
346the event module and the package name of the interface to use onto
347C<@AnyEvent::REGISTRY>. You can do that before and even without loading
348AnyEvent.
349
350Example:
351
352 push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::];
353
354This tells AnyEvent to (literally) use the C<urxvt::anyevent::>
355package/class when it finds the C<urxvt> package/module is loaded. When
356AnyEvent is loaded and asked to find a suitable event model, it will
357first check for the presence of urxvt.
358
359The class should provide implementations for all watcher types (see
360L<AnyEvent::Impl::Event> (source code), L<AnyEvent::Impl::Glib>
361(Source code) and so on for actual examples, use C<perldoc -m
362AnyEvent::Impl::Glib> to see the sources).
363
364The above isn't fictitious, the I<rxvt-unicode> (a.k.a. urxvt)
365uses the above line as-is. An interface isn't included in AnyEvent
366because it doesn't make sense outside the embedded interpreter inside
367I<rxvt-unicode>, and it is updated and maintained as part of the
368I<rxvt-unicode> distribution.
369
370I<rxvt-unicode> also cheats a bit by not providing blocking access to
371condition variables: code blocking while waiting for a condition will
372C<die>. This still works with most modules/usages, and blocking calls must
373not be in an interactive appliation, so it makes sense.
374
375=head1 ENVIRONMENT VARIABLES
376
377The following environment variables are used by this module:
378
379C<PERL_ANYEVENT_VERBOSE> when set to C<2> or higher, reports which event
380model gets used.
119 381
120=head1 EXAMPLE 382=head1 EXAMPLE
121 383
122The following program uses an io watcher to read data from stdin, a timer 384The following program uses an io watcher to read data from stdin, a timer
123to display a message once per second, and a condvar to exit the program 385to display a message once per second, and a condvar to exit the program

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines