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 |
DESCRIPTION |
22 |
AnyEvent provides an identical interface to multiple event loops. This |
23 |
allows module authors to utilise an event loop without forcing module |
24 |
users to use the same event loop (as only a single event loop can |
25 |
coexist peacefully at any one time). |
26 |
|
27 |
The interface itself is vaguely similar but not identical to the Event |
28 |
module. |
29 |
|
30 |
On the first call of any method, the module tries to detect the |
31 |
currently loaded event loop by probing wether any of the following |
32 |
modules is loaded: Coro::Event, Event, Glib, Tk. The first one found is |
33 |
used. If none is found, the module tries to load these modules in the |
34 |
order given. The first one that could be successfully loaded will be |
35 |
used. If still none could be found, AnyEvent will fall back to a |
36 |
pure-perl event loop, which is also not very efficient. |
37 |
|
38 |
Because AnyEvent first checks for modules that are already loaded, |
39 |
loading an Event model explicitly before first using AnyEvent will |
40 |
likely make that model the default. For example: |
41 |
|
42 |
use Tk; |
43 |
use AnyEvent; |
44 |
|
45 |
# .. AnyEvent will likely default to Tk |
46 |
|
47 |
The pure-perl implementation of AnyEvent is called |
48 |
"AnyEvent::Impl::Perl". Like other event modules you can load it |
49 |
explicitly. |
50 |
|
51 |
WATCHERS |
52 |
AnyEvent has the central concept of a *watcher*, which is an object that |
53 |
stores relevant data for each kind of event you are waiting for, such as |
54 |
the callback to call, the filehandle to watch, etc. |
55 |
|
56 |
These watchers are normal Perl objects with normal Perl lifetime. After |
57 |
creating a watcher it will immediately "watch" for events and invoke the |
58 |
callback. To disable the watcher you have to destroy it (e.g. by setting |
59 |
the variable that stores it to "undef" or otherwise deleting all |
60 |
references to it). |
61 |
|
62 |
All watchers are created by calling a method on the "AnyEvent" class. |
63 |
|
64 |
IO WATCHERS |
65 |
You can create I/O watcher by calling the "AnyEvent->io" method with the |
66 |
following mandatory arguments: |
67 |
|
68 |
"fh" the Perl *filehandle* (not filedescriptor) to watch for events. |
69 |
"poll" must be a string that is either "r" or "w", that creates a |
70 |
watcher waiting for "r"eadable or "w"ritable events. "cb" teh callback |
71 |
to invoke everytime the filehandle becomes ready. |
72 |
|
73 |
Only one io watcher per "fh" and "poll" combination is allowed (i.e. on |
74 |
a socket you can have one r + one w, not any more (limitation comes from |
75 |
Tk - if you are sure you are not using Tk this limitation is gone). |
76 |
|
77 |
Filehandles will be kept alive, so as long as the watcher exists, the |
78 |
filehandle exists, too. |
79 |
|
80 |
Example: |
81 |
|
82 |
# wait for readability of STDIN, then read a line and disable the watcher |
83 |
my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub { |
84 |
chomp (my $input = <STDIN>); |
85 |
warn "read: $input\n"; |
86 |
undef $w; |
87 |
}); |
88 |
|
89 |
TIMER WATCHERS |
90 |
You can create a timer watcher by calling the "AnyEvent->timer" method |
91 |
with the following mandatory arguments: |
92 |
|
93 |
"after" after how many seconds (fractions are supported) should the |
94 |
timer activate. "cb" the callback to invoke. |
95 |
|
96 |
The timer callback will be invoked at most once: if you want a repeating |
97 |
timer you have to create a new watcher (this is a limitation by both Tk |
98 |
and Glib). |
99 |
|
100 |
Example: |
101 |
|
102 |
# fire an event after 7.7 seconds |
103 |
my $w = AnyEvent->timer (after => 7.7, cb => sub { |
104 |
warn "timeout\n"; |
105 |
}); |
106 |
|
107 |
# to cancel the timer: |
108 |
undef $w |
109 |
|
110 |
CONDITION WATCHERS |
111 |
Condition watchers can be created by calling the "AnyEvent->condvar" |
112 |
method without any arguments. |
113 |
|
114 |
A condition watcher watches for a condition - precisely that the |
115 |
"->broadcast" method has been called. |
116 |
|
117 |
The watcher has only two methods: |
118 |
|
119 |
$cv->wait |
120 |
Wait (blocking if necessary) until the "->broadcast" method has been |
121 |
called on c<$cv>, while servicing other watchers normally. |
122 |
|
123 |
Not all event models support a blocking wait - some die in that |
124 |
case, so if you are using this from a module, never require a |
125 |
blocking wait, but let the caller decide wether the call will block |
126 |
or not (for example, by coupling condition variables with some kind |
127 |
of request results and supporting callbacks so the caller knows that |
128 |
getting the result will not block, while still suppporting blockign |
129 |
waits if the caller so desires). |
130 |
|
131 |
You can only wait once on a condition - additional calls will return |
132 |
immediately. |
133 |
|
134 |
$cv->broadcast |
135 |
Flag the condition as ready - a running "->wait" and all further |
136 |
calls to "wait" will return after this method has been called. If |
137 |
nobody is waiting the broadcast will be remembered.. |
138 |
|
139 |
Example: |
140 |
|
141 |
# wait till the result is ready |
142 |
my $result_ready = AnyEvent->condvar; |
143 |
|
144 |
# do something such as adding a timer |
145 |
# or socket watcher the calls $result_ready->broadcast |
146 |
# when the "result" is ready. |
147 |
|
148 |
$result_ready->wait; |
149 |
|
150 |
GLOBALS |
151 |
$AnyEvent::MODEL |
152 |
Contains "undef" until the first watcher is being created. Then it |
153 |
contains the event model that is being used, which is the name of |
154 |
the Perl class implementing the model. This class is usually one of |
155 |
the "AnyEvent::Impl:xxx" modules, but can be any other class in the |
156 |
case AnyEvent has been extended at runtime (e.g. in *rxvt-unicode*). |
157 |
|
158 |
The known classes so far are: |
159 |
|
160 |
AnyEvent::Impl::Coro based on Coro::Event, best choise. |
161 |
AnyEvent::Impl::Event based on Event, also best choice :) |
162 |
AnyEvent::Impl::Glib based on Glib, second-best choice. |
163 |
AnyEvent::Impl::Tk based on Tk, very bad choice. |
164 |
AnyEvent::Impl::Perl pure-perl implementation, inefficient. |
165 |
|
166 |
WHAT TO DO IN A MODULE |
167 |
As a module author, you should "use AnyEvent" and call AnyEvent methods |
168 |
freely, but you should not load a specific event module or rely on it. |
169 |
|
170 |
Be careful when you create watchers in the module body - Anyevent will |
171 |
decide which event module to use as soon as the first method is called, |
172 |
so by calling AnyEvent in your module body you force the user of your |
173 |
module to load the event module first. |
174 |
|
175 |
WHAT TO DO IN THE MAIN PROGRAM |
176 |
There will always be a single main program - the only place that should |
177 |
dictate which event model to use. |
178 |
|
179 |
If it doesn't care, it can just "use AnyEvent" and use it itself, or not |
180 |
do anything special and let AnyEvent decide which implementation to |
181 |
chose. |
182 |
|
183 |
If the main program relies on a specific event model (for example, in |
184 |
Gtk2 programs you have to rely on either Glib or Glib::Event), you |
185 |
should load it before loading AnyEvent or any module that uses it, |
186 |
generally, as early as possible. The reason is that modules might create |
187 |
watchers when they are loaded, and AnyEvent will decide on the event |
188 |
model to use as soon as it creates watchers, and it might chose the |
189 |
wrong one unless you load the correct one yourself. |
190 |
|
191 |
You can chose to use a rather inefficient pure-perl implementation by |
192 |
loading the "AnyEvent::Impl::Perl" module, but letting AnyEvent chose is |
193 |
generally better. |
194 |
|
195 |
SUPPLYING YOUR OWN EVENT MODEL INTERFACE |
196 |
If you need to support another event library which isn't directly |
197 |
supported by AnyEvent, you can supply your own interface to it by |
198 |
pushing, before the first watcher gets created, the package name of the |
199 |
event module and the package name of the interface to use onto |
200 |
@AnyEvent::REGISTRY. You can do that before and even without loading |
201 |
AnyEvent. |
202 |
|
203 |
Example: |
204 |
|
205 |
push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::]; |
206 |
|
207 |
This tells AnyEvent to (literally) use the "urxvt::anyevent::" |
208 |
package/class when it finds the "urxvt" package/module is loaded. When |
209 |
AnyEvent is loaded and asked to find a suitable event model, it will |
210 |
first check for the presence of urxvt. |
211 |
|
212 |
The class should prove implementations for all watcher types (see |
213 |
AnyEvent::Impl::Event (source code), AnyEvent::Impl::Glib (Source code) |
214 |
and so on for actual examples, use "perldoc -m AnyEvent::Impl::Glib" to |
215 |
see the sources). |
216 |
|
217 |
The above isn't fictitious, the *rxvt-unicode* (a.k.a. urxvt) uses the |
218 |
above line as-is. An interface isn't included in AnyEvent because it |
219 |
doesn't make sense outside the embedded interpreter inside |
220 |
*rxvt-unicode*, and it is updated and maintained as part of the |
221 |
*rxvt-unicode* distribution. |
222 |
|
223 |
*rxvt-unicode* also cheats a bit by not providing blocking access to |
224 |
condition variables: code blocking while waiting for a condition will |
225 |
"die". This still works with most modules/usages, and blocking calls |
226 |
must not be in an interactive appliation, so it makes sense. |
227 |
|
228 |
ENVIRONMENT VARIABLES |
229 |
The following environment variables are used by this module: |
230 |
|
231 |
"PERL_ANYEVENT_VERBOSE" when set to 2 or higher, reports which event |
232 |
model gets used. |
233 |
|
234 |
EXAMPLE |
235 |
The following program uses an io watcher to read data from stdin, a |
236 |
timer to display a message once per second, and a condvar to exit the |
237 |
program when the user enters quit: |
238 |
|
239 |
use AnyEvent; |
240 |
|
241 |
my $cv = AnyEvent->condvar; |
242 |
|
243 |
my $io_watcher = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub { |
244 |
warn "io event <$_[0]>\n"; # will always output <r> |
245 |
chomp (my $input = <STDIN>); # read a line |
246 |
warn "read: $input\n"; # output what has been read |
247 |
$cv->broadcast if $input =~ /^q/i; # quit program if /^q/i |
248 |
}); |
249 |
|
250 |
my $time_watcher; # can only be used once |
251 |
|
252 |
sub new_timer { |
253 |
$timer = AnyEvent->timer (after => 1, cb => sub { |
254 |
warn "timeout\n"; # print 'timeout' about every second |
255 |
&new_timer; # and restart the time |
256 |
}); |
257 |
} |
258 |
|
259 |
new_timer; # create first timer |
260 |
|
261 |
$cv->wait; # wait until user enters /^q/i |
262 |
|
263 |
REAL-WORLD EXAMPLE |
264 |
Consider the Net::FCP module. It features (among others) the following |
265 |
API calls, which are to freenet what HTTP GET requests are to http: |
266 |
|
267 |
my $data = $fcp->client_get ($url); # blocks |
268 |
|
269 |
my $transaction = $fcp->txn_client_get ($url); # does not block |
270 |
$transaction->cb ( sub { ... } ); # set optional result callback |
271 |
my $data = $transaction->result; # possibly blocks |
272 |
|
273 |
The "client_get" method works like "LWP::Simple::get": it requests the |
274 |
given URL and waits till the data has arrived. It is defined to be: |
275 |
|
276 |
sub client_get { $_[0]->txn_client_get ($_[1])->result } |
277 |
|
278 |
And in fact is automatically generated. This is the blocking API of |
279 |
Net::FCP, and it works as simple as in any other, similar, module. |
280 |
|
281 |
More complicated is "txn_client_get": It only creates a transaction |
282 |
(completion, result, ...) object and initiates the transaction. |
283 |
|
284 |
my $txn = bless { }, Net::FCP::Txn::; |
285 |
|
286 |
It also creates a condition variable that is used to signal the |
287 |
completion of the request: |
288 |
|
289 |
$txn->{finished} = AnyAvent->condvar; |
290 |
|
291 |
It then creates a socket in non-blocking mode. |
292 |
|
293 |
socket $txn->{fh}, ...; |
294 |
fcntl $txn->{fh}, F_SETFL, O_NONBLOCK; |
295 |
connect $txn->{fh}, ... |
296 |
and !$!{EWOULDBLOCK} |
297 |
and !$!{EINPROGRESS} |
298 |
and Carp::croak "unable to connect: $!\n"; |
299 |
|
300 |
Then it creates a write-watcher which gets called whenever an error |
301 |
occurs or the connection succeeds: |
302 |
|
303 |
$txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w }); |
304 |
|
305 |
And returns this transaction object. The "fh_ready_w" callback gets |
306 |
called as soon as the event loop detects that the socket is ready for |
307 |
writing. |
308 |
|
309 |
The "fh_ready_w" method makes the socket blocking again, writes the |
310 |
request data and replaces the watcher by a read watcher (waiting for |
311 |
reply data). The actual code is more complicated, but that doesn't |
312 |
matter for this example: |
313 |
|
314 |
fcntl $txn->{fh}, F_SETFL, 0; |
315 |
syswrite $txn->{fh}, $txn->{request} |
316 |
or die "connection or write error"; |
317 |
$txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r }); |
318 |
|
319 |
Again, "fh_ready_r" waits till all data has arrived, and then stores the |
320 |
result and signals any possible waiters that the request ahs finished: |
321 |
|
322 |
sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf}; |
323 |
|
324 |
if (end-of-file or data complete) { |
325 |
$txn->{result} = $txn->{buf}; |
326 |
$txn->{finished}->broadcast; |
327 |
$txb->{cb}->($txn) of $txn->{cb}; # also call callback |
328 |
} |
329 |
|
330 |
The "result" method, finally, just waits for the finished signal (if the |
331 |
request was already finished, it doesn't wait, of course, and returns |
332 |
the data: |
333 |
|
334 |
$txn->{finished}->wait; |
335 |
return $txn->{result}; |
336 |
|
337 |
The actual code goes further and collects all errors ("die"s, |
338 |
exceptions) that occured during request processing. The "result" method |
339 |
detects wether an exception as thrown (it is stored inside the $txn |
340 |
object) and just throws the exception, which means connection errors and |
341 |
other problems get reported tot he code that tries to use the result, |
342 |
not in a random callback. |
343 |
|
344 |
All of this enables the following usage styles: |
345 |
|
346 |
1. Blocking: |
347 |
|
348 |
my $data = $fcp->client_get ($url); |
349 |
|
350 |
2. Blocking, but parallelizing: |
351 |
|
352 |
my @datas = map $_->result, |
353 |
map $fcp->txn_client_get ($_), |
354 |
@urls; |
355 |
|
356 |
Both blocking examples work without the module user having to know |
357 |
anything about events. |
358 |
|
359 |
3a. Event-based in a main program, using any support Event module: |
360 |
|
361 |
use Event; |
362 |
|
363 |
$fcp->txn_client_get ($url)->cb (sub { |
364 |
my $txn = shift; |
365 |
my $data = $txn->result; |
366 |
... |
367 |
}); |
368 |
|
369 |
Event::loop; |
370 |
|
371 |
3b. The module user could use AnyEvent, too: |
372 |
|
373 |
use AnyEvent; |
374 |
|
375 |
my $quit = AnyEvent->condvar; |
376 |
|
377 |
$fcp->txn_client_get ($url)->cb (sub { |
378 |
... |
379 |
$quit->broadcast; |
380 |
}); |
381 |
|
382 |
$quit->wait; |
383 |
|
384 |
SEE ALSO |
385 |
Event modules: Coro::Event, Coro, Event, Glib::Event, Glib. |
386 |
|
387 |
Implementations: AnyEvent::Impl::Coro, AnyEvent::Impl::Event, |
388 |
AnyEvent::Impl::Glib, AnyEvent::Impl::Tk. |
389 |
|
390 |
Nontrivial usage example: Net::FCP. |
391 |
|
392 |
|