AnyEvent

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

        - the memleak fix in 7.03 caused resolving via /etc/hosts to always
          fail on first use (reported and testcase by Andrew Whatson).
        - expose AnyEvent::Log::format_time, and allow users to redefine it.
        - expose AnyEvent::Log::default_format, and allow redefinition.
        - expose AnyEvent::Log::fatal_exit, to allow redefinition.
	- AnyEvent::Debug shell can now run coro shell commands, if available.
	- t/63* tests were wrongly in MANIFEST.
        - kernel.org's finger server went MIA, switch to freebsd.org and
          icculus.org.
        - clarify that IO::AIO and AnyEvent::AIO are needed for AnyEvent::IO
          to function asynchronously (reported by Daniel Carosone).
        - hard-disable $^W in most tests, it generates too much garbage output.
        - use a (hopefully) more future-proof method to emulate common::sense.
        - upgrade to UTS-46:6.2.0.
        - switch to INSTLIB from INSTLIBDIR, as INSTLIBDIR was wrongly
          documented. should not affect anything.

7.04 Thu Nov 15 02:23:58 CET 2012
	- debugging code left in.

7.03 Thu Nov 15 02:16:11 CET 2012

Changes  view on Meta::CPAN

	- use File::Spec to get the tmpdir in t/*, to avoid needless
          failures on (most, not mine :) windows boxes.
        - new handle read types: tls_detect and tls_autostart.

7.0  Fri Apr 13 06:33:30 CEST 2012
        - child watchers are broken in POE 1.352 (also many earlier
          versions) and there seems to be no way to work around it, as POE
          itself is inherently racy. Document this regression and add a delay
          in t/68_poe_03_child.t for the time being.
	- new module AnyEvent::IO, that is a frontend to either a pure-perl
          synchronous I/O implementation (AnyEvent::IO::Perl), or to the
          asynchronous I/O extension IO::AIO (AnyEvent::IO::IOAIO).
        - load /etc/hosts only when DNS has no answer.
        - stat /etc/hosts on every access and reload it if it changed.
        - load /etc/hosts via AnyEvent::IO - potentially asynchronous.
        - fix a buggy croak in the dh parameter reading in AnyEvent::TLS.
        - AnyEvent::Log log_to_file and log_to_path now use AnyEvent::IO. As
          a side effect, they now use true appending as opposed to libc
          appending, and the file might not have been opened when the function
          returns.
        - the default logging level was not properly documented in a variety of
          places, this has hopefully been rectified.
	- updated uts46data.pl for unicode 6.1.0.
        - made log messages generated by AnyEvent submodules not
          include the package name anymore, as it will be logged

Changes  view on Meta::CPAN


4.411 Sun Jun  7 18:48:02 CEST 2009
	- do not try to use F_SETFD on windows.

4.41  Thu May 14 06:40:11 CEST 2009
        - work around issues in older perls (5.8.0?) when
          a signal handler is deleted from the %SIG hash.
        - use POSIX::_exit in child test, to avoid running
          destructors.
        - speed up CHLD handling by relying on SIGCHLD being
          synchronously delivered, even when we roll our own
          implementation.
	- AnyEvent::DNS: add the "dname" resource record name
          for cosmetic reasons.

4.4   Sun Apr 26 20:12:33 CEST 2009
	- implemented idle watchers, where applicable.
	- AnyEvent->time died when Event backend was in use.
        - fix a memleak in the Tk backend.
        - sped up Tk timer handling.
        - clip negative "after" values to 0 in AnyEvent::Impl::Event

Changes  view on Meta::CPAN

        - add AnyEvent->now_update.

4.351 Sat Apr 11 07:56:14 CEST 2009
        - actually make the signal pipe work under win32.
        - localise $! in signal handler to avoid changing $!, although
          perl itself does not seem to save/restore errno either.
	- set the cloexec flag on the signal pipe (normally set by perl too).

4.35  Fri Mar 27 11:48:20 CET 2009
        - event models relying on AnyEvent's signal watcher emulation did
          invoke the callback asynchronously, contradicting documentation
          and causing signals to get lost (this includes AnyEvent's own
          event loop). AnyEvent now uses the standard pipe trick to make
          callback execution synchronous to the event loop.
        - AnyEvent::Handle didn't free TLS context data on DESTROY
          (patch by Pavel Shaydo).
        - work around the ever-incompatibly-changing API of MakeMaker.
        - document that changing global variables without restoring them
          is a bad idea in Perl (noted by Adam Rosenstein).
        - AnyEvent::Strict now barfs if ->io is passed a file.

4.34  Thu Feb 12 18:32:45 CET 2009
	- separately buffer TLS read data, as otherwise the read queue could
          deadlock as receiving data is not expected while draining the

Changes  view on Meta::CPAN

2.9  Mon Jan 28 13:31:54 CET 2008
	- update for EV 3.0 API changes.

2.8  Sun Nov 25 15:06:03 CET 2007
	- waitpid can validly return 0. accept this fact of life
          instead of reporting it to any watchers.

2.7  Fri Nov 23 11:41:14 CET 2007
	- force use of AnyEvent::Impl::Perl in testsuite, there is
          too much breakage outside AnyEvent.
        - deliver signals synchronously in AnyEvent::Impl::Perl
          or any other event loop that relies on AnyEvents child
          watcher emulation. *Could* help with hanging testsuite
          (except when Event or EV are installed).

2.6  Fri Nov  9 20:36:35 CET 2007
	- fix bug in testsuite.
        - move EV adaptor modules to AnyEvent.
        - add Coro+EV adaptor module.

2.55 Tue Nov  6 17:41:32 CET 2007

README  view on Meta::CPAN

    AnyEvent cannot change this, but it can hide the differences between
    those event loops.

    The goal of AnyEvent is to offer module authors the ability to do event
    programming (waiting for I/O or timer events) without subscribing to a
    religion, a way of living, and most importantly: without forcing your
    module users into the same thing by forcing them to use the same event
    model you use.

    For modules like POE or IO::Async (which is a total misnomer as it is
    actually doing all I/O *synchronously*...), using them in your module is
    like joining a cult: After you join, you are dependent on them and you
    cannot use anything else, as they are simply incompatible to everything
    that isn't them. What's worse, all the potential users of your module
    are *also* forced to use the same event loop you use.

    AnyEvent is different: AnyEvent + POE works fine. AnyEvent + Glib works
    fine. AnyEvent + Tk works fine etc. etc. but none of these work together
    with the rest: POE + EV? No go. Tk + Event? No go. Again: if your module
    uses one of those, every user of your module has to use it, too. But if
    your module uses AnyEvent, it works transparently with all event models

README  view on Meta::CPAN

    AnyEvent, too, so it is future-proof).

    In addition to being free of having to use *the one and only true event
    model*, AnyEvent also is free of bloat and policy: with POE or similar
    modules, you get an enormous amount of code and strict rules you have to
    follow. AnyEvent, on the other hand, is lean and to the point, by only
    offering the functionality that is necessary, in as thin as a wrapper as
    technically possible.

    Of course, AnyEvent comes with a big (and fully optional!) toolbox of
    useful functionality, such as an asynchronous DNS resolver, 100%
    non-blocking connects (even with TLS/SSL, IPv6 and on broken platforms
    such as Windows) and lots of real-world knowledge and workarounds for
    platform bugs and differences.

    Now, if you *do want* lots of policy (this can arguably be somewhat
    useful) and you want to force your users to use the one and only event
    model, you should *not* use this module.

DESCRIPTION
    AnyEvent provides a uniform interface to various event loops. This

README  view on Meta::CPAN


    You can watch for signals using a signal watcher, "signal" is the signal
    *name* in uppercase and without any "SIG" prefix, "cb" is the Perl
    callback to be invoked whenever a signal occurs.

    Although the callback might get passed parameters, their value and
    presence is undefined and you cannot rely on them. Portable AnyEvent
    callbacks cannot use arguments passed to signal watcher callbacks.

    Multiple signal occurrences can be clumped together into one callback
    invocation, and callback invocation will be synchronous. Synchronous
    means that it might take a while until the signal gets handled by the
    process, but it is guaranteed not to interrupt any other callbacks.

    The main advantage of using these watchers is that you can share a
    signal between multiple watchers, and AnyEvent will ensure that signals
    will not interrupt your program at bad times.

    This watcher might use %SIG (depending on the event loop used), so
    programs overwriting those signals directly will likely not work
    correctly.

README  view on Meta::CPAN

    Example: exit on SIGINT

       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 delay signal delivery
    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
    race-free signal handling in perl, requiring C libraries for this.
    AnyEvent will try to do its best, which means in some cases, signals
    will be delayed. The maximum time a signal might be delayed is 10

README  view on Meta::CPAN

        where you merge multiple independent results/control flows into one.

    *   Condition variables represent a transaction - functions 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
    requests, then a condition variable would be the ideal candidate to
    signal the availability of results. The user can either act when the
    callback is called or can synchronously "->recv" for the results.

    You can also use them to simulate traditional event loops - for example,
    you can block your main program until an event occurs - for example, you
    could "->recv" in your main program until the user clicks the Quit
    button of your app, which would "->send" the "quit" event.

    Note that condition variables recurse into the event loop - if you have
    two pieces of code that call "->recv" in a round-robin fashion, you
    lose. Therefore, condition variables are good to export to your caller,
    but you should avoid making a blocking wait yourself, at least in

README  view on Meta::CPAN

       $timer_fired->recv;

    Example: wait for a timer, but take advantage of the fact that condition
    variables are also callable directly.

       my $done = AnyEvent->condvar;
       my $delay = AnyEvent->timer (after => 5, cb => $done);
       $done->recv;

    Example: Imagine an API that returns a condvar and doesn't support
    callbacks. This is how you make a synchronous call, for example from the
    main program:

       use AnyEvent::CouchDB;

       ...

       my @info = $couchdb->info->recv;

    And this is how you would just set a callback to be called whenever the
    results are available:

README  view on Meta::CPAN

    AnyEvent::postpone { BLOCK }
        Arranges for the block to be executed as soon as possible, but not
        before the call itself returns. In practise, the block will be
        executed just before the event loop polls for new events, or shortly
        afterwards.

        This function never returns anything (to make the "return postpone {
        ... }" idiom more useful.

        To understand the usefulness of this function, consider a function
        that asynchronously does something for you and returns some
        transaction object or guard to let you cancel the operation. For
        example, "AnyEvent::Socket::tcp_connect":

           # start a connection attempt unless one is active
           $self->{connect_guard} ||= AnyEvent::Socket::tcp_connect "www.example.net", 80, sub {
              delete $self->{connect_guard};
              ...
           };

        Imagine that this function could instantly call the callback, for

README  view on Meta::CPAN

        addresses and name resolution. Also functions to create non-blocking
        tcp connections or tcp servers, with IPv6 and SRV record support and
        more.

    AnyEvent::Handle (part of the AnyEvent distribution)
        Provide read and write buffers, manages watchers for reads and
        writes, supports raw and formatted I/O, I/O queued and fully
        transparent and non-blocking SSL/TLS (via AnyEvent::TLS).

    AnyEvent::DNS (part of the AnyEvent distribution)
        Provides rich asynchronous DNS resolver capabilities.

    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::AIO (part of the AnyEvent distribution)
        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.

    AnyEvent::Fork, AnyEvent::Fork::RPC, AnyEvent::Fork::Pool,
    AnyEvent::Fork::Remote
        These let you safely fork new subprocesses, either locally or
        remotely (e.g.v ia ssh), using some RPC protocol or not, without the
        limitations normally imposed by fork (AnyEvent works fine for
        example). Dynamically-resized worker pools are obviously included as

README  view on Meta::CPAN

        do just that in a portbale fashion, supporting inotify on GNU/Linux
        and some weird, without doubt broken, stuff on OS X to monitor
        files. It can fall back to blocking scans at regular intervals
        transparently on other platforms, so it's about as portable as it
        gets.

        (I haven't used it myself, but it seems the biggest problem with it
        is it quite bad performance).

    AnyEvent::DBI
        Executes DBI requests asynchronously in a proxy process for you,
        notifying you in an event-based way when the operation is finished.

    AnyEvent::FastPing
        The fastest ping in the west.

    Coro
        Has special support for AnyEvent via Coro::AnyEvent, which allows
        you to simply invert the flow control - don't call us, we will call
        you:

README  view on Meta::CPAN

        appropriately).

        For example, to force the pure perl model (AnyEvent::Loop::Perl) you
        could start your program like this:

           PERL_ANYEVENT_MODEL=Perl perl ...

    "PERL_ANYEVENT_IO_MODEL"
        The current file I/O model - see AnyEvent::IO for more info.

        At the moment, only "Perl" (small, pure-perl, synchronous) and
        "IOAIO" (truly asynchronous) are supported. The default is "IOAIO"
        if AnyEvent::AIO can be loaded, otherwise it is "Perl".

    "PERL_ANYEVENT_PROTOCOLS"
        Used by both AnyEvent::DNS and AnyEvent::Socket to determine
        preferences for IPv4 or IPv6. The default is unspecified (and might
        change, or be the result of auto probing).

        Must be set to a comma-separated list of protocols or address
        families, current supported: "ipv4" and "ipv6". Only protocols
        mentioned will be used, and preference will be given to protocols

README  view on Meta::CPAN

       POE/select, optimized   0.404 sec

       AnyEvent/select/nb      0.085 sec
       AnyEvent/EV/nb          0.068 sec
          +state machine       0.134 sec

    The benchmark is also a bit unfair (my fault): the IO::Lambda/POE
    benchmarks actually make blocking connects and use 100% blocking I/O,
    defeating the purpose of an event-based solution. All of the newly
    written AnyEvent benchmarks use 100% non-blocking connects (using
    AnyEvent::Socket::tcp_connect and the asynchronous pure perl DNS
    resolver), so AnyEvent is at a disadvantage here, as non-blocking
    connects generally require a lot more bookkeeping and event handling
    than blocking connects (which involve a single syscall only).

    The last AnyEvent benchmark additionally uses AnyEvent::Handle, which
    offers similar expressive power as POE and IO::Lambda, using
    conventional Perl syntax. This means that both the echo server and the
    client are 100% non-blocking, further placing it at a disadvantage.

    As you can see, the AnyEvent + EV combination even beats the

README  view on Meta::CPAN

        the help of AnyEvent::TLS), gains the ability to do TLS/SSL.

    Time::HiRes
        This module is part of perl since release 5.008. It will be used
        when the chosen event library does not come with a timing source of
        its own. The pure-perl event loop (AnyEvent::Loop) will additionally
        load it to try to use a monotonic clock for timing stability.

    AnyEvent::AIO (and IO::AIO)
        The default implementation of AnyEvent::IO is to do I/O
        synchronously, stopping programs while they access the disk, which
        is fine for a lot of programs.

        Installing AnyEvent::AIO (and its IO::AIO dependency) makes it
        switch to a true asynchronous implementation, so event processing
        can continue even while waiting for disk I/O.

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
    - 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).

README  view on Meta::CPAN


    Implementations: AnyEvent::Impl::EV, AnyEvent::Impl::Event,
    AnyEvent::Impl::Glib, AnyEvent::Impl::Tk, AnyEvent::Impl::Perl,
    AnyEvent::Impl::EventLib, AnyEvent::Impl::Qt, AnyEvent::Impl::POE,
    AnyEvent::Impl::IOAsync, AnyEvent::Impl::Irssi, AnyEvent::Impl::FLTK,
    AnyEvent::Impl::Cocoa, AnyEvent::Impl::UV.

    Non-blocking handles, pipes, stream sockets, TCP clients and servers:
    AnyEvent::Handle, AnyEvent::Socket, AnyEvent::TLS.

    Asynchronous File I/O: AnyEvent::IO.

    Asynchronous DNS: AnyEvent::DNS.

    Thread support: Coro, Coro::AnyEvent, Coro::EV, Coro::Event.

    Nontrivial usage examples: AnyEvent::GPSD, AnyEvent::IRC,
    AnyEvent::HTTP.

AUTHOR
       Marc Lehmann <schmorp@schmorp.de>
       http://anyevent.schmorp.de

lib/AnyEvent.pm  view on Meta::CPAN

cannot change this, but it can hide the differences between those event
loops.

The goal of AnyEvent is to offer module authors the ability to do event
programming (waiting for I/O or timer events) without subscribing to a
religion, a way of living, and most importantly: without forcing your
module users into the same thing by forcing them to use the same event
model you use.

For modules like POE or IO::Async (which is a total misnomer as it is
actually doing all I/O I<synchronously>...), using them in your module is
like joining a cult: After you join, you are dependent on them and you
cannot use anything else, as they are simply incompatible to everything
that isn't them. What's worse, all the potential users of your
module are I<also> forced to use the same event loop you use.

AnyEvent is different: AnyEvent + POE works fine. AnyEvent + Glib works
fine. AnyEvent + Tk works fine etc. etc. but none of these work together
with the rest: POE + EV? No go. Tk + Event? No go. Again: if your module
uses one of those, every user of your module has to use it, too. But if
your module uses AnyEvent, it works transparently with all event models it

lib/AnyEvent.pm  view on Meta::CPAN

so it is future-proof).

In addition to being free of having to use I<the one and only true event
model>, AnyEvent also is free of bloat and policy: with POE or similar
modules, you get an enormous amount of code and strict rules you have to
follow. AnyEvent, on the other hand, is lean and to the point, by only
offering the functionality that is necessary, in as thin as a wrapper as
technically possible.

Of course, AnyEvent comes with a big (and fully optional!) toolbox
of useful functionality, such as an asynchronous DNS resolver, 100%
non-blocking connects (even with TLS/SSL, IPv6 and on broken platforms
such as Windows) and lots of real-world knowledge and workarounds for
platform bugs and differences.

Now, if you I<do want> lots of policy (this can arguably be somewhat
useful) and you want to force your users to use the one and only event
model, you should I<not> use this module.

=head1 DESCRIPTION

lib/AnyEvent.pm  view on Meta::CPAN


You can watch for signals using a signal watcher, C<signal> is the signal
I<name> in uppercase and without any C<SIG> prefix, C<cb> is the Perl
callback to be invoked whenever a signal occurs.

Although the callback might get passed parameters, their value and
presence is undefined and you cannot rely on them. Portable AnyEvent
callbacks cannot use arguments passed to signal watcher callbacks.

Multiple signal occurrences can be clumped together into one callback
invocation, and callback invocation will be synchronous. Synchronous means
that it might take a while until the signal gets handled by the process,
but it is guaranteed not to interrupt any other callbacks.

The main advantage of using these watchers is that you can share a signal
between multiple watchers, and AnyEvent will ensure that signals will not
interrupt your program at bad times.

This watcher might use C<%SIG> (depending on the event loop used),
so programs overwriting those signals directly will likely not work
correctly.

lib/AnyEvent.pm  view on Meta::CPAN

   my $w = AnyEvent->signal (signal => "INT", cb => sub { exit 1 });

=head3 Restart Behaviour

While restart behaviour is up to the event loop implementation, most will
not restart syscalls (that includes L<Async::Interrupt> and AnyEvent's
pure perl implementation).

=head3 Safe/Unsafe Signals

Perl signals can be either "safe" (synchronous to opcode handling)
or "unsafe" (asynchronous) - the former might delay signal delivery
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).

=head3 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 race-free signal handling in perl, requiring
C libraries for this. AnyEvent will try to do its best, which

lib/AnyEvent.pm  view on Meta::CPAN

=item * Condition variables represent a transaction - functions that start
some kind of transaction can return them, leaving the caller the choice
between waiting in a blocking fashion, or setting a callback.

=item * Condition variables represent future values, or promises to deliver
some result, long before the result is available.

=back

Condition variables are very useful to signal that something has finished,
for example, if you write a module that does asynchronous http requests,
then a condition variable would be the ideal candidate to signal the
availability of results. The user can either act when the callback is
called or can synchronously C<< ->recv >> for the results.

You can also use them to simulate traditional event loops - for example,
you can block your main program until an event occurs - for example, you
could C<< ->recv >> in your main program until the user clicks the Quit
button of your app, which would C<< ->send >> the "quit" event.

Note that condition variables recurse into the event loop - if you have
two pieces of code that call C<< ->recv >> in a round-robin fashion, you
lose. Therefore, condition variables are good to export to your caller, but
you should avoid making a blocking wait yourself, at least in callbacks,

lib/AnyEvent.pm  view on Meta::CPAN

   $timer_fired->recv;

Example: wait for a timer, but take advantage of the fact that condition
variables are also callable directly.

   my $done = AnyEvent->condvar;
   my $delay = AnyEvent->timer (after => 5, cb => $done);
   $done->recv;

Example: Imagine an API that returns a condvar and doesn't support
callbacks. This is how you make a synchronous call, for example from
the main program:

   use AnyEvent::CouchDB;

   ...

   my @info = $couchdb->info->recv;

And this is how you would just set a callback to be called whenever the
results are available:

lib/AnyEvent.pm  view on Meta::CPAN

=item AnyEvent::postpone { BLOCK }

Arranges for the block to be executed as soon as possible, but not before
the call itself returns. In practise, the block will be executed just
before the event loop polls for new events, or shortly afterwards.

This function never returns anything (to make the C<return postpone { ...
}> idiom more useful.

To understand the usefulness of this function, consider a function that
asynchronously does something for you and returns some transaction
object or guard to let you cancel the operation. For example,
C<AnyEvent::Socket::tcp_connect>:

   # start a connection attempt unless one is active
   $self->{connect_guard} ||= AnyEvent::Socket::tcp_connect "www.example.net", 80, sub {
      delete $self->{connect_guard};
      ...
   };

Imagine that this function could instantly call the callback, for

lib/AnyEvent.pm  view on Meta::CPAN

connections or tcp servers, with IPv6 and SRV record support and more.

=item L<AnyEvent::Handle> (part of the AnyEvent distribution)

Provide read and write buffers, manages watchers for reads and writes,
supports raw and formatted I/O, I/O queued and fully transparent and
non-blocking SSL/TLS (via L<AnyEvent::TLS>).

=item L<AnyEvent::DNS> (part of the AnyEvent distribution)

Provides rich asynchronous DNS resolver capabilities.

=item L<AnyEvent::HTTP>, L<AnyEvent::IRC>, L<AnyEvent::XMPP>, L<AnyEvent::GPSD>, L<AnyEvent::IGS>, L<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).

=item L<AnyEvent::AIO> (part of the AnyEvent distribution)

Truly asynchronous (as opposed to non-blocking) I/O, should be in the
toolbox of every event programmer. AnyEvent::AIO transparently fuses
L<IO::AIO> and AnyEvent together, giving AnyEvent access to event-based
file I/O, and much more.

=item L<AnyEvent::Fork>, L<AnyEvent::Fork::RPC>, L<AnyEvent::Fork::Pool>, L<AnyEvent::Fork::Remote>

These let you safely fork new subprocesses, either locally or
remotely (e.g.v ia ssh), using some RPC protocol or not, without
the limitations normally imposed by fork (AnyEvent works fine for
example). Dynamically-resized worker pools are obviously included as well.

lib/AnyEvent.pm  view on Meta::CPAN

do just that in a portbale fashion, supporting inotify on GNU/Linux and
some weird, without doubt broken, stuff on OS X to monitor files. It can
fall back to blocking scans at regular intervals transparently on other
platforms, so it's about as portable as it gets.

(I haven't used it myself, but it seems the biggest problem with it is
it quite bad performance).

=item L<AnyEvent::DBI>

Executes L<DBI> requests asynchronously in a proxy process for you,
notifying you in an event-based way when the operation is finished.

=item L<AnyEvent::FastPing>

The fastest ping in the west.

=item L<Coro>

Has special support for AnyEvent via L<Coro::AnyEvent>, which allows you
to simply invert the flow control - don't call us, we will call you:

lib/AnyEvent.pm  view on Meta::CPAN


For example, to force the pure perl model (L<AnyEvent::Loop::Perl>) you
could start your program like this:

   PERL_ANYEVENT_MODEL=Perl perl ...

=item C<PERL_ANYEVENT_IO_MODEL>

The current file I/O model - see L<AnyEvent::IO> for more info.

At the moment, only C<Perl> (small, pure-perl, synchronous) and
C<IOAIO> (truly asynchronous) are supported. The default is C<IOAIO> if
L<AnyEvent::AIO> can be loaded, otherwise it is C<Perl>.

=item C<PERL_ANYEVENT_PROTOCOLS>

Used by both L<AnyEvent::DNS> and L<AnyEvent::Socket> to determine preferences
for IPv4 or IPv6. The default is unspecified (and might change, or be the result
of auto probing).

Must be set to a comma-separated list of protocols or address families,
current supported: C<ipv4> and C<ipv6>. Only protocols mentioned will be

lib/AnyEvent.pm  view on Meta::CPAN

   POE/select, optimized   0.404 sec

   AnyEvent/select/nb      0.085 sec
   AnyEvent/EV/nb          0.068 sec
      +state machine       0.134 sec

The benchmark is also a bit unfair (my fault): the IO::Lambda/POE
benchmarks actually make blocking connects and use 100% blocking I/O,
defeating the purpose of an event-based solution. All of the newly
written AnyEvent benchmarks use 100% non-blocking connects (using
AnyEvent::Socket::tcp_connect and the asynchronous pure perl DNS
resolver), so AnyEvent is at a disadvantage here, as non-blocking connects
generally require a lot more bookkeeping and event handling than blocking
connects (which involve a single syscall only).

The last AnyEvent benchmark additionally uses L<AnyEvent::Handle>, which
offers similar expressive power as POE and IO::Lambda, using conventional
Perl syntax. This means that both the echo server and the client are 100%
non-blocking, further placing it at a disadvantage.

As you can see, the AnyEvent + EV combination even beats the

lib/AnyEvent.pm  view on Meta::CPAN


=item L<Time::HiRes>

This module is part of perl since release 5.008. It will be used when the
chosen event library does not come with a timing source of its own. The
pure-perl event loop (L<AnyEvent::Loop>) will additionally load it to
try to use a monotonic clock for timing stability.

=item L<AnyEvent::AIO> (and L<IO::AIO>)

The default implementation of L<AnyEvent::IO> is to do I/O synchronously,
stopping programs while they access the disk, which is fine for a lot of
programs.

Installing AnyEvent::AIO (and its IO::AIO dependency) makes it switch to
a true asynchronous implementation, so event processing can continue even
while waiting for disk I/O.

=back


=head1 FORK

Most event libraries are not fork-safe. The ones who are usually are
because they rely on inefficient but fork-safe C<select> or C<poll> calls
- higher performance APIs such as BSD's kqueue or the dreaded Linux epoll

lib/AnyEvent.pm  view on Meta::CPAN


Implementations: L<AnyEvent::Impl::EV>, L<AnyEvent::Impl::Event>,
L<AnyEvent::Impl::Glib>, L<AnyEvent::Impl::Tk>, L<AnyEvent::Impl::Perl>,
L<AnyEvent::Impl::EventLib>, L<AnyEvent::Impl::Qt>,
L<AnyEvent::Impl::POE>, L<AnyEvent::Impl::IOAsync>, L<AnyEvent::Impl::Irssi>,
L<AnyEvent::Impl::FLTK>, L<AnyEvent::Impl::Cocoa>, L<AnyEvent::Impl::UV>.

Non-blocking handles, pipes, stream sockets, TCP clients and
servers: L<AnyEvent::Handle>, L<AnyEvent::Socket>, L<AnyEvent::TLS>.

Asynchronous File I/O: L<AnyEvent::IO>.

Asynchronous DNS: L<AnyEvent::DNS>.

Thread support: L<Coro>, L<Coro::AnyEvent>, L<Coro::EV>, L<Coro::Event>.

Nontrivial usage examples: L<AnyEvent::GPSD>, L<AnyEvent::IRC>,
L<AnyEvent::HTTP>.


=head1 AUTHOR

   Marc Lehmann <schmorp@schmorp.de>

lib/AnyEvent/DNS.pm  view on Meta::CPAN

=head1 NAME

AnyEvent::DNS - fully asynchronous DNS resolution

=head1 SYNOPSIS

   use AnyEvent::DNS;
   
   my $cv = AnyEvent->condvar;
   AnyEvent::DNS::a "www.google.de", $cv;
   # ... later
   my @addrs = $cv->recv;

=head1 DESCRIPTION

This module offers both a number of DNS convenience functions as well
as a fully asynchronous and high-performance pure-perl stub resolver.

The stub resolver supports DNS over IPv4 and IPv6, UDP and TCP, optional
EDNS0 support for up to 4kiB datagrams and automatically falls back to
virtual circuit mode for large responses.

=head2 CONVENIENCE FUNCTIONS

=over 4

=cut

lib/AnyEvent/DNS.pm  view on Meta::CPAN

   }

   $got_socket
      or Carp::croak "unable to create either an IPv4 or an IPv6 socket";

   $self->_compile;

   $self
}

# called to start asynchronous configuration
sub _config_begin {
   ++$_[0]{inhibit};
}

# called when done with async config
sub _config_done {
   --$_[0]{inhibit};
   $_[0]->_compile;
   $_[0]->_scheduler;
}

lib/AnyEvent/Handle.pm  view on Meta::CPAN

      and Net::SSLeay::state ($self->{tls}) == Net::SSLeay::ST_OK ()
      and (delete $self->{_on_starttls})->($self, 1, "TLS/SSL connection established");
}

=item $handle->starttls ($tls[, $tls_ctx])

Instead of starting TLS negotiation immediately when the AnyEvent::Handle
object is created, you can also do that at a later time by calling
C<starttls>. See the C<tls> constructor argument for general info.

Starting TLS is currently an asynchronous operation - when you push some
write data and then call C<< ->starttls >> then TLS negotiation will start
immediately, after which the queued write data is then sent. This might
change in future versions, so best make sure you have no outstanding write
data when calling this method.

The first argument is the same as the C<tls> constructor argument (either
C<"connect">, C<"accept"> or an existing Net::SSLeay object).

The second argument is the optional C<AnyEvent::TLS> object that is used
when AnyEvent::Handle has to create its own TLS connection object, or

lib/AnyEvent/IO.pm  view on Meta::CPAN

=head1 NAME

AnyEvent::IO - the DBI of asynchronous I/O implementations

=head1 SYNOPSIS

   use AnyEvent::IO;

   # load /etc/passwd, call callback with the file data when done.
   aio_load "/etc/passwd", sub {
      my ($data) = @_
         or return AE::log error => "/etc/passwd: $!";

lib/AnyEvent/IO.pm  view on Meta::CPAN

            $filedata->($data);
         };
      };
   };

   my $passwd = $filedata->recv;
   warn length $passwd, " octets.\n";

=head1 DESCRIPTION

This module provides functions that do I/O in an asynchronous fashion. It
is to I/O the same as L<AnyEvent> is to event libraries - it only
I<interfaces> to other implementations or to a portable pure-perl
implementation (which does not, however, do asynchronous I/O).

The only other implementation that is supported (or even known to the
author) is L<IO::AIO>, which is used automatically when it can be loaded
(via L<AnyEvent::AIO>, which also needs to be installed). If it is not
available, then L<AnyEvent::IO> falls back to its synchronous pure-perl
implementation.

Unlike L<AnyEvent>, which model to use is currently decided at module load
time, not at first use. Future releases might change this.

=head2 RATIONALE

While disk I/O often seems "instant" compared to, say, socket I/O, there
are many situations where your program can block for extended time periods
when doing disk I/O. For example, you access a disk on an NFS server and
it is gone - can take ages to respond again, if ever. Or your system is
extremely busy because it creates or restores a backup - reading data from
disk can then take seconds. Or you use Linux, which for so many years has
a close-to-broken VM/IO subsystem that can often induce minutes or more of
delay for disk I/O, even under what I would consider light I/O loads.

Whatever the situation, some programs just can't afford to block for long
times (say, half a second or more), because they need to respond as fast
as possible.

For those cases, you need asynchronous I/O.

The problem is, AnyEvent itself sometimes reads disk files (for example,
when looking at F</etc/hosts>), and under the above situations, this can
bring your program to a complete halt even if your program otherwise
takes care to only use asynchronous I/O for everything (e.g. by using
L<IO::AIO>).

On the other hand, requiring L<IO::AIO> for AnyEvent is clearly
impossible, as AnyEvent promises to stay pure-perl, and the overhead of
IO::AIO for small programs would be immense, especially when asynchronous
I/O isn't even needed.

Clearly, this calls for an abstraction layer, and that is what you are
looking at right now :-)

=head2 ASYNCHRONOUS VS. NON-BLOCKING

Many people are continuously confused on what the difference is between
asynchronous I/O and non-blocking I/O. In fact, those two terms are
not well defined, which often makes it hard to even talk about the
difference. Here is a short guideline that should leave you less
confused. It only talks about read operations, but the reasoning works
with other I/O operations as well.

Non-blocking I/O means that data is delivered by some external means,
automatically - that is, something I<pushes> data towards your file
handle, without you having to do anything. Non-blocking means that if
your operating system currently has no data (or EOF, or some error)
available for you, it will not wait ("block") as it would normally do,

lib/AnyEvent/IO.pm  view on Meta::CPAN

"on their own", and more so, the OS already knows that data is there, it
doesn't need to "wait" until it arrives from some external entity, it only
needs to transfer the data from disk to your memory buffer.

So basically, while the concept is sound, the existing OS APIs do not
support this. Therefore, it makes no sense to switch a disk file handle
into non-blocking mode - it will behave exactly the same as in blocking
mode, namely it will block until the data has been read from the disk.

The alternative to non-blocking I/O that actually works with disk files
is usually called I<asynchronous I/O>. Asynchronous, because the actual
I/O is done while your program does something else: there is no need to
call the read function to see if data is there, you only order the read
once, and it will notify you when the read has finished and the data is
your buffer - all the work is done in the background.

This works with disk files, and even with sockets and other sources. It
is, however, not very efficient when used with sources that could be
driven in a non-blocking way, because it usually has higher overhead
in the OS than non-blocking I/O, because it ties memory buffers for a
potentially unlimited time and often only a limited number of operations
can be done in parallel.

That's why asynchronous I/O makes most sense when confronted with disk
files, and non-blocking I/O only makes sense with sockets, pipes and
similar streaming sources.

=head1 IMPORT TAGS

By default, this module exports all C<aio_>xxx functions. In addition,
the following import tags can be used:

   :aio       all aio_* functions, same as :DEFAULT
   :flags     the fcntl open flags (O_CREAT, O_RDONLY, ...)

=head1 API NOTES

The functions in this module are not meant to be the most versatile or
the highest-performers (they are not very slow either, of course). They
are primarily meant to give users of your code the option to do the I/O
asynchronously (by installing L<IO::AIO> and L<AnyEvent::AIO>),
without adding a dependency on those modules.

=head2 NAMING

All the functions in this module implement an I/O operation, usually with
the same or similar name as the Perl built-in that they mimic, but with
an C<aio_> prefix. If you like you can think of the C<aio_>xxx functions as
"AnyEvent I/O" or "Asynchronous I/O" variants of Perl built-ins.

=head2 CALLING CONVENTIONS AND ERROR REPORTING

Each function expects a callback as their last argument. The callback is
usually called with the result data or result code. An error is usually
signalled by passing no arguments to the callback, which is then free to
look at C<$!> for the error code.

This makes all of the following forms of error checking valid:

lib/AnyEvent/IO.pm  view on Meta::CPAN

      aio_stat "path2", sub {
         warn "both stats done\n";
      };
   };

Starts a C<stat> operation and then exits by "falling off the end" of
the program. Nevertheless, I<both> C<stat> operations will be executed,
as AnyEvent::IO waits for all outstanding requests to finish and you can
start new requests from request callbacks.

In fact, since L<AnyEvent::IO::Perl> is currently synchronous, the
program will do both stats before falling off the end, but with
L<AnyEvent::IO::IOAIO>, the program first falls of the end, then the stats
are executed.

While not guaranteed, this behaviour will be present in future versions,
if reasonably possible (which is extreemly likely :).

=cut

package AnyEvent::IO;

lib/AnyEvent/IO/IOAIO.pm  view on Meta::CPAN

AnyEvent::IO::IOAIO - AnyEvent::IO backend based on IO::AIO

=head1 SYNOPSIS

   use AnyEvent::IO;

=head1 DESCRIPTION

This is the L<IO::AIO>-based backend of L<AnyEvent::IO> (via
L<AnyEvent::AIO>). All I/O operations it implements are done
asynchronously.

=head1 FUNCTIONS

=over 4

=cut

package AnyEvent::IO::IOAIO;

use AnyEvent (); BEGIN { AnyEvent::common_sense }

lib/AnyEvent/IO/Perl.pm  view on Meta::CPAN


AnyEvent::IO::Perl - pure perl backend for AnyEvent::IO

=head1 SYNOPSIS

   use AnyEvent::IO;

=head1 DESCRIPTION

This is the pure-perl backend of L<AnyEvent::IO> - it is always available,
but does not actually implement any I/O operation asynchronously -
everything is synchronous.

For simple programs that can wait for I/O, this is likely the most
efficient implementation.

=cut

package AnyEvent::IO::Perl;

use AnyEvent (); BEGIN { AnyEvent::common_sense }
our $VERSION = $AnyEvent::VERSION;

lib/AnyEvent/Impl/IOAsync.pm  view on Meta::CPAN


Apart from these fatal flaws, there are a number of unpleasent properties
that just need some mentioning:

=over 4

=item Confusing and misleading names

Another rather negative point about this module family is its name,
which is deeply confusing: Despite the "async" in the name, L<IO::Async>
only does I<synchronous> I/O, there is nothing "asynchronous" about it
whatsoever (when I first heard about it, I thought, "wow, a second async
I/O module, what does it do compared to L<IO::AIO>", and was somehow set
back when I learned that the only "async" aspect of it is the name).

=item Inconsistent, incomplete and convoluted API

Implementing AnyEvent's rather simple timers on top of IO::Async's timers
was a nightmare (try implementing a timer with configurable interval and
delay value...).

lib/AnyEvent/Intro.pod  view on Meta::CPAN


While the core L<AnyEvent> module is still small and self-contained,
the distribution comes with some very useful utility modules such as
L<AnyEvent::Handle>, L<AnyEvent::DNS> and L<AnyEvent::Socket>. These can
make your life as a non-blocking network programmer a lot easier.

Here is a quick overview of these three modules:

=head2 L<AnyEvent::DNS>

This module allows fully asynchronous DNS resolution. It is used mainly by
L<AnyEvent::Socket> to resolve hostnames and service ports for you, but is
a great way to do other DNS resolution tasks, such as reverse lookups of
IP addresses for log files.

=head2 L<AnyEvent::Handle>

This module handles non-blocking IO on (socket-, pipe- etc.) file handles
in an event based manner. It provides a wrapper object around your file
handle that provides queueing and buffering of incoming and outgoing data
for you.

lib/AnyEvent/Intro.pod  view on Meta::CPAN

instead of returning a condition variable you could also pass a third
parameter to your finger function, the callback to invoke with the
response:

   sub finger($$$) {
      my ($user, $host, $cb) = @_;

How you implement it is a matter of taste - if you expect your function to
be used mainly in an event-based program you would normally prefer to pass
a callback directly. If you write a module and expect your users to use
it "synchronously" often (for example, a simple http-get script would not
really care much for events), then you would use a condition variable and
tell them "simply C<< ->recv >> the data".

=head3 Problems with the implementation and how to fix them

To make this example more real-world-ready, we would not only implement
some write buffering (for the paranoid, or maybe denial-of-service aware
security expert), but we would also have to handle timeouts and maybe
protocol errors.

lib/AnyEvent/Util.pm  view on Meta::CPAN

         socketpair my $fh1, my $fh2, Socket::AF_UNIX(), Socket::SOCK_STREAM(), 0
            or return;

         ($fh1, $fh2)
      };
   }
}

=item fork_call { CODE } @args, $cb->(@res)

Executes the given code block asynchronously, by forking. Everything the
block returns will be transferred to the calling process (by serialising and
deserialising via L<Storable>).

If there are any errors, then the C<$cb> will be called without any
arguments. In that case, either C<$@> contains the exception (and C<$!> is
irrelevant), or C<$!> contains an error number. In all other cases, C<$@>
will be C<undef>ined.

The code block must not ever call an event-polling function or use
event-based programming that might cause any callbacks registered in the



( run in 0.814 second using v1.01-cache-2.11-cpan-0d8aa00de5b )