ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/README
(Generate patch)

Comparing AnyEvent/README (file contents):
Revision 1.14 by root, Mon Apr 7 19:46:50 2008 UTC vs.
Revision 1.18 by root, Thu Apr 24 09:13:26 2008 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines