1 | =head1 NAME |
1 | =head1 => NAME |
2 | |
2 | |
3 | AnyEvent - provide framework for multiple event loops |
3 | AnyEvent - provide framework for multiple event loops |
4 | |
4 | |
5 | EV, Event, Coro::EV, Coro::Event, Glib, Tk, Perl, Event::Lib, Qt, POE - various supported event loops |
5 | EV, Event, Glib, Tk, Perl, Event::Lib, Qt, POE - various supported event loops |
6 | |
6 | |
7 | =head1 SYNOPSIS |
7 | =head1 SYNOPSIS |
8 | |
8 | |
9 | use AnyEvent; |
9 | use AnyEvent; |
10 | |
10 | |
… | |
… | |
15 | my $w = AnyEvent->timer (after => $seconds, cb => sub { |
15 | my $w = AnyEvent->timer (after => $seconds, cb => sub { |
16 | ... |
16 | ... |
17 | }); |
17 | }); |
18 | |
18 | |
19 | my $w = AnyEvent->condvar; # stores whether a condition was flagged |
19 | my $w = AnyEvent->condvar; # stores whether a condition was flagged |
|
|
20 | $w->send; # wake up current and all future recv's |
20 | $w->wait; # enters "main loop" till $condvar gets ->broadcast |
21 | $w->recv; # enters "main loop" till $condvar gets ->send |
21 | $w->broadcast; # wake up current and all future wait's |
|
|
22 | |
22 | |
23 | =head1 WHY YOU SHOULD USE THIS MODULE (OR NOT) |
23 | =head1 WHY YOU SHOULD USE THIS MODULE (OR NOT) |
24 | |
24 | |
25 | Glib, POE, IO::Async, Event... CPAN offers event models by the dozen |
25 | Glib, POE, IO::Async, Event... CPAN offers event models by the dozen |
26 | nowadays. So what is different about AnyEvent? |
26 | nowadays. So what is different about AnyEvent? |
… | |
… | |
57 | as those use one of the supported event loops. It is trivial to add new |
57 | as those use one of the supported event loops. It is trivial to add new |
58 | event loops to AnyEvent, too, so it is future-proof). |
58 | event loops to AnyEvent, too, so it is future-proof). |
59 | |
59 | |
60 | In addition to being free of having to use I<the one and only true event |
60 | In addition to being free of having to use I<the one and only true event |
61 | model>, AnyEvent also is free of bloat and policy: with POE or similar |
61 | model>, AnyEvent also is free of bloat and policy: with POE or similar |
62 | modules, you get an enourmous amount of code and strict rules you have to |
62 | modules, you get an enormous amount of code and strict rules you have to |
63 | follow. AnyEvent, on the other hand, is lean and up to the point, by only |
63 | follow. AnyEvent, on the other hand, is lean and up to the point, by only |
64 | offering the functionality that is necessary, in as thin as a wrapper as |
64 | offering the functionality that is necessary, in as thin as a wrapper as |
65 | technically possible. |
65 | technically possible. |
66 | |
66 | |
67 | Of course, if you want lots of policy (this can arguably be somewhat |
67 | Of course, if you want lots of policy (this can arguably be somewhat |
… | |
… | |
78 | The interface itself is vaguely similar, but not identical to the L<Event> |
78 | The interface itself is vaguely similar, but not identical to the L<Event> |
79 | module. |
79 | module. |
80 | |
80 | |
81 | During the first call of any watcher-creation method, the module tries |
81 | During the first call of any watcher-creation method, the module tries |
82 | to detect the currently loaded event loop by probing whether one of the |
82 | to detect the currently loaded event loop by probing whether one of the |
83 | following modules is already loaded: L<Coro::EV>, L<Coro::Event>, L<EV>, |
83 | following modules is already loaded: L<EV>, |
84 | L<Event>, L<Glib>, L<AnyEvent::Impl::Perl>, L<Tk>, L<Event::Lib>, L<Qt>, |
84 | L<Event>, L<Glib>, L<AnyEvent::Impl::Perl>, L<Tk>, L<Event::Lib>, L<Qt>, |
85 | L<POE>. The first one found is used. If none are found, the module tries |
85 | L<POE>. The first one found is used. If none are found, the module tries |
86 | to load these modules (excluding Tk, Event::Lib, Qt and POE as the pure perl |
86 | to load these modules (excluding Tk, Event::Lib, Qt and POE as the pure perl |
87 | adaptor should always succeed) in the order given. The first one that can |
87 | adaptor should always succeed) in the order given. The first one that can |
88 | be successfully loaded will be used. If, after this, still none could be |
88 | be successfully loaded will be used. If, after this, still none could be |
… | |
… | |
108 | |
108 | |
109 | =head1 WATCHERS |
109 | =head1 WATCHERS |
110 | |
110 | |
111 | AnyEvent has the central concept of a I<watcher>, which is an object that |
111 | AnyEvent has the central concept of a I<watcher>, which is an object that |
112 | stores relevant data for each kind of event you are waiting for, such as |
112 | stores relevant data for each kind of event you are waiting for, such as |
113 | the callback to call, the filehandle to watch, etc. |
113 | the callback to call, the file handle to watch, etc. |
114 | |
114 | |
115 | These watchers are normal Perl objects with normal Perl lifetime. After |
115 | These watchers are normal Perl objects with normal Perl lifetime. After |
116 | creating a watcher it will immediately "watch" for events and invoke the |
116 | creating a watcher it will immediately "watch" for events and invoke the |
117 | callback when the event occurs (of course, only when the event model |
117 | callback when the event occurs (of course, only when the event model |
118 | is in control). |
118 | is in control). |
… | |
… | |
237 | |
237 | |
238 | Although the callback might get passed parameters, their value and |
238 | Although the callback might get passed parameters, their value and |
239 | presence is undefined and you cannot rely on them. Portable AnyEvent |
239 | presence is undefined and you cannot rely on them. Portable AnyEvent |
240 | callbacks cannot use arguments passed to signal watcher callbacks. |
240 | callbacks cannot use arguments passed to signal watcher callbacks. |
241 | |
241 | |
242 | Multiple signal occurances can be clumped together into one callback |
242 | Multiple signal occurrences can be clumped together into one callback |
243 | invocation, and callback invocation will be synchronous. synchronous means |
243 | invocation, and callback invocation will be synchronous. Synchronous means |
244 | that it might take a while until the signal gets handled by the process, |
244 | that it might take a while until the signal gets handled by the process, |
245 | but it is guarenteed not to interrupt any other callbacks. |
245 | but it is guaranteed not to interrupt any other callbacks. |
246 | |
246 | |
247 | The main advantage of using these watchers is that you can share a signal |
247 | The main advantage of using these watchers is that you can share a signal |
248 | between multiple watchers. |
248 | between multiple watchers. |
249 | |
249 | |
250 | This watcher might use C<%SIG>, so programs overwriting those signals |
250 | This watcher might use C<%SIG>, so programs overwriting those signals |
… | |
… | |
279 | |
279 | |
280 | Example: fork a process and wait for it |
280 | Example: fork a process and wait for it |
281 | |
281 | |
282 | my $done = AnyEvent->condvar; |
282 | my $done = AnyEvent->condvar; |
283 | |
283 | |
284 | AnyEvent::detect; # force event module to be initialised |
|
|
285 | |
|
|
286 | my $pid = fork or exit 5; |
284 | my $pid = fork or exit 5; |
287 | |
285 | |
288 | my $w = AnyEvent->child ( |
286 | my $w = AnyEvent->child ( |
289 | pid => $pid, |
287 | pid => $pid, |
290 | cb => sub { |
288 | cb => sub { |
291 | my ($pid, $status) = @_; |
289 | my ($pid, $status) = @_; |
292 | warn "pid $pid exited with status $status"; |
290 | warn "pid $pid exited with status $status"; |
293 | $done->broadcast; |
291 | $done->send; |
294 | }, |
292 | }, |
295 | ); |
293 | ); |
296 | |
294 | |
297 | # do something else, then wait for process exit |
295 | # do something else, then wait for process exit |
298 | $done->wait; |
296 | $done->recv; |
299 | |
297 | |
300 | =head2 CONDITION VARIABLES |
298 | =head2 CONDITION VARIABLES |
301 | |
299 | |
|
|
300 | If you are familiar with some event loops you will know that all of them |
|
|
301 | require you to run some blocking "loop", "run" or similar function that |
|
|
302 | will actively watch for new events and call your callbacks. |
|
|
303 | |
|
|
304 | AnyEvent is different, it expects somebody else to run the event loop and |
|
|
305 | will only block when necessary (usually when told by the user). |
|
|
306 | |
|
|
307 | The instrument to do that is called a "condition variable", so called |
|
|
308 | because they represent a condition that must become true. |
|
|
309 | |
302 | Condition variables can be created by calling the C<< AnyEvent->condvar >> |
310 | Condition variables can be created by calling the C<< AnyEvent->condvar |
303 | method without any arguments. |
311 | >> method, usually without arguments. The only argument pair allowed is |
|
|
312 | C<cb>, which specifies a callback to be called when the condition variable |
|
|
313 | becomes true. |
304 | |
314 | |
305 | A condition variable waits for a condition - precisely that the C<< |
315 | After creation, the condition variable is "false" until it becomes "true" |
306 | ->broadcast >> method has been called. |
316 | by calling the C<send> method (or calling the condition variable as if it |
|
|
317 | were a callback). |
307 | |
318 | |
308 | They are very useful to signal that a condition has been fulfilled, for |
319 | Condition variables are similar to callbacks, except that you can |
|
|
320 | optionally wait for them. They can also be called merge points - points |
|
|
321 | in time where multiple outstanding events have been processed. And yet |
|
|
322 | another way to call them is transactions - each condition variable can be |
|
|
323 | used to represent a transaction, which finishes at some point and delivers |
|
|
324 | a result. |
|
|
325 | |
|
|
326 | Condition variables are very useful to signal that something has finished, |
309 | example, if you write a module that does asynchronous http requests, |
327 | for example, if you write a module that does asynchronous http requests, |
310 | then a condition variable would be the ideal candidate to signal the |
328 | then a condition variable would be the ideal candidate to signal the |
311 | availability of results. |
329 | availability of results. The user can either act when the callback is |
|
|
330 | called or can synchronously C<< ->recv >> for the results. |
312 | |
331 | |
313 | You can also use condition variables to block your main program until |
332 | You can also use them to simulate traditional event loops - for example, |
314 | an event occurs - for example, you could C<< ->wait >> in your main |
333 | you can block your main program until an event occurs - for example, you |
315 | program until the user clicks the Quit button in your app, which would C<< |
334 | could C<< ->recv >> in your main program until the user clicks the Quit |
316 | ->broadcast >> the "quit" event. |
335 | button of your app, which would C<< ->send >> the "quit" event. |
317 | |
336 | |
318 | Note that condition variables recurse into the event loop - if you have |
337 | Note that condition variables recurse into the event loop - if you have |
319 | two pirces of code that call C<< ->wait >> in a round-robbin fashion, you |
338 | two pieces of code that call C<< ->recv >> in a round-robin fashion, you |
320 | lose. Therefore, condition variables are good to export to your caller, but |
339 | lose. Therefore, condition variables are good to export to your caller, but |
321 | you should avoid making a blocking wait yourself, at least in callbacks, |
340 | you should avoid making a blocking wait yourself, at least in callbacks, |
322 | as this asks for trouble. |
341 | as this asks for trouble. |
323 | |
342 | |
324 | This object has two methods: |
343 | Condition variables are represented by hash refs in perl, and the keys |
|
|
344 | used by AnyEvent itself are all named C<_ae_XXX> to make subclassing |
|
|
345 | easy (it is often useful to build your own transaction class on top of |
|
|
346 | AnyEvent). To subclass, use C<AnyEvent::CondVar> as base class and call |
|
|
347 | it's C<new> method in your own C<new> method. |
|
|
348 | |
|
|
349 | There are two "sides" to a condition variable - the "producer side" which |
|
|
350 | eventually calls C<< -> send >>, and the "consumer side", which waits |
|
|
351 | for the send to occur. |
|
|
352 | |
|
|
353 | Example: wait for a timer. |
|
|
354 | |
|
|
355 | # wait till the result is ready |
|
|
356 | my $result_ready = AnyEvent->condvar; |
|
|
357 | |
|
|
358 | # do something such as adding a timer |
|
|
359 | # or socket watcher the calls $result_ready->send |
|
|
360 | # when the "result" is ready. |
|
|
361 | # in this case, we simply use a timer: |
|
|
362 | my $w = AnyEvent->timer ( |
|
|
363 | after => 1, |
|
|
364 | cb => sub { $result_ready->send }, |
|
|
365 | ); |
|
|
366 | |
|
|
367 | # this "blocks" (while handling events) till the callback |
|
|
368 | # calls send |
|
|
369 | $result_ready->recv; |
|
|
370 | |
|
|
371 | Example: wait for a timer, but take advantage of the fact that |
|
|
372 | condition variables are also code references. |
|
|
373 | |
|
|
374 | my $done = AnyEvent->condvar; |
|
|
375 | my $delay = AnyEvent->timer (after => 5, cb => $done); |
|
|
376 | $done->recv; |
|
|
377 | |
|
|
378 | =head3 METHODS FOR PRODUCERS |
|
|
379 | |
|
|
380 | These methods should only be used by the producing side, i.e. the |
|
|
381 | code/module that eventually sends the signal. Note that it is also |
|
|
382 | the producer side which creates the condvar in most cases, but it isn't |
|
|
383 | uncommon for the consumer to create it as well. |
325 | |
384 | |
326 | =over 4 |
385 | =over 4 |
327 | |
386 | |
|
|
387 | =item $cv->send (...) |
|
|
388 | |
|
|
389 | Flag the condition as ready - a running C<< ->recv >> and all further |
|
|
390 | calls to C<recv> will (eventually) return after this method has been |
|
|
391 | called. If nobody is waiting the send will be remembered. |
|
|
392 | |
|
|
393 | If a callback has been set on the condition variable, it is called |
|
|
394 | immediately from within send. |
|
|
395 | |
|
|
396 | Any arguments passed to the C<send> call will be returned by all |
|
|
397 | future C<< ->recv >> calls. |
|
|
398 | |
|
|
399 | Condition variables are overloaded so one can call them directly (as a |
|
|
400 | code reference). Calling them directly is the same as calling C<send>. |
|
|
401 | |
|
|
402 | =item $cv->croak ($error) |
|
|
403 | |
|
|
404 | Similar to send, but causes all call's to C<< ->recv >> to invoke |
|
|
405 | C<Carp::croak> with the given error message/object/scalar. |
|
|
406 | |
|
|
407 | This can be used to signal any errors to the condition variable |
|
|
408 | user/consumer. |
|
|
409 | |
|
|
410 | =item $cv->begin ([group callback]) |
|
|
411 | |
328 | =item $cv->wait |
412 | =item $cv->end |
329 | |
413 | |
330 | Wait (blocking if necessary) until the C<< ->broadcast >> method has been |
414 | These two methods are EXPERIMENTAL and MIGHT CHANGE. |
|
|
415 | |
|
|
416 | These two methods can be used to combine many transactions/events into |
|
|
417 | one. For example, a function that pings many hosts in parallel might want |
|
|
418 | to use a condition variable for the whole process. |
|
|
419 | |
|
|
420 | Every call to C<< ->begin >> will increment a counter, and every call to |
|
|
421 | C<< ->end >> will decrement it. If the counter reaches C<0> in C<< ->end |
|
|
422 | >>, the (last) callback passed to C<begin> will be executed. That callback |
|
|
423 | is I<supposed> to call C<< ->send >>, but that is not required. If no |
|
|
424 | callback was set, C<send> will be called without any arguments. |
|
|
425 | |
|
|
426 | Let's clarify this with the ping example: |
|
|
427 | |
|
|
428 | my $cv = AnyEvent->condvar; |
|
|
429 | |
|
|
430 | my %result; |
|
|
431 | $cv->begin (sub { $cv->send (\%result) }); |
|
|
432 | |
|
|
433 | for my $host (@list_of_hosts) { |
|
|
434 | $cv->begin; |
|
|
435 | ping_host_then_call_callback $host, sub { |
|
|
436 | $result{$host} = ...; |
|
|
437 | $cv->end; |
|
|
438 | }; |
|
|
439 | } |
|
|
440 | |
|
|
441 | $cv->end; |
|
|
442 | |
|
|
443 | This code fragment supposedly pings a number of hosts and calls |
|
|
444 | C<send> after results for all then have have been gathered - in any |
|
|
445 | order. To achieve this, the code issues a call to C<begin> when it starts |
|
|
446 | each ping request and calls C<end> when it has received some result for |
|
|
447 | it. Since C<begin> and C<end> only maintain a counter, the order in which |
|
|
448 | results arrive is not relevant. |
|
|
449 | |
|
|
450 | There is an additional bracketing call to C<begin> and C<end> outside the |
|
|
451 | loop, which serves two important purposes: first, it sets the callback |
|
|
452 | to be called once the counter reaches C<0>, and second, it ensures that |
|
|
453 | C<send> is called even when C<no> hosts are being pinged (the loop |
|
|
454 | doesn't execute once). |
|
|
455 | |
|
|
456 | This is the general pattern when you "fan out" into multiple subrequests: |
|
|
457 | use an outer C<begin>/C<end> pair to set the callback and ensure C<end> |
|
|
458 | is called at least once, and then, for each subrequest you start, call |
|
|
459 | C<begin> and for each subrequest you finish, call C<end>. |
|
|
460 | |
|
|
461 | =back |
|
|
462 | |
|
|
463 | =head3 METHODS FOR CONSUMERS |
|
|
464 | |
|
|
465 | These methods should only be used by the consuming side, i.e. the |
|
|
466 | code awaits the condition. |
|
|
467 | |
|
|
468 | =over 4 |
|
|
469 | |
|
|
470 | =item $cv->recv |
|
|
471 | |
|
|
472 | Wait (blocking if necessary) until the C<< ->send >> or C<< ->croak |
331 | called on c<$cv>, while servicing other watchers normally. |
473 | >> methods have been called on c<$cv>, while servicing other watchers |
|
|
474 | normally. |
332 | |
475 | |
333 | You can only wait once on a condition - additional calls will return |
476 | You can only wait once on a condition - additional calls are valid but |
334 | immediately. |
477 | will return immediately. |
|
|
478 | |
|
|
479 | If an error condition has been set by calling C<< ->croak >>, then this |
|
|
480 | function will call C<croak>. |
|
|
481 | |
|
|
482 | In list context, all parameters passed to C<send> will be returned, |
|
|
483 | in scalar context only the first one will be returned. |
335 | |
484 | |
336 | Not all event models support a blocking wait - some die in that case |
485 | Not all event models support a blocking wait - some die in that case |
337 | (programs might want to do that to stay interactive), so I<if you are |
486 | (programs might want to do that to stay interactive), so I<if you are |
338 | using this from a module, never require a blocking wait>, but let the |
487 | using this from a module, never require a blocking wait>, but let the |
339 | caller decide whether the call will block or not (for example, by coupling |
488 | caller decide whether the call will block or not (for example, by coupling |
340 | condition variables with some kind of request results and supporting |
489 | condition variables with some kind of request results and supporting |
341 | callbacks so the caller knows that getting the result will not block, |
490 | callbacks so the caller knows that getting the result will not block, |
342 | while still suppporting blocking waits if the caller so desires). |
491 | while still supporting blocking waits if the caller so desires). |
343 | |
492 | |
344 | Another reason I<never> to C<< ->wait >> in a module is that you cannot |
493 | Another reason I<never> to C<< ->recv >> in a module is that you cannot |
345 | sensibly have two C<< ->wait >>'s in parallel, as that would require |
494 | sensibly have two C<< ->recv >>'s in parallel, as that would require |
346 | multiple interpreters or coroutines/threads, none of which C<AnyEvent> |
495 | multiple interpreters or coroutines/threads, none of which C<AnyEvent> |
347 | can supply (the coroutine-aware backends L<AnyEvent::Impl::CoroEV> and |
496 | can supply. |
348 | L<AnyEvent::Impl::CoroEvent> explicitly support concurrent C<< ->wait >>'s |
|
|
349 | from different coroutines, however). |
|
|
350 | |
497 | |
351 | =item $cv->broadcast |
498 | The L<Coro> module, however, I<can> and I<does> supply coroutines and, in |
|
|
499 | fact, L<Coro::AnyEvent> replaces AnyEvent's condvars by coroutine-safe |
|
|
500 | versions and also integrates coroutines into AnyEvent, making blocking |
|
|
501 | C<< ->recv >> calls perfectly safe as long as they are done from another |
|
|
502 | coroutine (one that doesn't run the event loop). |
352 | |
503 | |
353 | Flag the condition as ready - a running C<< ->wait >> and all further |
504 | You can ensure that C<< -recv >> never blocks by setting a callback and |
354 | calls to C<wait> will (eventually) return after this method has been |
505 | only calling C<< ->recv >> from within that callback (or at a later |
355 | called. If nobody is waiting the broadcast will be remembered.. |
506 | time). This will work even when the event loop does not support blocking |
|
|
507 | waits otherwise. |
|
|
508 | |
|
|
509 | =item $bool = $cv->ready |
|
|
510 | |
|
|
511 | Returns true when the condition is "true", i.e. whether C<send> or |
|
|
512 | C<croak> have been called. |
|
|
513 | |
|
|
514 | =item $cb = $cv->cb ([new callback]) |
|
|
515 | |
|
|
516 | This is a mutator function that returns the callback set and optionally |
|
|
517 | replaces it before doing so. |
|
|
518 | |
|
|
519 | The callback will be called when the condition becomes "true", i.e. when |
|
|
520 | C<send> or C<croak> are called. Calling C<recv> inside the callback |
|
|
521 | or at any later time is guaranteed not to block. |
356 | |
522 | |
357 | =back |
523 | =back |
358 | |
|
|
359 | Example: |
|
|
360 | |
|
|
361 | # wait till the result is ready |
|
|
362 | my $result_ready = AnyEvent->condvar; |
|
|
363 | |
|
|
364 | # do something such as adding a timer |
|
|
365 | # or socket watcher the calls $result_ready->broadcast |
|
|
366 | # when the "result" is ready. |
|
|
367 | # in this case, we simply use a timer: |
|
|
368 | my $w = AnyEvent->timer ( |
|
|
369 | after => 1, |
|
|
370 | cb => sub { $result_ready->broadcast }, |
|
|
371 | ); |
|
|
372 | |
|
|
373 | # this "blocks" (while handling events) till the watcher |
|
|
374 | # calls broadcast |
|
|
375 | $result_ready->wait; |
|
|
376 | |
524 | |
377 | =head1 GLOBAL VARIABLES AND FUNCTIONS |
525 | =head1 GLOBAL VARIABLES AND FUNCTIONS |
378 | |
526 | |
379 | =over 4 |
527 | =over 4 |
380 | |
528 | |
… | |
… | |
386 | C<AnyEvent::Impl:xxx> modules, but can be any other class in the case |
534 | C<AnyEvent::Impl:xxx> modules, but can be any other class in the case |
387 | AnyEvent has been extended at runtime (e.g. in I<rxvt-unicode>). |
535 | AnyEvent has been extended at runtime (e.g. in I<rxvt-unicode>). |
388 | |
536 | |
389 | The known classes so far are: |
537 | The known classes so far are: |
390 | |
538 | |
391 | AnyEvent::Impl::CoroEV based on Coro::EV, best choice. |
|
|
392 | AnyEvent::Impl::CoroEvent based on Coro::Event, second best choice. |
|
|
393 | AnyEvent::Impl::EV based on EV (an interface to libev, best choice). |
539 | AnyEvent::Impl::EV based on EV (an interface to libev, best choice). |
394 | AnyEvent::Impl::Event based on Event, second best choice. |
540 | AnyEvent::Impl::Event based on Event, second best choice. |
|
|
541 | AnyEvent::Impl::Perl pure-perl implementation, fast and portable. |
395 | AnyEvent::Impl::Glib based on Glib, third-best choice. |
542 | AnyEvent::Impl::Glib based on Glib, third-best choice. |
396 | AnyEvent::Impl::Perl pure-perl implementation, inefficient but portable. |
|
|
397 | AnyEvent::Impl::Tk based on Tk, very bad choice. |
543 | AnyEvent::Impl::Tk based on Tk, very bad choice. |
398 | AnyEvent::Impl::Qt based on Qt, cannot be autoprobed (see its docs). |
544 | AnyEvent::Impl::Qt based on Qt, cannot be autoprobed (see its docs). |
399 | AnyEvent::Impl::EventLib based on Event::Lib, leaks memory and worse. |
545 | AnyEvent::Impl::EventLib based on Event::Lib, leaks memory and worse. |
400 | AnyEvent::Impl::POE based on POE, not generic enough for full support. |
546 | AnyEvent::Impl::POE based on POE, not generic enough for full support. |
401 | |
547 | |
… | |
… | |
414 | Returns C<$AnyEvent::MODEL>, forcing autodetection of the event model |
560 | Returns C<$AnyEvent::MODEL>, forcing autodetection of the event model |
415 | if necessary. You should only call this function right before you would |
561 | if necessary. You should only call this function right before you would |
416 | have created an AnyEvent watcher anyway, that is, as late as possible at |
562 | have created an AnyEvent watcher anyway, that is, as late as possible at |
417 | runtime. |
563 | runtime. |
418 | |
564 | |
|
|
565 | =item $guard = AnyEvent::post_detect { BLOCK } |
|
|
566 | |
|
|
567 | Arranges for the code block to be executed as soon as the event model is |
|
|
568 | autodetected (or immediately if this has already happened). |
|
|
569 | |
|
|
570 | If called in scalar or list context, then it creates and returns an object |
|
|
571 | that automatically removes the callback again when it is destroyed. See |
|
|
572 | L<Coro::BDB> for a case where this is useful. |
|
|
573 | |
|
|
574 | =item @AnyEvent::post_detect |
|
|
575 | |
|
|
576 | If there are any code references in this array (you can C<push> to it |
|
|
577 | before or after loading AnyEvent), then they will called directly after |
|
|
578 | the event loop has been chosen. |
|
|
579 | |
|
|
580 | You should check C<$AnyEvent::MODEL> before adding to this array, though: |
|
|
581 | if it contains a true value then the event loop has already been detected, |
|
|
582 | and the array will be ignored. |
|
|
583 | |
|
|
584 | Best use C<AnyEvent::post_detect { BLOCK }> instead. |
|
|
585 | |
419 | =back |
586 | =back |
420 | |
587 | |
421 | =head1 WHAT TO DO IN A MODULE |
588 | =head1 WHAT TO DO IN A MODULE |
422 | |
589 | |
423 | As a module author, you should C<use AnyEvent> and call AnyEvent methods |
590 | As a module author, you should C<use AnyEvent> and call AnyEvent methods |
… | |
… | |
426 | Be careful when you create watchers in the module body - AnyEvent will |
593 | Be careful when you create watchers in the module body - AnyEvent will |
427 | decide which event module to use as soon as the first method is called, so |
594 | decide which event module to use as soon as the first method is called, so |
428 | by calling AnyEvent in your module body you force the user of your module |
595 | by calling AnyEvent in your module body you force the user of your module |
429 | to load the event module first. |
596 | to load the event module first. |
430 | |
597 | |
431 | Never call C<< ->wait >> on a condition variable unless you I<know> that |
598 | Never call C<< ->recv >> on a condition variable unless you I<know> that |
432 | the C<< ->broadcast >> method has been called on it already. This is |
599 | the C<< ->send >> method has been called on it already. This is |
433 | because it will stall the whole program, and the whole point of using |
600 | because it will stall the whole program, and the whole point of using |
434 | events is to stay interactive. |
601 | events is to stay interactive. |
435 | |
602 | |
436 | It is fine, however, to call C<< ->wait >> when the user of your module |
603 | It is fine, however, to call C<< ->recv >> when the user of your module |
437 | requests it (i.e. if you create a http request object ad have a method |
604 | requests it (i.e. if you create a http request object ad have a method |
438 | called C<results> that returns the results, it should call C<< ->wait >> |
605 | called C<results> that returns the results, it should call C<< ->recv >> |
439 | freely, as the user of your module knows what she is doing. always). |
606 | freely, as the user of your module knows what she is doing. always). |
440 | |
607 | |
441 | =head1 WHAT TO DO IN THE MAIN PROGRAM |
608 | =head1 WHAT TO DO IN THE MAIN PROGRAM |
442 | |
609 | |
443 | There will always be a single main program - the only place that should |
610 | There will always be a single main program - the only place that should |
… | |
… | |
445 | |
612 | |
446 | If it doesn't care, it can just "use AnyEvent" and use it itself, or not |
613 | If it doesn't care, it can just "use AnyEvent" and use it itself, or not |
447 | do anything special (it does not need to be event-based) and let AnyEvent |
614 | do anything special (it does not need to be event-based) and let AnyEvent |
448 | decide which implementation to chose if some module relies on it. |
615 | decide which implementation to chose if some module relies on it. |
449 | |
616 | |
450 | If the main program relies on a specific event model. For example, in |
617 | If the main program relies on a specific event model - for example, in |
451 | Gtk2 programs you have to rely on the Glib module. You should load the |
618 | Gtk2 programs you have to rely on the Glib module - you should load the |
452 | event module before loading AnyEvent or any module that uses it: generally |
619 | event module before loading AnyEvent or any module that uses it: generally |
453 | speaking, you should load it as early as possible. The reason is that |
620 | speaking, you should load it as early as possible. The reason is that |
454 | modules might create watchers when they are loaded, and AnyEvent will |
621 | modules might create watchers when they are loaded, and AnyEvent will |
455 | decide on the event model to use as soon as it creates watchers, and it |
622 | decide on the event model to use as soon as it creates watchers, and it |
456 | might chose the wrong one unless you load the correct one yourself. |
623 | might chose the wrong one unless you load the correct one yourself. |
457 | |
624 | |
458 | You can chose to use a rather inefficient pure-perl implementation by |
625 | You can chose to use a pure-perl implementation by loading the |
459 | loading the C<AnyEvent::Impl::Perl> module, which gives you similar |
626 | C<AnyEvent::Impl::Perl> module, which gives you similar behaviour |
460 | behaviour everywhere, but letting AnyEvent chose is generally better. |
627 | everywhere, but letting AnyEvent chose the model is generally better. |
|
|
628 | |
|
|
629 | =head2 MAINLOOP EMULATION |
|
|
630 | |
|
|
631 | Sometimes (often for short test scripts, or even standalone programs who |
|
|
632 | only want to use AnyEvent), you do not want to run a specific event loop. |
|
|
633 | |
|
|
634 | In that case, you can use a condition variable like this: |
|
|
635 | |
|
|
636 | AnyEvent->condvar->recv; |
|
|
637 | |
|
|
638 | This has the effect of entering the event loop and looping forever. |
|
|
639 | |
|
|
640 | Note that usually your program has some exit condition, in which case |
|
|
641 | it is better to use the "traditional" approach of storing a condition |
|
|
642 | variable somewhere, waiting for it, and sending it when the program should |
|
|
643 | exit cleanly. |
|
|
644 | |
461 | |
645 | |
462 | =head1 OTHER MODULES |
646 | =head1 OTHER MODULES |
463 | |
647 | |
464 | The following is a non-exhaustive list of additional modules that use |
648 | The following is a non-exhaustive list of additional modules that use |
465 | AnyEvent and can therefore be mixed easily with other AnyEvent modules |
649 | AnyEvent and can therefore be mixed easily with other AnyEvent modules |
… | |
… | |
477 | |
661 | |
478 | Provide read and write buffers and manages watchers for reads and writes. |
662 | Provide read and write buffers and manages watchers for reads and writes. |
479 | |
663 | |
480 | =item L<AnyEvent::Socket> |
664 | =item L<AnyEvent::Socket> |
481 | |
665 | |
482 | Provides a means to do non-blocking connects, accepts etc. |
666 | Provides various utility functions for (internet protocol) sockets, |
|
|
667 | addresses and name resolution. Also functions to create non-blocking tcp |
|
|
668 | connections or tcp servers, with IPv6 and SRV record support and more. |
|
|
669 | |
|
|
670 | =item L<AnyEvent::DNS> |
|
|
671 | |
|
|
672 | Provides rich asynchronous DNS resolver capabilities. |
483 | |
673 | |
484 | =item L<AnyEvent::HTTPD> |
674 | =item L<AnyEvent::HTTPD> |
485 | |
675 | |
486 | Provides a simple web application server framework. |
676 | Provides a simple web application server framework. |
487 | |
|
|
488 | =item L<AnyEvent::DNS> |
|
|
489 | |
|
|
490 | Provides asynchronous DNS resolver capabilities, beyond what |
|
|
491 | L<AnyEvent::Util> offers. |
|
|
492 | |
677 | |
493 | =item L<AnyEvent::FastPing> |
678 | =item L<AnyEvent::FastPing> |
494 | |
679 | |
495 | The fastest ping in the west. |
680 | The fastest ping in the west. |
496 | |
681 | |
… | |
… | |
511 | |
696 | |
512 | High level API for event-based execution flow control. |
697 | High level API for event-based execution flow control. |
513 | |
698 | |
514 | =item L<Coro> |
699 | =item L<Coro> |
515 | |
700 | |
516 | Has special support for AnyEvent. |
701 | Has special support for AnyEvent via L<Coro::AnyEvent>. |
|
|
702 | |
|
|
703 | =item L<AnyEvent::AIO>, L<IO::AIO> |
|
|
704 | |
|
|
705 | Truly asynchronous I/O, should be in the toolbox of every event |
|
|
706 | programmer. AnyEvent::AIO transparently fuses IO::AIO and AnyEvent |
|
|
707 | together. |
|
|
708 | |
|
|
709 | =item L<AnyEvent::BDB>, L<BDB> |
|
|
710 | |
|
|
711 | Truly asynchronous Berkeley DB access. AnyEvent::AIO transparently fuses |
|
|
712 | IO::AIO and AnyEvent together. |
517 | |
713 | |
518 | =item L<IO::Lambda> |
714 | =item L<IO::Lambda> |
519 | |
715 | |
520 | The lambda approach to I/O - don't ask, look there. Can use AnyEvent. |
716 | The lambda approach to I/O - don't ask, look there. Can use AnyEvent. |
521 | |
|
|
522 | =item L<IO::AIO> |
|
|
523 | |
|
|
524 | Truly asynchronous I/O, should be in the toolbox of every event |
|
|
525 | programmer. Can be trivially made to use AnyEvent. |
|
|
526 | |
|
|
527 | =item L<BDB> |
|
|
528 | |
|
|
529 | Truly asynchronous Berkeley DB access. Can be trivially made to use |
|
|
530 | AnyEvent. |
|
|
531 | |
717 | |
532 | =back |
718 | =back |
533 | |
719 | |
534 | =cut |
720 | =cut |
535 | |
721 | |
… | |
… | |
538 | no warnings; |
724 | no warnings; |
539 | use strict; |
725 | use strict; |
540 | |
726 | |
541 | use Carp; |
727 | use Carp; |
542 | |
728 | |
543 | our $VERSION = '3.3'; |
729 | our $VERSION = '4.03'; |
544 | our $MODEL; |
730 | our $MODEL; |
545 | |
731 | |
546 | our $AUTOLOAD; |
732 | our $AUTOLOAD; |
547 | our @ISA; |
733 | our @ISA; |
548 | |
734 | |
549 | our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1; |
735 | our $verbose = $ENV{PERL_ANYEVENT_VERBOSE}*1; |
550 | |
736 | |
551 | our @REGISTRY; |
737 | our @REGISTRY; |
552 | |
738 | |
|
|
739 | our %PROTOCOL; # (ipv4|ipv6) => (1|2) |
|
|
740 | |
|
|
741 | { |
|
|
742 | my $idx; |
|
|
743 | $PROTOCOL{$_} = ++$idx |
|
|
744 | for split /\s*,\s*/, $ENV{PERL_ANYEVENT_PROTOCOLS} || "ipv4,ipv6"; |
|
|
745 | } |
|
|
746 | |
553 | my @models = ( |
747 | my @models = ( |
554 | [Coro::EV:: => AnyEvent::Impl::CoroEV::], |
|
|
555 | [Coro::Event:: => AnyEvent::Impl::CoroEvent::], |
|
|
556 | [EV:: => AnyEvent::Impl::EV::], |
748 | [EV:: => AnyEvent::Impl::EV::], |
557 | [Event:: => AnyEvent::Impl::Event::], |
749 | [Event:: => AnyEvent::Impl::Event::], |
558 | [Glib:: => AnyEvent::Impl::Glib::], |
|
|
559 | [Tk:: => AnyEvent::Impl::Tk::], |
750 | [Tk:: => AnyEvent::Impl::Tk::], |
560 | [Wx:: => AnyEvent::Impl::POE::], |
751 | [Wx:: => AnyEvent::Impl::POE::], |
561 | [Prima:: => AnyEvent::Impl::POE::], |
752 | [Prima:: => AnyEvent::Impl::POE::], |
562 | [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl::], |
753 | [AnyEvent::Impl::Perl:: => AnyEvent::Impl::Perl::], |
563 | # everything below here will not be autoprobed as the pureperl backend should work everywhere |
754 | # everything below here will not be autoprobed as the pureperl backend should work everywhere |
|
|
755 | [Glib:: => AnyEvent::Impl::Glib::], |
564 | [Event::Lib:: => AnyEvent::Impl::EventLib::], # too buggy |
756 | [Event::Lib:: => AnyEvent::Impl::EventLib::], # too buggy |
565 | [Qt:: => AnyEvent::Impl::Qt::], # requires special main program |
757 | [Qt:: => AnyEvent::Impl::Qt::], # requires special main program |
566 | [POE::Kernel:: => AnyEvent::Impl::POE::], # lasciate ogni speranza |
758 | [POE::Kernel:: => AnyEvent::Impl::POE::], # lasciate ogni speranza |
567 | ); |
759 | ); |
568 | |
760 | |
569 | our %method = map +($_ => 1), qw(io timer signal child condvar broadcast wait one_event DESTROY); |
761 | our %method = map +($_ => 1), qw(io timer signal child condvar one_event DESTROY); |
|
|
762 | |
|
|
763 | our @post_detect; |
|
|
764 | |
|
|
765 | sub post_detect(&) { |
|
|
766 | my ($cb) = @_; |
|
|
767 | |
|
|
768 | if ($MODEL) { |
|
|
769 | $cb->(); |
|
|
770 | |
|
|
771 | 1 |
|
|
772 | } else { |
|
|
773 | push @post_detect, $cb; |
|
|
774 | |
|
|
775 | defined wantarray |
|
|
776 | ? bless \$cb, "AnyEvent::Util::PostDetect" |
|
|
777 | : () |
|
|
778 | } |
|
|
779 | } |
|
|
780 | |
|
|
781 | sub AnyEvent::Util::PostDetect::DESTROY { |
|
|
782 | @post_detect = grep $_ != ${$_[0]}, @post_detect; |
|
|
783 | } |
570 | |
784 | |
571 | sub detect() { |
785 | sub detect() { |
572 | unless ($MODEL) { |
786 | unless ($MODEL) { |
573 | no strict 'refs'; |
787 | no strict 'refs'; |
574 | |
788 | |
… | |
… | |
608 | last; |
822 | last; |
609 | } |
823 | } |
610 | } |
824 | } |
611 | |
825 | |
612 | $MODEL |
826 | $MODEL |
613 | or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: EV (or Coro+EV), Event (or Coro+Event) or Glib."; |
827 | or die "No event module selected for AnyEvent and autodetect failed. Install any one of these modules: EV, Event or Glib."; |
614 | } |
828 | } |
615 | } |
829 | } |
616 | |
830 | |
617 | unshift @ISA, $MODEL; |
831 | unshift @ISA, $MODEL; |
618 | push @{"$MODEL\::ISA"}, "AnyEvent::Base"; |
832 | push @{"$MODEL\::ISA"}, "AnyEvent::Base"; |
|
|
833 | |
|
|
834 | (shift @post_detect)->() while @post_detect; |
619 | } |
835 | } |
620 | |
836 | |
621 | $MODEL |
837 | $MODEL |
622 | } |
838 | } |
623 | |
839 | |
… | |
… | |
633 | $class->$func (@_); |
849 | $class->$func (@_); |
634 | } |
850 | } |
635 | |
851 | |
636 | package AnyEvent::Base; |
852 | package AnyEvent::Base; |
637 | |
853 | |
638 | # default implementation for ->condvar, ->wait, ->broadcast |
854 | # default implementation for ->condvar |
639 | |
855 | |
640 | sub condvar { |
856 | sub condvar { |
641 | bless \my $flag, "AnyEvent::Base::CondVar" |
857 | bless { @_ == 3 ? (_ae_cb => $_[2]) : () }, AnyEvent::CondVar:: |
642 | } |
|
|
643 | |
|
|
644 | sub AnyEvent::Base::CondVar::broadcast { |
|
|
645 | ${$_[0]}++; |
|
|
646 | } |
|
|
647 | |
|
|
648 | sub AnyEvent::Base::CondVar::wait { |
|
|
649 | AnyEvent->one_event while !${$_[0]}; |
|
|
650 | } |
858 | } |
651 | |
859 | |
652 | # default implementation for ->signal |
860 | # default implementation for ->signal |
653 | |
861 | |
654 | our %SIG_CB; |
862 | our %SIG_CB; |
… | |
… | |
728 | delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} }; |
936 | delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} }; |
729 | |
937 | |
730 | undef $CHLD_W unless keys %PID_CB; |
938 | undef $CHLD_W unless keys %PID_CB; |
731 | } |
939 | } |
732 | |
940 | |
|
|
941 | package AnyEvent::CondVar; |
|
|
942 | |
|
|
943 | our @ISA = AnyEvent::CondVar::Base::; |
|
|
944 | |
|
|
945 | package AnyEvent::CondVar::Base; |
|
|
946 | |
|
|
947 | use overload |
|
|
948 | '&{}' => sub { my $self = shift; sub { $self->send (@_) } }, |
|
|
949 | fallback => 1; |
|
|
950 | |
|
|
951 | sub _send { |
|
|
952 | # nop |
|
|
953 | } |
|
|
954 | |
|
|
955 | sub send { |
|
|
956 | my $cv = shift; |
|
|
957 | $cv->{_ae_sent} = [@_]; |
|
|
958 | (delete $cv->{_ae_cb})->($cv) if $cv->{_ae_cb}; |
|
|
959 | $cv->_send; |
|
|
960 | } |
|
|
961 | |
|
|
962 | sub croak { |
|
|
963 | $_[0]{_ae_croak} = $_[1]; |
|
|
964 | $_[0]->send; |
|
|
965 | } |
|
|
966 | |
|
|
967 | sub ready { |
|
|
968 | $_[0]{_ae_sent} |
|
|
969 | } |
|
|
970 | |
|
|
971 | sub _wait { |
|
|
972 | AnyEvent->one_event while !$_[0]{_ae_sent}; |
|
|
973 | } |
|
|
974 | |
|
|
975 | sub recv { |
|
|
976 | $_[0]->_wait; |
|
|
977 | |
|
|
978 | Carp::croak $_[0]{_ae_croak} if $_[0]{_ae_croak}; |
|
|
979 | wantarray ? @{ $_[0]{_ae_sent} } : $_[0]{_ae_sent}[0] |
|
|
980 | } |
|
|
981 | |
|
|
982 | sub cb { |
|
|
983 | $_[0]{_ae_cb} = $_[1] if @_ > 1; |
|
|
984 | $_[0]{_ae_cb} |
|
|
985 | } |
|
|
986 | |
|
|
987 | sub begin { |
|
|
988 | ++$_[0]{_ae_counter}; |
|
|
989 | $_[0]{_ae_end_cb} = $_[1] if @_ > 1; |
|
|
990 | } |
|
|
991 | |
|
|
992 | sub end { |
|
|
993 | return if --$_[0]{_ae_counter}; |
|
|
994 | &{ $_[0]{_ae_end_cb} || sub { $_[0]->send } }; |
|
|
995 | } |
|
|
996 | |
|
|
997 | # undocumented/compatibility with pre-3.4 |
|
|
998 | *broadcast = \&send; |
|
|
999 | *wait = \&_wait; |
|
|
1000 | |
733 | =head1 SUPPLYING YOUR OWN EVENT MODEL INTERFACE |
1001 | =head1 SUPPLYING YOUR OWN EVENT MODEL INTERFACE |
734 | |
1002 | |
735 | This is an advanced topic that you do not normally need to use AnyEvent in |
1003 | This is an advanced topic that you do not normally need to use AnyEvent in |
736 | a module. This section is only of use to event loop authors who want to |
1004 | a module. This section is only of use to event loop authors who want to |
737 | provide AnyEvent compatibility. |
1005 | provide AnyEvent compatibility. |
… | |
… | |
793 | model it chooses. |
1061 | model it chooses. |
794 | |
1062 | |
795 | =item C<PERL_ANYEVENT_MODEL> |
1063 | =item C<PERL_ANYEVENT_MODEL> |
796 | |
1064 | |
797 | This can be used to specify the event model to be used by AnyEvent, before |
1065 | This can be used to specify the event model to be used by AnyEvent, before |
798 | autodetection and -probing kicks in. It must be a string consisting |
1066 | auto detection and -probing kicks in. It must be a string consisting |
799 | entirely of ASCII letters. The string C<AnyEvent::Impl::> gets prepended |
1067 | entirely of ASCII letters. The string C<AnyEvent::Impl::> gets prepended |
800 | and the resulting module name is loaded and if the load was successful, |
1068 | and the resulting module name is loaded and if the load was successful, |
801 | used as event model. If it fails to load AnyEvent will proceed with |
1069 | used as event model. If it fails to load AnyEvent will proceed with |
802 | autodetection and -probing. |
1070 | auto detection and -probing. |
803 | |
1071 | |
804 | This functionality might change in future versions. |
1072 | This functionality might change in future versions. |
805 | |
1073 | |
806 | For example, to force the pure perl model (L<AnyEvent::Impl::Perl>) you |
1074 | For example, to force the pure perl model (L<AnyEvent::Impl::Perl>) you |
807 | could start your program like this: |
1075 | could start your program like this: |
808 | |
1076 | |
809 | PERL_ANYEVENT_MODEL=Perl perl ... |
1077 | PERL_ANYEVENT_MODEL=Perl perl ... |
|
|
1078 | |
|
|
1079 | =item C<PERL_ANYEVENT_PROTOCOLS> |
|
|
1080 | |
|
|
1081 | Used by both L<AnyEvent::DNS> and L<AnyEvent::Socket> to determine preferences |
|
|
1082 | for IPv4 or IPv6. The default is unspecified (and might change, or be the result |
|
|
1083 | of auto probing). |
|
|
1084 | |
|
|
1085 | Must be set to a comma-separated list of protocols or address families, |
|
|
1086 | current supported: C<ipv4> and C<ipv6>. Only protocols mentioned will be |
|
|
1087 | used, and preference will be given to protocols mentioned earlier in the |
|
|
1088 | list. |
|
|
1089 | |
|
|
1090 | This variable can effectively be used for denial-of-service attacks |
|
|
1091 | against local programs (e.g. when setuid), although the impact is likely |
|
|
1092 | small, as the program has to handle connection errors already- |
|
|
1093 | |
|
|
1094 | Examples: C<PERL_ANYEVENT_PROTOCOLS=ipv4,ipv6> - prefer IPv4 over IPv6, |
|
|
1095 | but support both and try to use both. C<PERL_ANYEVENT_PROTOCOLS=ipv4> |
|
|
1096 | - only support IPv4, never try to resolve or contact IPv6 |
|
|
1097 | addresses. C<PERL_ANYEVENT_PROTOCOLS=ipv6,ipv4> support either IPv4 or |
|
|
1098 | IPv6, but prefer IPv6 over IPv4. |
|
|
1099 | |
|
|
1100 | =item C<PERL_ANYEVENT_EDNS0> |
|
|
1101 | |
|
|
1102 | Used by L<AnyEvent::DNS> to decide whether to use the EDNS0 extension |
|
|
1103 | for DNS. This extension is generally useful to reduce DNS traffic, but |
|
|
1104 | some (broken) firewalls drop such DNS packets, which is why it is off by |
|
|
1105 | default. |
|
|
1106 | |
|
|
1107 | Setting this variable to C<1> will cause L<AnyEvent::DNS> to announce |
|
|
1108 | EDNS0 in its DNS requests. |
810 | |
1109 | |
811 | =back |
1110 | =back |
812 | |
1111 | |
813 | =head1 EXAMPLE PROGRAM |
1112 | =head1 EXAMPLE PROGRAM |
814 | |
1113 | |
… | |
… | |
825 | poll => 'r', |
1124 | poll => 'r', |
826 | cb => sub { |
1125 | cb => sub { |
827 | warn "io event <$_[0]>\n"; # will always output <r> |
1126 | warn "io event <$_[0]>\n"; # will always output <r> |
828 | chomp (my $input = <STDIN>); # read a line |
1127 | chomp (my $input = <STDIN>); # read a line |
829 | warn "read: $input\n"; # output what has been read |
1128 | warn "read: $input\n"; # output what has been read |
830 | $cv->broadcast if $input =~ /^q/i; # quit program if /^q/i |
1129 | $cv->send if $input =~ /^q/i; # quit program if /^q/i |
831 | }, |
1130 | }, |
832 | ); |
1131 | ); |
833 | |
1132 | |
834 | my $time_watcher; # can only be used once |
1133 | my $time_watcher; # can only be used once |
835 | |
1134 | |
… | |
… | |
840 | }); |
1139 | }); |
841 | } |
1140 | } |
842 | |
1141 | |
843 | new_timer; # create first timer |
1142 | new_timer; # create first timer |
844 | |
1143 | |
845 | $cv->wait; # wait until user enters /^q/i |
1144 | $cv->recv; # wait until user enters /^q/i |
846 | |
1145 | |
847 | =head1 REAL-WORLD EXAMPLE |
1146 | =head1 REAL-WORLD EXAMPLE |
848 | |
1147 | |
849 | Consider the L<Net::FCP> module. It features (among others) the following |
1148 | Consider the L<Net::FCP> module. It features (among others) the following |
850 | API calls, which are to freenet what HTTP GET requests are to http: |
1149 | API calls, which are to freenet what HTTP GET requests are to http: |
… | |
… | |
900 | syswrite $txn->{fh}, $txn->{request} |
1199 | syswrite $txn->{fh}, $txn->{request} |
901 | or die "connection or write error"; |
1200 | or die "connection or write error"; |
902 | $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r }); |
1201 | $txn->{w} = AnyEvent->io (fh => $txn->{fh}, poll => 'r', cb => sub { $txn->fh_ready_r }); |
903 | |
1202 | |
904 | Again, C<fh_ready_r> waits till all data has arrived, and then stores the |
1203 | Again, C<fh_ready_r> waits till all data has arrived, and then stores the |
905 | result and signals any possible waiters that the request ahs finished: |
1204 | result and signals any possible waiters that the request has finished: |
906 | |
1205 | |
907 | sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf}; |
1206 | sysread $txn->{fh}, $txn->{buf}, length $txn->{$buf}; |
908 | |
1207 | |
909 | if (end-of-file or data complete) { |
1208 | if (end-of-file or data complete) { |
910 | $txn->{result} = $txn->{buf}; |
1209 | $txn->{result} = $txn->{buf}; |
911 | $txn->{finished}->broadcast; |
1210 | $txn->{finished}->send; |
912 | $txb->{cb}->($txn) of $txn->{cb}; # also call callback |
1211 | $txb->{cb}->($txn) of $txn->{cb}; # also call callback |
913 | } |
1212 | } |
914 | |
1213 | |
915 | The C<result> method, finally, just waits for the finished signal (if the |
1214 | The C<result> method, finally, just waits for the finished signal (if the |
916 | request was already finished, it doesn't wait, of course, and returns the |
1215 | request was already finished, it doesn't wait, of course, and returns the |
917 | data: |
1216 | data: |
918 | |
1217 | |
919 | $txn->{finished}->wait; |
1218 | $txn->{finished}->recv; |
920 | return $txn->{result}; |
1219 | return $txn->{result}; |
921 | |
1220 | |
922 | The actual code goes further and collects all errors (C<die>s, exceptions) |
1221 | The actual code goes further and collects all errors (C<die>s, exceptions) |
923 | that occured during request processing. The C<result> method detects |
1222 | that occurred during request processing. The C<result> method detects |
924 | whether an exception as thrown (it is stored inside the $txn object) |
1223 | whether an exception as thrown (it is stored inside the $txn object) |
925 | and just throws the exception, which means connection errors and other |
1224 | and just throws the exception, which means connection errors and other |
926 | problems get reported tot he code that tries to use the result, not in a |
1225 | problems get reported tot he code that tries to use the result, not in a |
927 | random callback. |
1226 | random callback. |
928 | |
1227 | |
… | |
… | |
959 | |
1258 | |
960 | my $quit = AnyEvent->condvar; |
1259 | my $quit = AnyEvent->condvar; |
961 | |
1260 | |
962 | $fcp->txn_client_get ($url)->cb (sub { |
1261 | $fcp->txn_client_get ($url)->cb (sub { |
963 | ... |
1262 | ... |
964 | $quit->broadcast; |
1263 | $quit->send; |
965 | }); |
1264 | }); |
966 | |
1265 | |
967 | $quit->wait; |
1266 | $quit->recv; |
968 | |
1267 | |
969 | |
1268 | |
970 | =head1 BENCHMARKS |
1269 | =head1 BENCHMARKS |
971 | |
1270 | |
972 | To give you an idea of the performance and overheads that AnyEvent adds |
1271 | To give you an idea of the performance and overheads that AnyEvent adds |
… | |
… | |
974 | of various event loops I prepared some benchmarks. |
1273 | of various event loops I prepared some benchmarks. |
975 | |
1274 | |
976 | =head2 BENCHMARKING ANYEVENT OVERHEAD |
1275 | =head2 BENCHMARKING ANYEVENT OVERHEAD |
977 | |
1276 | |
978 | Here is a benchmark of various supported event models used natively and |
1277 | Here is a benchmark of various supported event models used natively and |
979 | through anyevent. The benchmark creates a lot of timers (with a zero |
1278 | through AnyEvent. The benchmark creates a lot of timers (with a zero |
980 | timeout) and I/O watchers (watching STDOUT, a pty, to become writable, |
1279 | timeout) and I/O watchers (watching STDOUT, a pty, to become writable, |
981 | which it is), lets them fire exactly once and destroys them again. |
1280 | which it is), lets them fire exactly once and destroys them again. |
982 | |
1281 | |
983 | Source code for this benchmark is found as F<eg/bench> in the AnyEvent |
1282 | Source code for this benchmark is found as F<eg/bench> in the AnyEvent |
984 | distribution. |
1283 | distribution. |
… | |
… | |
1001 | all watchers, to avoid adding memory overhead. That means closure creation |
1300 | all watchers, to avoid adding memory overhead. That means closure creation |
1002 | and memory usage is not included in the figures. |
1301 | and memory usage is not included in the figures. |
1003 | |
1302 | |
1004 | I<invoke> is the time, in microseconds, used to invoke a simple |
1303 | I<invoke> is the time, in microseconds, used to invoke a simple |
1005 | callback. The callback simply counts down a Perl variable and after it was |
1304 | callback. The callback simply counts down a Perl variable and after it was |
1006 | invoked "watcher" times, it would C<< ->broadcast >> a condvar once to |
1305 | invoked "watcher" times, it would C<< ->send >> a condvar once to |
1007 | signal the end of this phase. |
1306 | signal the end of this phase. |
1008 | |
1307 | |
1009 | I<destroy> is the time, in microseconds, that it takes to destroy a single |
1308 | I<destroy> is the time, in microseconds, that it takes to destroy a single |
1010 | watcher. |
1309 | watcher. |
1011 | |
1310 | |
… | |
… | |
1107 | |
1406 | |
1108 | =back |
1407 | =back |
1109 | |
1408 | |
1110 | =head2 BENCHMARKING THE LARGE SERVER CASE |
1409 | =head2 BENCHMARKING THE LARGE SERVER CASE |
1111 | |
1410 | |
1112 | This benchmark atcually benchmarks the event loop itself. It works by |
1411 | This benchmark actually benchmarks the event loop itself. It works by |
1113 | creating a number of "servers": each server consists of a socketpair, a |
1412 | creating a number of "servers": each server consists of a socket pair, a |
1114 | timeout watcher that gets reset on activity (but never fires), and an I/O |
1413 | timeout watcher that gets reset on activity (but never fires), and an I/O |
1115 | watcher waiting for input on one side of the socket. Each time the socket |
1414 | watcher waiting for input on one side of the socket. Each time the socket |
1116 | watcher reads a byte it will write that byte to a random other "server". |
1415 | watcher reads a byte it will write that byte to a random other "server". |
1117 | |
1416 | |
1118 | The effect is that there will be a lot of I/O watchers, only part of which |
1417 | The effect is that there will be a lot of I/O watchers, only part of which |
1119 | are active at any one point (so there is a constant number of active |
1418 | are active at any one point (so there is a constant number of active |
1120 | fds for each loop iterstaion, but which fds these are is random). The |
1419 | fds for each loop iteration, but which fds these are is random). The |
1121 | timeout is reset each time something is read because that reflects how |
1420 | timeout is reset each time something is read because that reflects how |
1122 | most timeouts work (and puts extra pressure on the event loops). |
1421 | most timeouts work (and puts extra pressure on the event loops). |
1123 | |
1422 | |
1124 | In this benchmark, we use 10000 socketpairs (20000 sockets), of which 100 |
1423 | In this benchmark, we use 10000 socket pairs (20000 sockets), of which 100 |
1125 | (1%) are active. This mirrors the activity of large servers with many |
1424 | (1%) are active. This mirrors the activity of large servers with many |
1126 | connections, most of which are idle at any one point in time. |
1425 | connections, most of which are idle at any one point in time. |
1127 | |
1426 | |
1128 | Source code for this benchmark is found as F<eg/bench2> in the AnyEvent |
1427 | Source code for this benchmark is found as F<eg/bench2> in the AnyEvent |
1129 | distribution. |
1428 | distribution. |
… | |
… | |
1131 | =head3 Explanation of the columns |
1430 | =head3 Explanation of the columns |
1132 | |
1431 | |
1133 | I<sockets> is the number of sockets, and twice the number of "servers" (as |
1432 | I<sockets> is the number of sockets, and twice the number of "servers" (as |
1134 | each server has a read and write socket end). |
1433 | each server has a read and write socket end). |
1135 | |
1434 | |
1136 | I<create> is the time it takes to create a socketpair (which is |
1435 | I<create> is the time it takes to create a socket pair (which is |
1137 | nontrivial) and two watchers: an I/O watcher and a timeout watcher. |
1436 | nontrivial) and two watchers: an I/O watcher and a timeout watcher. |
1138 | |
1437 | |
1139 | I<request>, the most important value, is the time it takes to handle a |
1438 | I<request>, the most important value, is the time it takes to handle a |
1140 | single "request", that is, reading the token from the pipe and forwarding |
1439 | single "request", that is, reading the token from the pipe and forwarding |
1141 | it to another server. This includes deleting the old timeout and creating |
1440 | it to another server. This includes deleting the old timeout and creating |
… | |
… | |
1214 | speed most when you have lots of watchers, not when you only have a few of |
1513 | speed most when you have lots of watchers, not when you only have a few of |
1215 | them). |
1514 | them). |
1216 | |
1515 | |
1217 | EV is again fastest. |
1516 | EV is again fastest. |
1218 | |
1517 | |
1219 | Perl again comes second. It is noticably faster than the C-based event |
1518 | Perl again comes second. It is noticeably faster than the C-based event |
1220 | loops Event and Glib, although the difference is too small to really |
1519 | loops Event and Glib, although the difference is too small to really |
1221 | matter. |
1520 | matter. |
1222 | |
1521 | |
1223 | POE also performs much better in this case, but is is still far behind the |
1522 | POE also performs much better in this case, but is is still far behind the |
1224 | others. |
1523 | others. |
… | |
… | |
1234 | |
1533 | |
1235 | |
1534 | |
1236 | =head1 FORK |
1535 | =head1 FORK |
1237 | |
1536 | |
1238 | Most event libraries are not fork-safe. The ones who are usually are |
1537 | Most event libraries are not fork-safe. The ones who are usually are |
1239 | because they are so inefficient. Only L<EV> is fully fork-aware. |
1538 | because they rely on inefficient but fork-safe C<select> or C<poll> |
|
|
1539 | calls. Only L<EV> is fully fork-aware. |
1240 | |
1540 | |
1241 | If you have to fork, you must either do so I<before> creating your first |
1541 | If you have to fork, you must either do so I<before> creating your first |
1242 | watcher OR you must not use AnyEvent at all in the child. |
1542 | watcher OR you must not use AnyEvent at all in the child. |
1243 | |
1543 | |
1244 | |
1544 | |
… | |
… | |
1256 | |
1556 | |
1257 | BEGIN { delete $ENV{PERL_ANYEVENT_MODEL} } |
1557 | BEGIN { delete $ENV{PERL_ANYEVENT_MODEL} } |
1258 | |
1558 | |
1259 | use AnyEvent; |
1559 | use AnyEvent; |
1260 | |
1560 | |
|
|
1561 | Similar considerations apply to $ENV{PERL_ANYEVENT_VERBOSE}, as that can |
|
|
1562 | be used to probe what backend is used and gain other information (which is |
|
|
1563 | probably even less useful to an attacker than PERL_ANYEVENT_MODEL). |
|
|
1564 | |
1261 | |
1565 | |
1262 | =head1 SEE ALSO |
1566 | =head1 SEE ALSO |
1263 | |
1567 | |
1264 | Event modules: L<Coro::EV>, L<EV>, L<EV::Glib>, L<Glib::EV>, |
1568 | Utility functions: L<AnyEvent::Util>. |
1265 | L<Coro::Event>, L<Event>, L<Glib::Event>, L<Glib>, L<Coro>, L<Tk>, |
1569 | |
|
|
1570 | Event modules: L<EV>, L<EV::Glib>, L<Glib::EV>, L<Event>, L<Glib::Event>, |
1266 | L<Event::Lib>, L<Qt>, L<POE>. |
1571 | L<Glib>, L<Tk>, L<Event::Lib>, L<Qt>, L<POE>. |
1267 | |
1572 | |
1268 | Implementations: L<AnyEvent::Impl::CoroEV>, L<AnyEvent::Impl::EV>, |
1573 | Implementations: L<AnyEvent::Impl::EV>, L<AnyEvent::Impl::Event>, |
1269 | L<AnyEvent::Impl::CoroEvent>, L<AnyEvent::Impl::Event>, L<AnyEvent::Impl::Glib>, |
1574 | L<AnyEvent::Impl::Glib>, L<AnyEvent::Impl::Tk>, L<AnyEvent::Impl::Perl>, |
1270 | L<AnyEvent::Impl::Tk>, L<AnyEvent::Impl::Perl>, L<AnyEvent::Impl::EventLib>, |
1575 | L<AnyEvent::Impl::EventLib>, L<AnyEvent::Impl::Qt>, |
1271 | L<AnyEvent::Impl::Qt>, L<AnyEvent::Impl::POE>. |
1576 | L<AnyEvent::Impl::POE>. |
1272 | |
1577 | |
|
|
1578 | Non-blocking file handles, sockets, TCP clients and |
|
|
1579 | servers: L<AnyEvent::Handle>, L<AnyEvent::Socket>. |
|
|
1580 | |
|
|
1581 | Asynchronous DNS: L<AnyEvent::DNS>. |
|
|
1582 | |
|
|
1583 | Coroutine support: L<Coro>, L<Coro::AnyEvent>, L<Coro::EV>, L<Coro::Event>, |
|
|
1584 | |
1273 | Nontrivial usage examples: L<Net::FCP>, L<Net::XMPP2>. |
1585 | Nontrivial usage examples: L<Net::FCP>, L<Net::XMPP2>, L<AnyEvent::DNS>. |
1274 | |
1586 | |
1275 | |
1587 | |
1276 | =head1 AUTHOR |
1588 | =head1 AUTHOR |
1277 | |
1589 | |
1278 | Marc Lehmann <schmorp@schmorp.de> |
1590 | Marc Lehmann <schmorp@schmorp.de> |