1 |
NAME |
2 |
AnyEvent - provide framework for multiple event loops |
3 |
|
4 |
Event, Coro, Glib, Tk, Perl - various supported event loops |
5 |
|
6 |
SYNOPSIS |
7 |
use AnyEvent; |
8 |
|
9 |
my $w = AnyEvent->io (fh => $fh, poll => "r|w", cb => sub { |
10 |
... |
11 |
}); |
12 |
|
13 |
my $w = AnyEvent->timer (after => $seconds, cb => sub { |
14 |
... |
15 |
}); |
16 |
|
17 |
my $w = AnyEvent->condvar; # stores wether a condition was flagged |
18 |
$w->wait; # enters "main loop" till $condvar gets ->broadcast |
19 |
$w->broadcast; # wake up current and all future wait's |
20 |
|
21 |
WHY YOU SHOULD USE THIS MODULE (OR NOT) |
22 |
Glib, POE, IO::Async, Event... CPAN offers event models by the dozen |
23 |
nowadays. So what is different about AnyEvent? |
24 |
|
25 |
Executive Summary: AnyEvent is *compatible*, AnyEvent is *free of |
26 |
policy* and AnyEvent is *small and efficient*. |
27 |
|
28 |
First and foremost, *AnyEvent is not an event model* itself, it only |
29 |
interfaces to whatever event model the main program happens to use in a |
30 |
pragmatic way. For event models and certain classes of immortals alike, |
31 |
the statement "there can only be one" is a bitter reality, and AnyEvent |
32 |
helps hiding the differences. |
33 |
|
34 |
The goal of AnyEvent is to offer module authors the ability to do event |
35 |
programming (waiting for I/O or timer events) without subscribing to a |
36 |
religion, a way of living, and most importantly: without forcing your |
37 |
module users into the same thing by forcing them to use the same event |
38 |
model you use. |
39 |
|
40 |
For modules like POE or IO::Async (which is actually doing all I/O |
41 |
*synchronously*...), using them in your module is like joining a cult: |
42 |
After you joined, you are dependent on them and you cannot use anything |
43 |
else, as it is simply incompatible to everything that isn't itself. |
44 |
|
45 |
AnyEvent + POE works fine. AnyEvent + Glib works fine. AnyEvent + Tk |
46 |
works fine etc. etc. but none of these work together with the rest: POE |
47 |
+ IO::Async? no go. Tk + Event? no go. If your module uses one of those, |
48 |
every user of your module has to use it, too. If your module uses |
49 |
AnyEvent, it works transparently with all event models it supports |
50 |
(including stuff like POE and IO::Async). |
51 |
|
52 |
In addition of being free of having to use *the one and only true event |
53 |
model*, AnyEvent also is free of bloat and policy: with POE or similar |
54 |
modules, you get an enourmous amount of code and strict rules you have |
55 |
to follow. AnyEvent, on the other hand, is lean and to the point by only |
56 |
offering the functionality that is useful, in as thin as a wrapper as |
57 |
technically possible. |
58 |
|
59 |
Of course, if you want lots of policy (this can arguably be somewhat |
60 |
useful) and you want to force your users to use the one and only event |
61 |
model, you should *not* use this module. |
62 |
|
63 |
DESCRIPTION |
64 |
AnyEvent provides an identical interface to multiple event loops. This |
65 |
allows module authors to utilise an event loop without forcing module |
66 |
users to use the same event loop (as only a single event loop can |
67 |
coexist peacefully at any one time). |
68 |
|
69 |
The interface itself is vaguely similar but not identical to the Event |
70 |
module. |
71 |
|
72 |
On the first call of any method, the module tries to detect the |
73 |
currently loaded event loop by probing wether any of the following |
74 |
modules is loaded: Coro::Event, Event, Glib, Tk. The first one found is |
75 |
used. If none is found, the module tries to load these modules in the |
76 |
order given. The first one that could be successfully loaded will be |
77 |
used. If still none could be found, AnyEvent will fall back to a |
78 |
pure-perl event loop, which is also not very efficient. |
79 |
|
80 |
Because AnyEvent first checks for modules that are already loaded, |
81 |
loading an Event model explicitly before first using AnyEvent will |
82 |
likely make that model the default. For example: |
83 |
|
84 |
use Tk; |
85 |
use AnyEvent; |
86 |
|
87 |
# .. AnyEvent will likely default to Tk |
88 |
|
89 |
The pure-perl implementation of AnyEvent is called |
90 |
"AnyEvent::Impl::Perl". Like other event modules you can load it |
91 |
explicitly. |
92 |
|
93 |
WATCHERS |
94 |
AnyEvent has the central concept of a *watcher*, which is an object that |
95 |
stores relevant data for each kind of event you are waiting for, such as |
96 |
the callback to call, the filehandle to watch, etc. |
97 |
|
98 |
These watchers are normal Perl objects with normal Perl lifetime. After |
99 |
creating a watcher it will immediately "watch" for events and invoke the |
100 |
callback. To disable the watcher you have to destroy it (e.g. by setting |
101 |
the variable that stores it to "undef" or otherwise deleting all |
102 |
references to it). |
103 |
|
104 |
All watchers are created by calling a method on the "AnyEvent" class. |
105 |
|
106 |
IO WATCHERS |
107 |
You can create I/O watcher by calling the "AnyEvent->io" method with the |
108 |
following mandatory arguments: |
109 |
|
110 |
"fh" the Perl *filehandle* (not filedescriptor) to watch for events. |
111 |
"poll" must be a string that is either "r" or "w", that creates a |
112 |
watcher waiting for "r"eadable or "w"ritable events. "cb" the callback |
113 |
to invoke everytime the filehandle becomes ready. |
114 |
|
115 |
Only one io watcher per "fh" and "poll" combination is allowed (i.e. on |
116 |
a socket you can have one r + one w, not any more (limitation comes from |
117 |
Tk - if you are sure you are not using Tk this limitation is gone). |
118 |
|
119 |
Filehandles will be kept alive, so as long as the watcher exists, the |
120 |
filehandle exists, too. |
121 |
|
122 |
Example: |
123 |
|
124 |
# wait for readability of STDIN, then read a line and disable the watcher |
125 |
my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub { |
126 |
chomp (my $input = <STDIN>); |
127 |
warn "read: $input\n"; |
128 |
undef $w; |
129 |
}); |
130 |
|
131 |
TIME WATCHERS |
132 |
You can create a time watcher by calling the "AnyEvent->timer" method |
133 |
with the following mandatory arguments: |
134 |
|
135 |
"after" after how many seconds (fractions are supported) should the |
136 |
timer activate. "cb" the callback to invoke. |
137 |
|
138 |
The timer callback will be invoked at most once: if you want a repeating |
139 |
timer you have to create a new watcher (this is a limitation by both Tk |
140 |
and Glib). |
141 |
|
142 |
Example: |
143 |
|
144 |
# fire an event after 7.7 seconds |
145 |
my $w = AnyEvent->timer (after => 7.7, cb => sub { |
146 |
warn "timeout\n"; |
147 |
}); |
148 |
|
149 |
# to cancel the timer: |
150 |
undef $w; |
151 |
|
152 |
CONDITION WATCHERS |
153 |
Condition watchers can be created by calling the "AnyEvent->condvar" |
154 |
method without any arguments. |
155 |
|
156 |
A condition watcher watches for a condition - precisely that the |
157 |
"->broadcast" method has been called. |
158 |
|
159 |
Note that condition watchers recurse into the event loop - if you have |
160 |
two watchers that call "->wait" in a round-robbin fashion, you lose. |
161 |
Therefore, condition watchers are good to export to your caller, but you |
162 |
should avoid making a blocking wait, at least in callbacks, as this |
163 |
usually asks for trouble. |
164 |
|
165 |
The watcher has only two methods: |
166 |
|
167 |
$cv->wait |
168 |
Wait (blocking if necessary) until the "->broadcast" method has been |
169 |
called on c<$cv>, while servicing other watchers normally. |
170 |
|
171 |
Not all event models support a blocking wait - some die in that |
172 |
case, so if you are using this from a module, never require a |
173 |
blocking wait, but let the caller decide wether the call will block |
174 |
or not (for example, by coupling condition variables with some kind |
175 |
of request results and supporting callbacks so the caller knows that |
176 |
getting the result will not block, while still suppporting blockign |
177 |
waits if the caller so desires). |
178 |
|
179 |
You can only wait once on a condition - additional calls will return |
180 |
immediately. |
181 |
|
182 |
$cv->broadcast |
183 |
Flag the condition as ready - a running "->wait" and all further |
184 |
calls to "wait" will return after this method has been called. If |
185 |
nobody is waiting the broadcast will be remembered.. |
186 |
|
187 |
Example: |
188 |
|
189 |
# wait till the result is ready |
190 |
my $result_ready = AnyEvent->condvar; |
191 |
|
192 |
# do something such as adding a timer |
193 |
# or socket watcher the calls $result_ready->broadcast |
194 |
# when the "result" is ready. |
195 |
|
196 |
$result_ready->wait; |
197 |
|
198 |
SIGNAL WATCHERS |
199 |
You can listen for signals using a signal watcher, "signal" is the |
200 |
signal *name* without any "SIG" prefix. Multiple signals events can be |
201 |
clumped together into one callback invocation, and callback invocation |
202 |
might or might not be asynchronous. |
203 |
|
204 |
These watchers might use %SIG, so programs overwriting those signals |
205 |
directly will likely not work correctly. |
206 |
|
207 |
Example: exit on SIGINT |
208 |
|
209 |
my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 }); |
210 |
|
211 |
CHILD PROCESS WATCHERS |
212 |
You can also listen for the status of a child process specified by the |
213 |
"pid" argument (or any child if the pid argument is 0). The watcher will |
214 |
trigger as often as status change for the child are received. This works |
215 |
by installing a signal handler for "SIGCHLD". The callback will be |
216 |
called with the pid and exit status (as returned by waitpid). |
217 |
|
218 |
Example: wait for pid 1333 |
219 |
|
220 |
my $w = AnyEvent->child (pid => 1333, cb => sub { warn "exit status $?" }); |
221 |
|
222 |
GLOBALS |
223 |
$AnyEvent::MODEL |
224 |
Contains "undef" until the first watcher is being created. Then it |
225 |
contains the event model that is being used, which is the name of |
226 |
the Perl class implementing the model. This class is usually one of |
227 |
the "AnyEvent::Impl:xxx" modules, but can be any other class in the |
228 |
case AnyEvent has been extended at runtime (e.g. in *rxvt-unicode*). |
229 |
|
230 |
The known classes so far are: |
231 |
|
232 |
AnyEvent::Impl::CoroEV based on Coro::EV, best choice. |
233 |
AnyEvent::Impl::EV based on EV (an interface to libev, also best choice). |
234 |
AnyEvent::Impl::CoroEvent based on Coro::Event, second best choice. |
235 |
AnyEvent::Impl::Event based on Event, also second best choice :) |
236 |
AnyEvent::Impl::Glib based on Glib, second-best choice. |
237 |
AnyEvent::Impl::Tk based on Tk, very bad choice. |
238 |
AnyEvent::Impl::Perl pure-perl implementation, inefficient. |
239 |
|
240 |
AnyEvent::detect |
241 |
Returns $AnyEvent::MODEL, forcing autodetection of the event model |
242 |
if necessary. You should only call this function right before you |
243 |
would have created an AnyEvent watcher anyway, that is, very late at |
244 |
runtime. |
245 |
|
246 |
WHAT TO DO IN A MODULE |
247 |
As a module author, you should "use AnyEvent" and call AnyEvent methods |
248 |
freely, but you should not load a specific event module or rely on it. |
249 |
|
250 |
Be careful when you create watchers in the module body - Anyevent will |
251 |
decide which event module to use as soon as the first method is called, |
252 |
so by calling AnyEvent in your module body you force the user of your |
253 |
module to load the event module first. |
254 |
|
255 |
WHAT TO DO IN THE MAIN PROGRAM |
256 |
There will always be a single main program - the only place that should |
257 |
dictate which event model to use. |
258 |
|
259 |
If it doesn't care, it can just "use AnyEvent" and use it itself, or not |
260 |
do anything special and let AnyEvent decide which implementation to |
261 |
chose. |
262 |
|
263 |
If the main program relies on a specific event model (for example, in |
264 |
Gtk2 programs you have to rely on either Glib or Glib::Event), you |
265 |
should load it before loading AnyEvent or any module that uses it, |
266 |
generally, as early as possible. The reason is that modules might create |
267 |
watchers when they are loaded, and AnyEvent will decide on the event |
268 |
model to use as soon as it creates watchers, and it might chose the |
269 |
wrong one unless you load the correct one yourself. |
270 |
|
271 |
You can chose to use a rather inefficient pure-perl implementation by |
272 |
loading the "AnyEvent::Impl::Perl" module, but letting AnyEvent chose is |
273 |
generally better. |
274 |
|
275 |
SUPPLYING YOUR OWN EVENT MODEL INTERFACE |
276 |
If you need to support another event library which isn't directly |
277 |
supported by AnyEvent, you can supply your own interface to it by |
278 |
pushing, before the first watcher gets created, the package name of the |
279 |
event module and the package name of the interface to use onto |
280 |
@AnyEvent::REGISTRY. You can do that before and even without loading |
281 |
AnyEvent. |
282 |
|
283 |
Example: |
284 |
|
285 |
push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::]; |
286 |
|
287 |
This tells AnyEvent to (literally) use the "urxvt::anyevent::" |
288 |
package/class when it finds the "urxvt" package/module is loaded. When |
289 |
AnyEvent is loaded and asked to find a suitable event model, it will |
290 |
first check for the presence of urxvt. |
291 |
|
292 |
The class should provide implementations for all watcher types (see |
293 |
AnyEvent::Impl::Event (source code), AnyEvent::Impl::Glib (Source code) |
294 |
and so on for actual examples, use "perldoc -m AnyEvent::Impl::Glib" to |
295 |
see the sources). |
296 |
|
297 |
The above isn't fictitious, the *rxvt-unicode* (a.k.a. urxvt) uses the |
298 |
above line as-is. An interface isn't included in AnyEvent because it |
299 |
doesn't make sense outside the embedded interpreter inside |
300 |
*rxvt-unicode*, and it is updated and maintained as part of the |
301 |
*rxvt-unicode* distribution. |
302 |
|
303 |
*rxvt-unicode* also cheats a bit by not providing blocking access to |
304 |
condition variables: code blocking while waiting for a condition will |
305 |
"die". This still works with most modules/usages, and blocking calls |
306 |
must not be in an interactive application, so it makes sense. |
307 |
|
308 |
ENVIRONMENT VARIABLES |
309 |
The following environment variables are used by this module: |
310 |
|
311 |
"PERL_ANYEVENT_VERBOSE" when set to 2 or higher, reports which event |
312 |
model gets used. |
313 |
|
314 |
EXAMPLE |
315 |
The following program uses an io watcher to read data from stdin, a |
316 |
timer to display a message once per second, and a condvar to exit the |
317 |
program when the user enters quit: |
318 |
|
319 |
use AnyEvent; |
320 |
|
321 |
my $cv = AnyEvent->condvar; |
322 |
|
323 |
my $io_watcher = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub { |
324 |
warn "io event <$_[0]>\n"; # will always output <r> |
325 |
chomp (my $input = <STDIN>); # read a line |
326 |
warn "read: $input\n"; # output what has been read |
327 |
$cv->broadcast if $input =~ /^q/i; # quit program if /^q/i |
328 |
}); |
329 |
|
330 |
my $time_watcher; # can only be used once |
331 |
|
332 |
sub new_timer { |
333 |
$timer = AnyEvent->timer (after => 1, cb => sub { |
334 |
warn "timeout\n"; # print 'timeout' about every second |
335 |
&new_timer; # and restart the time |
336 |
}); |
337 |
} |
338 |
|
339 |
new_timer; # create first timer |
340 |
|
341 |
$cv->wait; # wait until user enters /^q/i |
342 |
|
343 |
REAL-WORLD EXAMPLE |
344 |
Consider the Net::FCP module. It features (among others) the following |
345 |
API calls, which are to freenet what HTTP GET requests are to http: |
346 |
|
347 |
my $data = $fcp->client_get ($url); # blocks |
348 |
|
349 |
my $transaction = $fcp->txn_client_get ($url); # does not block |
350 |
$transaction->cb ( sub { ... } ); # set optional result callback |
351 |
my $data = $transaction->result; # possibly blocks |
352 |
|
353 |
The "client_get" method works like "LWP::Simple::get": it requests the |
354 |
given URL and waits till the data has arrived. It is defined to be: |
355 |
|
356 |
sub client_get { $_[0]->txn_client_get ($_[1])->result } |
357 |
|
358 |
And in fact is automatically generated. This is the blocking API of |
359 |
Net::FCP, and it works as simple as in any other, similar, module. |
360 |
|
361 |
More complicated is "txn_client_get": It only creates a transaction |
362 |
(completion, result, ...) object and initiates the transaction. |
363 |
|
364 |
my $txn = bless { }, Net::FCP::Txn::; |
365 |
|
366 |
It also creates a condition variable that is used to signal the |
367 |
completion of the request: |
368 |
|
369 |
$txn->{finished} = AnyAvent->condvar; |
370 |
|
371 |
It then creates a socket in non-blocking mode. |
372 |
|
373 |
socket $txn->{fh}, ...; |
374 |
fcntl $txn->{fh}, F_SETFL, O_NONBLOCK; |
375 |
connect $txn->{fh}, ... |
376 |
and !$!{EWOULDBLOCK} |
377 |
and !$!{EINPROGRESS} |
378 |
and Carp::croak "unable to connect: $!\n"; |
379 |
|
380 |
Then it creates a write-watcher which gets called whenever an error |
381 |
occurs or the connection succeeds: |
382 |
|
383 |
$txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w }); |
384 |
|
385 |
And returns this transaction object. The "fh_ready_w" callback gets |
386 |
called as soon as the event loop detects that the socket is ready for |
387 |
writing. |
388 |
|
389 |
The "fh_ready_w" method makes the socket blocking again, writes the |
390 |
request data and replaces the watcher by a read watcher (waiting for |
391 |
reply data). The actual code is more complicated, but that doesn't |
392 |
matter for this example: |
393 |
|
394 |
fcntl $txn->{fh}, F_SETFL, 0; |
395 |
syswrite $txn->{fh}, $txn->{request} |
396 |
or die "connection or write error"; |
397 |
$txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r }); |
398 |
|
399 |
Again, "fh_ready_r" waits till all data has arrived, and then stores the |
400 |
result and signals any possible waiters that the request ahs finished: |
401 |
|
402 |
sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf}; |
403 |
|
404 |
if (end-of-file or data complete) { |
405 |
$txn->{result} = $txn->{buf}; |
406 |
$txn->{finished}->broadcast; |
407 |
$txb->{cb}->($txn) of $txn->{cb}; # also call callback |
408 |
} |
409 |
|
410 |
The "result" method, finally, just waits for the finished signal (if the |
411 |
request was already finished, it doesn't wait, of course, and returns |
412 |
the data: |
413 |
|
414 |
$txn->{finished}->wait; |
415 |
return $txn->{result}; |
416 |
|
417 |
The actual code goes further and collects all errors ("die"s, |
418 |
exceptions) that occured during request processing. The "result" method |
419 |
detects wether an exception as thrown (it is stored inside the $txn |
420 |
object) and just throws the exception, which means connection errors and |
421 |
other problems get reported tot he code that tries to use the result, |
422 |
not in a random callback. |
423 |
|
424 |
All of this enables the following usage styles: |
425 |
|
426 |
1. Blocking: |
427 |
|
428 |
my $data = $fcp->client_get ($url); |
429 |
|
430 |
2. Blocking, but parallelizing: |
431 |
|
432 |
my @datas = map $_->result, |
433 |
map $fcp->txn_client_get ($_), |
434 |
@urls; |
435 |
|
436 |
Both blocking examples work without the module user having to know |
437 |
anything about events. |
438 |
|
439 |
3a. Event-based in a main program, using any support Event module: |
440 |
|
441 |
use Event; |
442 |
|
443 |
$fcp->txn_client_get ($url)->cb (sub { |
444 |
my $txn = shift; |
445 |
my $data = $txn->result; |
446 |
... |
447 |
}); |
448 |
|
449 |
Event::loop; |
450 |
|
451 |
3b. The module user could use AnyEvent, too: |
452 |
|
453 |
use AnyEvent; |
454 |
|
455 |
my $quit = AnyEvent->condvar; |
456 |
|
457 |
$fcp->txn_client_get ($url)->cb (sub { |
458 |
... |
459 |
$quit->broadcast; |
460 |
}); |
461 |
|
462 |
$quit->wait; |
463 |
|
464 |
SEE ALSO |
465 |
Event modules: Coro::Event, Coro, Event, Glib::Event, Glib. |
466 |
|
467 |
Implementations: AnyEvent::Impl::Coro, AnyEvent::Impl::Event, |
468 |
AnyEvent::Impl::Glib, AnyEvent::Impl::Tk. |
469 |
|
470 |
Nontrivial usage example: Net::FCP. |
471 |
|
472 |
|