|
|
1 | NAME |
|
|
2 | AnyEvent - provide framework for multiple event loops |
|
|
3 | |
|
|
4 | EV, Event, Coro::EV, Coro::Event, Glib, Tk, Perl - various supported |
|
|
5 | event loops |
|
|
6 | |
|
|
7 | SYNOPSIS |
|
|
8 | use AnyEvent; |
|
|
9 | |
|
|
10 | my $w = AnyEvent->io (fh => $fh, poll => "r|w", cb => sub { |
|
|
11 | ... |
|
|
12 | }); |
|
|
13 | |
|
|
14 | my $w = AnyEvent->timer (after => $seconds, cb => sub { |
|
|
15 | ... |
|
|
16 | }); |
|
|
17 | |
|
|
18 | my $w = AnyEvent->condvar; # stores whether a condition was flagged |
|
|
19 | $w->wait; # enters "main loop" till $condvar gets ->broadcast |
|
|
20 | $w->broadcast; # wake up current and all future wait's |
|
|
21 | |
|
|
22 | WHY YOU SHOULD USE THIS MODULE (OR NOT) |
|
|
23 | Glib, POE, IO::Async, Event... CPAN offers event models by the dozen |
|
|
24 | nowadays. So what is different about AnyEvent? |
|
|
25 | |
|
|
26 | Executive Summary: AnyEvent is *compatible*, AnyEvent is *free of |
|
|
27 | policy* and AnyEvent is *small and efficient*. |
|
|
28 | |
|
|
29 | First and foremost, *AnyEvent is not an event model* itself, it only |
|
|
30 | interfaces to whatever event model the main program happens to use in a |
|
|
31 | pragmatic way. For event models and certain classes of immortals alike, |
|
|
32 | the statement "there can only be one" is a bitter reality: In general, |
|
|
33 | only one event loop can be active at the same time in a process. |
|
|
34 | AnyEvent helps hiding the differences between those event loops. |
|
|
35 | |
|
|
36 | The goal of AnyEvent is to offer module authors the ability to do event |
|
|
37 | programming (waiting for I/O or timer events) without subscribing to a |
|
|
38 | religion, a way of living, and most importantly: without forcing your |
|
|
39 | module users into the same thing by forcing them to use the same event |
|
|
40 | model you use. |
|
|
41 | |
|
|
42 | For modules like POE or IO::Async (which is a total misnomer as it is |
|
|
43 | actually doing all I/O *synchronously*...), using them in your module is |
|
|
44 | like joining a cult: After you joined, you are dependent on them and you |
|
|
45 | cannot use anything else, as it is simply incompatible to everything |
|
|
46 | that isn't itself. What's worse, all the potential users of your module |
|
|
47 | are *also* forced to use the same event loop you use. |
|
|
48 | |
|
|
49 | AnyEvent is different: AnyEvent + POE works fine. AnyEvent + Glib works |
|
|
50 | fine. AnyEvent + Tk works fine etc. etc. but none of these work together |
|
|
51 | with the rest: POE + IO::Async? no go. Tk + Event? no go. Again: if your |
|
|
52 | module uses one of those, every user of your module has to use it, too. |
|
|
53 | But if your module uses AnyEvent, it works transparently with all event |
|
|
54 | models it supports (including stuff like POE and IO::Async, as long as |
|
|
55 | those use one of the supported event loops. It is trivial to add new |
|
|
56 | event loops to AnyEvent, too, so it is future-proof). |
|
|
57 | |
|
|
58 | In addition to being free of having to use *the one and only true event |
|
|
59 | model*, AnyEvent also is free of bloat and policy: with POE or similar |
|
|
60 | modules, you get an enourmous amount of code and strict rules you have |
|
|
61 | to follow. AnyEvent, on the other hand, is lean and up to the point, by |
|
|
62 | only offering the functionality that is necessary, in as thin as a |
|
|
63 | wrapper as technically possible. |
|
|
64 | |
|
|
65 | Of course, if you want lots of policy (this can arguably be somewhat |
|
|
66 | useful) and you want to force your users to use the one and only event |
|
|
67 | model, you should *not* use this module. |
|
|
68 | |
|
|
69 | DESCRIPTION |
|
|
70 | AnyEvent provides an identical interface to multiple event loops. This |
|
|
71 | allows module authors to utilise an event loop without forcing module |
|
|
72 | users to use the same event loop (as only a single event loop can |
|
|
73 | coexist peacefully at any one time). |
|
|
74 | |
|
|
75 | The interface itself is vaguely similar, but not identical to the Event |
|
|
76 | module. |
|
|
77 | |
|
|
78 | During the first call of any watcher-creation method, the module tries |
|
|
79 | to detect the currently loaded event loop by probing whether one of the |
|
|
80 | following modules is already loaded: Coro::EV, Coro::Event, EV, Event, |
|
|
81 | Glib, Tk. The first one found is used. If none are found, the module |
|
|
82 | tries to load these modules in the stated order. The first one that can |
|
|
83 | be successfully loaded will be used. If, after this, still none could be |
|
|
84 | found, AnyEvent will fall back to a pure-perl event loop, which is not |
|
|
85 | very efficient, but should work everywhere. |
|
|
86 | |
|
|
87 | Because AnyEvent first checks for modules that are already loaded, |
|
|
88 | loading an event model explicitly before first using AnyEvent will |
|
|
89 | likely make that model the default. For example: |
|
|
90 | |
|
|
91 | use Tk; |
|
|
92 | use AnyEvent; |
|
|
93 | |
|
|
94 | # .. AnyEvent will likely default to Tk |
|
|
95 | |
|
|
96 | The *likely* means that, if any module loads another event model and |
|
|
97 | starts using it, all bets are off. Maybe you should tell their authors |
|
|
98 | to use AnyEvent so their modules work together with others seamlessly... |
|
|
99 | |
|
|
100 | The pure-perl implementation of AnyEvent is called |
|
|
101 | "AnyEvent::Impl::Perl". Like other event modules you can load it |
|
|
102 | explicitly. |
|
|
103 | |
|
|
104 | WATCHERS |
|
|
105 | AnyEvent has the central concept of a *watcher*, which is an object that |
|
|
106 | stores relevant data for each kind of event you are waiting for, such as |
|
|
107 | the callback to call, the filehandle to watch, etc. |
|
|
108 | |
|
|
109 | These watchers are normal Perl objects with normal Perl lifetime. After |
|
|
110 | creating a watcher it will immediately "watch" for events and invoke the |
|
|
111 | callback when the event occurs (of course, only when the event model is |
|
|
112 | in control). |
|
|
113 | |
|
|
114 | To disable the watcher you have to destroy it (e.g. by setting the |
|
|
115 | variable you store it in to "undef" or otherwise deleting all references |
|
|
116 | to it). |
|
|
117 | |
|
|
118 | All watchers are created by calling a method on the "AnyEvent" class. |
|
|
119 | |
|
|
120 | Many watchers either are used with "recursion" (repeating timers for |
|
|
121 | example), or need to refer to their watcher object in other ways. |
|
|
122 | |
|
|
123 | An any way to achieve that is this pattern: |
|
|
124 | |
|
|
125 | my $w; $w = AnyEvent->type (arg => value ..., cb => sub { |
|
|
126 | # you can use $w here, for example to undef it |
|
|
127 | undef $w; |
|
|
128 | }); |
|
|
129 | |
|
|
130 | Note that "my $w; $w =" combination. This is necessary because in Perl, |
|
|
131 | my variables are only visible after the statement in which they are |
|
|
132 | declared. |
|
|
133 | |
|
|
134 | IO WATCHERS |
|
|
135 | You can create an I/O watcher by calling the "AnyEvent->io" method with |
|
|
136 | the following mandatory key-value pairs as arguments: |
|
|
137 | |
|
|
138 | "fh" the Perl *file handle* (*not* file descriptor) to watch for events. |
|
|
139 | "poll" must be a string that is either "r" or "w", which creates a |
|
|
140 | watcher waiting for "r"eadable or "w"ritable events, respectively. "cb" |
|
|
141 | is the callback to invoke each time the file handle becomes ready. |
|
|
142 | |
|
|
143 | File handles will be kept alive, so as long as the watcher exists, the |
|
|
144 | file handle exists, too. |
|
|
145 | |
|
|
146 | It is not allowed to close a file handle as long as any watcher is |
|
|
147 | active on the underlying file descriptor. |
|
|
148 | |
|
|
149 | Some event loops issue spurious readyness notifications, so you should |
|
|
150 | always use non-blocking calls when reading/writing from/to your file |
|
|
151 | handles. |
|
|
152 | |
|
|
153 | Example: |
|
|
154 | |
|
|
155 | # wait for readability of STDIN, then read a line and disable the watcher |
|
|
156 | my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub { |
|
|
157 | chomp (my $input = <STDIN>); |
|
|
158 | warn "read: $input\n"; |
|
|
159 | undef $w; |
|
|
160 | }); |
|
|
161 | |
|
|
162 | TIME WATCHERS |
|
|
163 | You can create a time watcher by calling the "AnyEvent->timer" method |
|
|
164 | with the following mandatory arguments: |
|
|
165 | |
|
|
166 | "after" specifies after how many seconds (fractional values are |
|
|
167 | supported) should the timer activate. "cb" the callback to invoke in |
|
|
168 | that case. |
|
|
169 | |
|
|
170 | The timer callback will be invoked at most once: if you want a repeating |
|
|
171 | timer you have to create a new watcher (this is a limitation by both Tk |
|
|
172 | and Glib). |
|
|
173 | |
|
|
174 | Example: |
|
|
175 | |
|
|
176 | # fire an event after 7.7 seconds |
|
|
177 | my $w = AnyEvent->timer (after => 7.7, cb => sub { |
|
|
178 | warn "timeout\n"; |
|
|
179 | }); |
|
|
180 | |
|
|
181 | # to cancel the timer: |
|
|
182 | undef $w; |
|
|
183 | |
|
|
184 | Example 2: |
|
|
185 | |
|
|
186 | # fire an event after 0.5 seconds, then roughly every second |
|
|
187 | my $w; |
|
|
188 | |
|
|
189 | my $cb = sub { |
|
|
190 | # cancel the old timer while creating a new one |
|
|
191 | $w = AnyEvent->timer (after => 1, cb => $cb); |
|
|
192 | }; |
|
|
193 | |
|
|
194 | # start the "loop" by creating the first watcher |
|
|
195 | $w = AnyEvent->timer (after => 0.5, cb => $cb); |
|
|
196 | |
|
|
197 | TIMING ISSUES |
|
|
198 | There are two ways to handle timers: based on real time (relative, "fire |
|
|
199 | in 10 seconds") and based on wallclock time (absolute, "fire at 12 |
|
|
200 | o'clock"). |
|
|
201 | |
|
|
202 | While most event loops expect timers to specified in a relative way, |
|
|
203 | they use absolute time internally. This makes a difference when your |
|
|
204 | clock "jumps", for example, when ntp decides to set your clock backwards |
|
|
205 | from the wrong 2014-01-01 to 2008-01-01, a watcher that you created to |
|
|
206 | fire "after" a second might actually take six years to finally fire. |
|
|
207 | |
|
|
208 | AnyEvent cannot compensate for this. The only event loop that is |
|
|
209 | conscious about these issues is EV, which offers both relative |
|
|
210 | (ev_timer) and absolute (ev_periodic) timers. |
|
|
211 | |
|
|
212 | AnyEvent always prefers relative timers, if available, matching the |
|
|
213 | AnyEvent API. |
|
|
214 | |
|
|
215 | SIGNAL WATCHERS |
|
|
216 | You can watch for signals using a signal watcher, "signal" is the signal |
|
|
217 | *name* without any "SIG" prefix, "cb" is the Perl callback to be invoked |
|
|
218 | whenever a signal occurs. |
|
|
219 | |
|
|
220 | Multiple signals occurances can be clumped together into one callback |
|
|
221 | invocation, and callback invocation will be synchronous. synchronous |
|
|
222 | means that it might take a while until the signal gets handled by the |
|
|
223 | process, but it is guarenteed not to interrupt any other callbacks. |
|
|
224 | |
|
|
225 | The main advantage of using these watchers is that you can share a |
|
|
226 | signal between multiple watchers. |
|
|
227 | |
|
|
228 | This watcher might use %SIG, so programs overwriting those signals |
|
|
229 | directly will likely not work correctly. |
|
|
230 | |
|
|
231 | Example: exit on SIGINT |
|
|
232 | |
|
|
233 | my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 }); |
|
|
234 | |
|
|
235 | CHILD PROCESS WATCHERS |
|
|
236 | You can also watch on a child process exit and catch its exit status. |
|
|
237 | |
|
|
238 | The child process is specified by the "pid" argument (if set to 0, it |
|
|
239 | watches for any child process exit). The watcher will trigger as often |
|
|
240 | as status change for the child are received. This works by installing a |
|
|
241 | signal handler for "SIGCHLD". The callback will be called with the pid |
|
|
242 | and exit status (as returned by waitpid). |
|
|
243 | |
|
|
244 | Example: wait for pid 1333 |
|
|
245 | |
|
|
246 | my $w = AnyEvent->child ( |
|
|
247 | pid => 1333, |
|
|
248 | cb => sub { |
|
|
249 | my ($pid, $status) = @_; |
|
|
250 | warn "pid $pid exited with status $status"; |
|
|
251 | }, |
|
|
252 | ); |
|
|
253 | |
|
|
254 | CONDITION VARIABLES |
|
|
255 | Condition variables can be created by calling the "AnyEvent->condvar" |
|
|
256 | method without any arguments. |
|
|
257 | |
|
|
258 | A condition variable waits for a condition - precisely that the |
|
|
259 | "->broadcast" method has been called. |
|
|
260 | |
|
|
261 | They are very useful to signal that a condition has been fulfilled, for |
|
|
262 | example, if you write a module that does asynchronous http requests, |
|
|
263 | then a condition variable would be the ideal candidate to signal the |
|
|
264 | availability of results. |
|
|
265 | |
|
|
266 | You can also use condition variables to block your main program until an |
|
|
267 | event occurs - for example, you could "->wait" in your main program |
|
|
268 | until the user clicks the Quit button in your app, which would |
|
|
269 | "->broadcast" the "quit" event. |
|
|
270 | |
|
|
271 | Note that condition variables recurse into the event loop - if you have |
|
|
272 | two pirces of code that call "->wait" in a round-robbin fashion, you |
|
|
273 | lose. Therefore, condition variables are good to export to your caller, |
|
|
274 | but you should avoid making a blocking wait yourself, at least in |
|
|
275 | callbacks, as this asks for trouble. |
|
|
276 | |
|
|
277 | This object has two methods: |
|
|
278 | |
|
|
279 | $cv->wait |
|
|
280 | Wait (blocking if necessary) until the "->broadcast" method has been |
|
|
281 | called on c<$cv>, while servicing other watchers normally. |
|
|
282 | |
|
|
283 | You can only wait once on a condition - additional calls will return |
|
|
284 | immediately. |
|
|
285 | |
|
|
286 | Not all event models support a blocking wait - some die in that case |
|
|
287 | (programs might want to do that to stay interactive), so *if you are |
|
|
288 | using this from a module, never require a blocking wait*, but let |
|
|
289 | the caller decide whether the call will block or not (for example, |
|
|
290 | by coupling condition variables with some kind of request results |
|
|
291 | and supporting callbacks so the caller knows that getting the result |
|
|
292 | will not block, while still suppporting blocking waits if the caller |
|
|
293 | so desires). |
|
|
294 | |
|
|
295 | Another reason *never* to "->wait" in a module is that you cannot |
|
|
296 | sensibly have two "->wait"'s in parallel, as that would require |
|
|
297 | multiple interpreters or coroutines/threads, none of which |
|
|
298 | "AnyEvent" can supply (the coroutine-aware backends |
|
|
299 | AnyEvent::Impl::CoroEV and AnyEvent::Impl::CoroEvent explicitly |
|
|
300 | support concurrent "->wait"'s from different coroutines, however). |
|
|
301 | |
|
|
302 | $cv->broadcast |
|
|
303 | Flag the condition as ready - a running "->wait" and all further |
|
|
304 | calls to "wait" will (eventually) return after this method has been |
|
|
305 | called. If nobody is waiting the broadcast will be remembered.. |
|
|
306 | |
|
|
307 | Example: |
|
|
308 | |
|
|
309 | # wait till the result is ready |
|
|
310 | my $result_ready = AnyEvent->condvar; |
|
|
311 | |
|
|
312 | # do something such as adding a timer |
|
|
313 | # or socket watcher the calls $result_ready->broadcast |
|
|
314 | # when the "result" is ready. |
|
|
315 | # in this case, we simply use a timer: |
|
|
316 | my $w = AnyEvent->timer ( |
|
|
317 | after => 1, |
|
|
318 | cb => sub { $result_ready->broadcast }, |
|
|
319 | ); |
|
|
320 | |
|
|
321 | # this "blocks" (while handling events) till the watcher |
|
|
322 | # calls broadcast |
|
|
323 | $result_ready->wait; |
|
|
324 | |
|
|
325 | GLOBAL VARIABLES AND FUNCTIONS |
|
|
326 | $AnyEvent::MODEL |
|
|
327 | Contains "undef" until the first watcher is being created. Then it |
|
|
328 | contains the event model that is being used, which is the name of |
|
|
329 | the Perl class implementing the model. This class is usually one of |
|
|
330 | the "AnyEvent::Impl:xxx" modules, but can be any other class in the |
|
|
331 | case AnyEvent has been extended at runtime (e.g. in *rxvt-unicode*). |
|
|
332 | |
|
|
333 | The known classes so far are: |
|
|
334 | |
|
|
335 | AnyEvent::Impl::CoroEV based on Coro::EV, best choice. |
|
|
336 | AnyEvent::Impl::CoroEvent based on Coro::Event, second best choice. |
|
|
337 | AnyEvent::Impl::EV based on EV (an interface to libev, also best choice). |
|
|
338 | AnyEvent::Impl::Event based on Event, also second best choice :) |
|
|
339 | AnyEvent::Impl::Glib based on Glib, third-best choice. |
|
|
340 | AnyEvent::Impl::Tk based on Tk, very bad choice. |
|
|
341 | AnyEvent::Impl::Perl pure-perl implementation, inefficient but portable. |
|
|
342 | |
|
|
343 | AnyEvent::detect |
|
|
344 | Returns $AnyEvent::MODEL, forcing autodetection of the event model |
|
|
345 | if necessary. You should only call this function right before you |
|
|
346 | would have created an AnyEvent watcher anyway, that is, as late as |
|
|
347 | possible at runtime. |
|
|
348 | |
|
|
349 | WHAT TO DO IN A MODULE |
|
|
350 | As a module author, you should "use AnyEvent" and call AnyEvent methods |
|
|
351 | freely, but you should not load a specific event module or rely on it. |
|
|
352 | |
|
|
353 | Be careful when you create watchers in the module body - AnyEvent will |
|
|
354 | decide which event module to use as soon as the first method is called, |
|
|
355 | so by calling AnyEvent in your module body you force the user of your |
|
|
356 | module to load the event module first. |
|
|
357 | |
|
|
358 | Never call "->wait" on a condition variable unless you *know* that the |
|
|
359 | "->broadcast" method has been called on it already. This is because it |
|
|
360 | will stall the whole program, and the whole point of using events is to |
|
|
361 | stay interactive. |
|
|
362 | |
|
|
363 | It is fine, however, to call "->wait" when the user of your module |
|
|
364 | requests it (i.e. if you create a http request object ad have a method |
|
|
365 | called "results" that returns the results, it should call "->wait" |
|
|
366 | freely, as the user of your module knows what she is doing. always). |
|
|
367 | |
|
|
368 | WHAT TO DO IN THE MAIN PROGRAM |
|
|
369 | There will always be a single main program - the only place that should |
|
|
370 | dictate which event model to use. |
|
|
371 | |
|
|
372 | If it doesn't care, it can just "use AnyEvent" and use it itself, or not |
|
|
373 | do anything special (it does not need to be event-based) and let |
|
|
374 | AnyEvent decide which implementation to chose if some module relies on |
|
|
375 | it. |
|
|
376 | |
|
|
377 | If the main program relies on a specific event model. For example, in |
|
|
378 | Gtk2 programs you have to rely on the Glib module. You should load the |
|
|
379 | event module before loading AnyEvent or any module that uses it: |
|
|
380 | generally speaking, you should load it as early as possible. The reason |
|
|
381 | is that modules might create watchers when they are loaded, and AnyEvent |
|
|
382 | will decide on the event model to use as soon as it creates watchers, |
|
|
383 | and it might chose the wrong one unless you load the correct one |
|
|
384 | yourself. |
|
|
385 | |
|
|
386 | You can chose to use a rather inefficient pure-perl implementation by |
|
|
387 | loading the "AnyEvent::Impl::Perl" module, which gives you similar |
|
|
388 | behaviour everywhere, but letting AnyEvent chose is generally better. |
|
|
389 | |
|
|
390 | SUPPLYING YOUR OWN EVENT MODEL INTERFACE |
|
|
391 | This is an advanced topic that you do not normally need to use AnyEvent |
|
|
392 | in a module. This section is only of use to event loop authors who want |
|
|
393 | to provide AnyEvent compatibility. |
|
|
394 | |
|
|
395 | If you need to support another event library which isn't directly |
|
|
396 | supported by AnyEvent, you can supply your own interface to it by |
|
|
397 | pushing, before the first watcher gets created, the package name of the |
|
|
398 | event module and the package name of the interface to use onto |
|
|
399 | @AnyEvent::REGISTRY. You can do that before and even without loading |
|
|
400 | AnyEvent, so it is reasonably cheap. |
|
|
401 | |
|
|
402 | Example: |
|
|
403 | |
|
|
404 | push @AnyEvent::REGISTRY, [urxvt => urxvt::anyevent::]; |
|
|
405 | |
|
|
406 | This tells AnyEvent to (literally) use the "urxvt::anyevent::" |
|
|
407 | package/class when it finds the "urxvt" package/module is already |
|
|
408 | loaded. |
|
|
409 | |
|
|
410 | When AnyEvent is loaded and asked to find a suitable event model, it |
|
|
411 | will first check for the presence of urxvt by trying to "use" the |
|
|
412 | "urxvt::anyevent" module. |
|
|
413 | |
|
|
414 | The class should provide implementations for all watcher types. See |
|
|
415 | AnyEvent::Impl::EV (source code), AnyEvent::Impl::Glib (Source code) and |
|
|
416 | so on for actual examples. Use "perldoc -m AnyEvent::Impl::Glib" to see |
|
|
417 | the sources. |
|
|
418 | |
|
|
419 | If you don't provide "signal" and "child" watchers than AnyEvent will |
|
|
420 | provide suitable (hopefully) replacements. |
|
|
421 | |
|
|
422 | The above example isn't fictitious, the *rxvt-unicode* (a.k.a. urxvt) |
|
|
423 | terminal emulator uses the above line as-is. An interface isn't included |
|
|
424 | in AnyEvent because it doesn't make sense outside the embedded |
|
|
425 | interpreter inside *rxvt-unicode*, and it is updated and maintained as |
|
|
426 | part of the *rxvt-unicode* distribution. |
|
|
427 | |
|
|
428 | *rxvt-unicode* also cheats a bit by not providing blocking access to |
|
|
429 | condition variables: code blocking while waiting for a condition will |
|
|
430 | "die". This still works with most modules/usages, and blocking calls |
|
|
431 | must not be done in an interactive application, so it makes sense. |
|
|
432 | |
|
|
433 | ENVIRONMENT VARIABLES |
|
|
434 | The following environment variables are used by this module: |
|
|
435 | |
|
|
436 | "PERL_ANYEVENT_VERBOSE" when set to 2 or higher, cause AnyEvent to |
|
|
437 | report to STDERR which event model it chooses. |
|
|
438 | |
|
|
439 | EXAMPLE PROGRAM |
|
|
440 | The following program uses an IO watcher to read data from STDIN, a |
|
|
441 | timer to display a message once per second, and a condition variable to |
|
|
442 | quit the program when the user enters quit: |
|
|
443 | |
|
|
444 | use AnyEvent; |
|
|
445 | |
|
|
446 | my $cv = AnyEvent->condvar; |
|
|
447 | |
|
|
448 | my $io_watcher = AnyEvent->io ( |
|
|
449 | fh => \*STDIN, |
|
|
450 | poll => 'r', |
|
|
451 | cb => sub { |
|
|
452 | warn "io event <$_[0]>\n"; # will always output <r> |
|
|
453 | chomp (my $input = <STDIN>); # read a line |
|
|
454 | warn "read: $input\n"; # output what has been read |
|
|
455 | $cv->broadcast if $input =~ /^q/i; # quit program if /^q/i |
|
|
456 | }, |
|
|
457 | ); |
|
|
458 | |
|
|
459 | my $time_watcher; # can only be used once |
|
|
460 | |
|
|
461 | sub new_timer { |
|
|
462 | $timer = AnyEvent->timer (after => 1, cb => sub { |
|
|
463 | warn "timeout\n"; # print 'timeout' about every second |
|
|
464 | &new_timer; # and restart the time |
|
|
465 | }); |
|
|
466 | } |
|
|
467 | |
|
|
468 | new_timer; # create first timer |
|
|
469 | |
|
|
470 | $cv->wait; # wait until user enters /^q/i |
|
|
471 | |
|
|
472 | REAL-WORLD EXAMPLE |
|
|
473 | Consider the Net::FCP module. It features (among others) the following |
|
|
474 | API calls, which are to freenet what HTTP GET requests are to http: |
|
|
475 | |
|
|
476 | my $data = $fcp->client_get ($url); # blocks |
|
|
477 | |
|
|
478 | my $transaction = $fcp->txn_client_get ($url); # does not block |
|
|
479 | $transaction->cb ( sub { ... } ); # set optional result callback |
|
|
480 | my $data = $transaction->result; # possibly blocks |
|
|
481 | |
|
|
482 | The "client_get" method works like "LWP::Simple::get": it requests the |
|
|
483 | given URL and waits till the data has arrived. It is defined to be: |
|
|
484 | |
|
|
485 | sub client_get { $_[0]->txn_client_get ($_[1])->result } |
|
|
486 | |
|
|
487 | And in fact is automatically generated. This is the blocking API of |
|
|
488 | Net::FCP, and it works as simple as in any other, similar, module. |
|
|
489 | |
|
|
490 | More complicated is "txn_client_get": It only creates a transaction |
|
|
491 | (completion, result, ...) object and initiates the transaction. |
|
|
492 | |
|
|
493 | my $txn = bless { }, Net::FCP::Txn::; |
|
|
494 | |
|
|
495 | It also creates a condition variable that is used to signal the |
|
|
496 | completion of the request: |
|
|
497 | |
|
|
498 | $txn->{finished} = AnyAvent->condvar; |
|
|
499 | |
|
|
500 | It then creates a socket in non-blocking mode. |
|
|
501 | |
|
|
502 | socket $txn->{fh}, ...; |
|
|
503 | fcntl $txn->{fh}, F_SETFL, O_NONBLOCK; |
|
|
504 | connect $txn->{fh}, ... |
|
|
505 | and !$!{EWOULDBLOCK} |
|
|
506 | and !$!{EINPROGRESS} |
|
|
507 | and Carp::croak "unable to connect: $!\n"; |
|
|
508 | |
|
|
509 | Then it creates a write-watcher which gets called whenever an error |
|
|
510 | occurs or the connection succeeds: |
|
|
511 | |
|
|
512 | $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'w', cb => sub { $txn->fh_ready_w }); |
|
|
513 | |
|
|
514 | And returns this transaction object. The "fh_ready_w" callback gets |
|
|
515 | called as soon as the event loop detects that the socket is ready for |
|
|
516 | writing. |
|
|
517 | |
|
|
518 | The "fh_ready_w" method makes the socket blocking again, writes the |
|
|
519 | request data and replaces the watcher by a read watcher (waiting for |
|
|
520 | reply data). The actual code is more complicated, but that doesn't |
|
|
521 | matter for this example: |
|
|
522 | |
|
|
523 | fcntl $txn->{fh}, F_SETFL, 0; |
|
|
524 | syswrite $txn->{fh}, $txn->{request} |
|
|
525 | or die "connection or write error"; |
|
|
526 | $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r }); |
|
|
527 | |
|
|
528 | Again, "fh_ready_r" waits till all data has arrived, and then stores the |
|
|
529 | result and signals any possible waiters that the request ahs finished: |
|
|
530 | |
|
|
531 | sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf}; |
|
|
532 | |
|
|
533 | if (end-of-file or data complete) { |
|
|
534 | $txn->{result} = $txn->{buf}; |
|
|
535 | $txn->{finished}->broadcast; |
|
|
536 | $txb->{cb}->($txn) of $txn->{cb}; # also call callback |
|
|
537 | } |
|
|
538 | |
|
|
539 | The "result" method, finally, just waits for the finished signal (if the |
|
|
540 | request was already finished, it doesn't wait, of course, and returns |
|
|
541 | the data: |
|
|
542 | |
|
|
543 | $txn->{finished}->wait; |
|
|
544 | return $txn->{result}; |
|
|
545 | |
|
|
546 | The actual code goes further and collects all errors ("die"s, |
|
|
547 | exceptions) that occured during request processing. The "result" method |
|
|
548 | detects whether an exception as thrown (it is stored inside the $txn |
|
|
549 | object) and just throws the exception, which means connection errors and |
|
|
550 | other problems get reported tot he code that tries to use the result, |
|
|
551 | not in a random callback. |
|
|
552 | |
|
|
553 | All of this enables the following usage styles: |
|
|
554 | |
|
|
555 | 1. Blocking: |
|
|
556 | |
|
|
557 | my $data = $fcp->client_get ($url); |
|
|
558 | |
|
|
559 | 2. Blocking, but running in parallel: |
|
|
560 | |
|
|
561 | my @datas = map $_->result, |
|
|
562 | map $fcp->txn_client_get ($_), |
|
|
563 | @urls; |
|
|
564 | |
|
|
565 | Both blocking examples work without the module user having to know |
|
|
566 | anything about events. |
|
|
567 | |
|
|
568 | 3a. Event-based in a main program, using any supported event module: |
|
|
569 | |
|
|
570 | use EV; |
|
|
571 | |
|
|
572 | $fcp->txn_client_get ($url)->cb (sub { |
|
|
573 | my $txn = shift; |
|
|
574 | my $data = $txn->result; |
|
|
575 | ... |
|
|
576 | }); |
|
|
577 | |
|
|
578 | EV::loop; |
|
|
579 | |
|
|
580 | 3b. The module user could use AnyEvent, too: |
|
|
581 | |
|
|
582 | use AnyEvent; |
|
|
583 | |
|
|
584 | my $quit = AnyEvent->condvar; |
|
|
585 | |
|
|
586 | $fcp->txn_client_get ($url)->cb (sub { |
|
|
587 | ... |
|
|
588 | $quit->broadcast; |
|
|
589 | }); |
|
|
590 | |
|
|
591 | $quit->wait; |
|
|
592 | |
|
|
593 | SEE ALSO |
|
|
594 | Event modules: Coro::EV, EV, EV::Glib, Glib::EV, Coro::Event, Event, |
|
|
595 | Glib::Event, Glib, Coro, Tk. |
|
|
596 | |
|
|
597 | Implementations: AnyEvent::Impl::CoroEV, AnyEvent::Impl::EV, |
|
|
598 | AnyEvent::Impl::CoroEvent, AnyEvent::Impl::Event, AnyEvent::Impl::Glib, |
|
|
599 | AnyEvent::Impl::Tk, AnyEvent::Impl::Perl. |
|
|
600 | |
|
|
601 | Nontrivial usage examples: Net::FCP, Net::XMPP2. |
|
|
602 | |
|
|
603 | |