--- AnyEvent/README 2009/08/21 11:59:24 1.53 +++ AnyEvent/README 2010/06/06 10:13:57 1.62 @@ -7,7 +7,10 @@ SYNOPSIS use AnyEvent; - # file descriptor readable + # if you prefer function calls, look at the AE manpage for + # an alternative API. + + # file handle or descriptor readable my $w = AnyEvent->io (fh => $fh, poll => "r", cb => sub { ... }); # one-shot or repeating timers @@ -356,6 +359,14 @@ When this is the case, you can call this method, which will update the event loop's idea of "current time". + A typical example would be a script in a web server (e.g. + "mod_perl") - when mod_perl executes the script, then the event loop + will have the wrong idea about the "current time" (being potentially + far in the past, when the script ran the last time). In that case + you should arrange a call to "AnyEvent->now_update" each time the + web server process wakes up again (e.g. at the start of your script, + or in a handler). + Note that updating the time *might* cause some events to be handled. SIGNAL WATCHERS @@ -386,6 +397,21 @@ my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 }); + Restart Behaviour + While restart behaviour is up to the event loop implementation, most + will not restart syscalls (that includes Async::Interrupt and AnyEvent's + pure perl implementation). + + Safe/Unsafe Signals + Perl signals can be either "safe" (synchronous to opcode handling) or + "unsafe" (asynchronous) - the former might get delayed indefinitely, the + latter might corrupt your memory. + + AnyEvent signal handlers are, in addition, synchronous to the event + loop, i.e. they will not interrupt your running perl program but will + only be called as part of the normal event handling (just like timer, + I/O etc. callbacks, too). + Signal Races, Delays and Workarounds Many event loops (e.g. Glib, Tk, Qt, IO::Async) do not support attaching callbacks to signals in a generic way, which is a pity, as you cannot do @@ -465,18 +491,21 @@ IDLE WATCHERS $w = AnyEvent->idle (cb => ); - Sometimes there is a need to do something, but it is not so important to - do it instantly, but only when there is nothing better to do. This - "nothing better to do" is usually defined to be "no other events need - attention by the event loop". - - Idle watchers ideally get invoked when the event loop has nothing better - to do, just before it would block the process to wait for new events. - Instead of blocking, the idle watcher is invoked. - - Most event loops unfortunately do not really support idle watchers (only - EV, Event and Glib do it in a usable fashion) - for the rest, AnyEvent - will simply call the callback "from time to time". + Repeatedly invoke the callback after the process becomes idle, until + either the watcher is destroyed or new events have been detected. + + Idle watchers are useful when there is a need to do something, but it is + not so important (or wise) to do it instantly. The callback will be + invoked only when there is "nothing better to do", which is usually + defined as "all outstanding events have been handled and no new events + have been detected". That means that idle watchers ideally get invoked + when the event loop has just polled for new events but none have been + detected. Instead of blocking to wait for more events, the idle watchers + will be invoked. + + Unfortunately, most event loops do not really support idle watchers + (only EV, Event and Glib do it in a usable fashion) - for the rest, + AnyEvent will simply call the callback "from time to time". Example: read lines from STDIN, but only process them when the program is otherwise idle: @@ -512,8 +541,8 @@ event loop and will only block when necessary (usually when told by the user). - The instrument to do that is called a "condition variable", so called - because they represent a condition that must become true. + The tool to do that is called a "condition variable", so called because + they represent a condition that must become true. Now is probably a good time to look at the examples further below. @@ -528,13 +557,27 @@ as if it were a callback, read about the caveats in the description for the "->send" method). - Condition variables are similar to callbacks, except that you can - optionally wait for them. They can also be called merge points - points - in time where multiple outstanding events have been processed. And yet - another way to call them is transactions - each condition variable can - be used to represent a transaction, which finishes at some point and - delivers a result. And yet some people know them as "futures" - a - promise to compute/deliver something that you can wait for. + Since condition variables are the most complex part of the AnyEvent API, + here are some different mental models of what they are - pick the ones + you can connect to: + + * Condition variables are like callbacks - you can call them (and pass + them instead of callbacks). Unlike callbacks however, you can also + wait for them to be called. + + * Condition variables are signals - one side can emit or send them, + the other side can wait for them, or install a handler that is + called when the signal fires. + + * Condition variables are like "Merge Points" - points in your program + where you merge multiple independent results/control flows into one. + + * Condition variables represent a transaction - function that start + some kind of transaction can return them, leaving the caller the + choice between waiting in a blocking fashion, or setting a callback. + + * Condition variables represent future values, or promises to deliver + some result, long before the result is available. Condition variables are very useful to signal that something has finished, for example, if you write a module that does asynchronous http @@ -565,21 +608,21 @@ Example: wait for a timer. - # wait till the result is ready - my $result_ready = AnyEvent->condvar; + # condition: "wait till the timer is fired" + my $timer_fired = AnyEvent->condvar; - # do something such as adding a timer - # or socket watcher the calls $result_ready->send - # when the "result" is ready. + # create the timer - we could wait for, say + # a handle becomign ready, or even an + # AnyEvent::HTTP request to finish, but # in this case, we simply use a timer: my $w = AnyEvent->timer ( after => 1, - cb => sub { $result_ready->send }, + cb => sub { $timer_fired->send }, ); # this "blocks" (while handling events) till the callback # calls ->send - $result_ready->recv; + $timer_fired->recv; Example: wait for a timer, but take advantage of the fact that condition variables are also callable directly. @@ -898,7 +941,7 @@ detected, and the array will be ignored. Best use "AnyEvent::post_detect { BLOCK }" when your application - allows it,as it takes care of these details. + allows it, as it takes care of these details. This variable is mainly useful for modules that can do something useful when AnyEvent is used and thus want to know when it is @@ -906,6 +949,19 @@ provides the means to hook into AnyEvent passively, without loading it. + Example: To load Coro::AnyEvent whenever Coro and AnyEvent are used + together, you could put this into Coro (this is the actual code used + by Coro to accomplish this): + + if (defined $AnyEvent::MODEL) { + # AnyEvent already initialised, so load Coro::AnyEvent + require Coro::AnyEvent; + } else { + # AnyEvent not yet initialised, so make sure to load Coro::AnyEvent + # as soon as it is + push @AnyEvent::post_detect, sub { require Coro::AnyEvent }; + } + WHAT TO DO IN A MODULE As a module author, you should "use AnyEvent" and call AnyEvent methods freely, but you should not load a specific event module or rely on it. @@ -967,7 +1023,7 @@ The following is a non-exhaustive list of additional modules that use AnyEvent as a client and can therefore be mixed easily with other AnyEvent modules and other event loops in the same program. Some of the - modules come with AnyEvent, most are available via CPAN. + modules come as part of AnyEvent, the others are available via CPAN. AnyEvent::Util Contains various utility functions that replace often-used but @@ -988,50 +1044,44 @@ AnyEvent::DNS Provides rich asynchronous DNS resolver capabilities. - AnyEvent::HTTP - A simple-to-use HTTP library that is capable of making a lot of - concurrent HTTP requests. - - AnyEvent::HTTPD - Provides a simple web application server framework. - - AnyEvent::FastPing - The fastest ping in the west. + AnyEvent::HTTP, AnyEvent::IRC, AnyEvent::XMPP, AnyEvent::GPSD, + AnyEvent::IGS, AnyEvent::FCP + Implement event-based interfaces to the protocols of the same name + (for the curious, IGS is the International Go Server and FCP is the + Freenet Client Protocol). + + AnyEvent::Handle::UDP + Here be danger! + + As Pauli would put it, "Not only is it not right, it's not even + wrong!" - there are so many things wrong with AnyEvent::Handle::UDP, + most notably it's use of a stream-based API with a protocol that + isn't streamable, that the only way to improve it is to delete it. + + It features data corruption (but typically only under load) and + general confusion. On top, the author is not only clueless about UDP + but also fact-resistant - some gems of his understanding: "connect + doesn't work with UDP", "UDP packets are not IP packets", "UDP only + has datagrams, not packets", "I don't need to implement proper error + checking as UDP doesn't support error checking" and so on - he + doesn't even understand what's wrong with his module when it is + explained to him. AnyEvent::DBI - Executes DBI requests asynchronously in a proxy process. + Executes DBI requests asynchronously in a proxy process for you, + notifying you in an event-bnased way when the operation is finished. AnyEvent::AIO - Truly asynchronous I/O, should be in the toolbox of every event - programmer. AnyEvent::AIO transparently fuses IO::AIO and AnyEvent - together. - - AnyEvent::BDB - Truly asynchronous Berkeley DB access. AnyEvent::BDB transparently - fuses BDB and AnyEvent together. - - AnyEvent::GPSD - A non-blocking interface to gpsd, a daemon delivering GPS - information. - - AnyEvent::IRC - AnyEvent based IRC client module family (replacing the older - Net::IRC3). - - AnyEvent::XMPP - AnyEvent based XMPP (Jabber protocol) module family (replacing the - older Net::XMPP2>. - - AnyEvent::IGS - A non-blocking interface to the Internet Go Server protocol (used by - App::IGS). - - Net::FCP - AnyEvent-based implementation of the Freenet Client Protocol, - birthplace of AnyEvent. + Truly asynchronous (as opposed to non-blocking) I/O, should be in + the toolbox of every event programmer. AnyEvent::AIO transparently + fuses IO::AIO and AnyEvent together, giving AnyEvent access to + event-based file I/O, and much more. - Event::ExecFlow - High level API for event-based execution flow control. + AnyEvent::HTTPD + A simple embedded webserver. + + AnyEvent::FastPing + The fastest ping in the west. Coro Has special support for AnyEvent via Coro::AnyEvent. @@ -1039,7 +1089,7 @@ SIMPLIFIED AE API Starting with version 5.0, AnyEvent officially supports a second, much simpler, API that is designed to reduce the calling, typing and memory - overhead. + overhead by using function call syntax and a fixed number of parameters. See the AE manpage for details. @@ -1230,16 +1280,9 @@ }, ); - my $time_watcher; # can only be used once - - sub new_timer { - $timer = AnyEvent->timer (after => 1, cb => sub { - warn "timeout\n"; # print 'timeout' about every second - &new_timer; # and restart the time - }); - } - - new_timer; # create first timer + my $time_watcher = AnyEvent->timer (after => 1, interval => 1, cb => sub { + warn "timeout\n"; # print 'timeout' at most every second + }); $cv->recv; # wait until user enters /^q/i @@ -1321,7 +1364,7 @@ exceptions) that occurred during request processing. The "result" method detects whether an exception as thrown (it is stored inside the $txn object) and just throws the exception, which means connection errors and - other problems get reported tot he code that tries to use the result, + other problems get reported to the code that tries to use the result, not in a random callback. All of this enables the following usage styles: @@ -1667,13 +1710,13 @@ backend easily beats IO::Lambda and POE. And even the 100% non-blocking version written using the high-level (and - slow :) AnyEvent::Handle abstraction beats both POE and IO::Lambda by a - large margin, even though it does all of DNS, tcp-connect and socket I/O - in a non-blocking way. + slow :) AnyEvent::Handle abstraction beats both POE and IO::Lambda + higher level ("unoptimised") abstractions by a large margin, even though + it does all of DNS, tcp-connect and socket I/O in a non-blocking way. The two AnyEvent benchmarks programs can be found as eg/ae0.pl and eg/ae2.pl in the AnyEvent distribution, the remaining benchmarks are - part of the IO::lambda distribution and were used without any changes. + part of the IO::Lambda distribution and were used without any changes. SIGNALS AnyEvent currently installs handlers for these signals: @@ -1710,8 +1753,8 @@ That does not mean that AnyEvent won't take advantage of some additional modules if they are installed. - This section epxlains which additional modules will be used, and how - they affect AnyEvent's operetion. + This section explains which additional modules will be used, and how + they affect AnyEvent's operation. Async::Interrupt This slightly arcane module is used to implement fast signal @@ -1724,7 +1767,7 @@ If this module is available, then it will be used to implement signal catching, which means that signals will not be delayed, and the event loop will not be interrupted regularly, which is more - efficient (And good for battery life on laptops). + efficient (and good for battery life on laptops). This affects not just the pure-perl event loop, but also other event loops that have no signal handling on their own (e.g. Glib, Tk, Qt). @@ -1744,6 +1787,9 @@ You can even embed Glib/Gtk2 in it (or vice versa, see EV::Glib and Glib::EV). + If you only use backends that rely on another event loop (e.g. + "Tk"), then this module will do nothing for you. + Guard The guard module, when used, will be used to implement "AnyEvent::Util::guard". This speeds up guards considerably (and @@ -1751,13 +1797,10 @@ operation much. It is purely used for performance. JSON and JSON::XS - This module is required when you want to read or write JSON data via - AnyEvent::Handle. It is also written in pure-perl, but can take - advantage of the ultra-high-speed JSON::XS module when it is - installed. - - In fact, AnyEvent::Handle will use JSON::XS by default if it is - installed. + One of these modules is required when you want to read or write JSON + data via AnyEvent::Handle. JSON is also written in pure-perl, but + can take advantage of the ultra-high-speed JSON::XS module when it + is installed. Net::SSLeay Implementing TLS/SSL in Perl is certainly interesting, but not very @@ -1773,13 +1816,31 @@ FORK Most event libraries are not fork-safe. The ones who are usually are - because they rely on inefficient but fork-safe "select" or "poll" calls. - Only EV is fully fork-aware. + because they rely on inefficient but fork-safe "select" or "poll" calls + - higher performance APIs such as BSD's kqueue or the dreaded Linux + epoll are usually badly thought-out hacks that are incompatible with + fork in one way or another. Only EV is fully fork-aware and ensures that + you continue event-processing in both parent and child (or both, if you + know what you are doing). + + This means that, in general, you cannot fork and do event processing in + the child if the event library was initialised before the fork (which + usually happens when the first AnyEvent watcher is created, or the + library is loaded). If you have to fork, you must either do so *before* creating your first watcher OR you must not use AnyEvent at all in the child OR you must do something completely out of the scope of AnyEvent. + The problem of doing event processing in the parent *and* the child is + much more complicated: even for backends that *are* fork-aware or + fork-safe, their behaviour is not usually what you want: fork clones all + watchers, that means all timers, I/O watchers etc. are active in both + parent and child, which is almost never what you want. USing "exec" to + start worker children from some kind of manage rprocess is usually + preferred, because it is much easier and cleaner, at the expense of + having to have another binary. + SECURITY CONSIDERATIONS AnyEvent can be forced to load any event model via $ENV{PERL_ANYEVENT_MODEL}. While this cannot (to my knowledge) be used