AnyEvent

 view release on metacpan or  search on metacpan

lib/AnyEvent.pm  view on Meta::CPAN

   });

   # called when event loop idle (if applicable)
   my $w = AnyEvent->idle (cb => sub { ... });

   my $w = AnyEvent->condvar; # stores whether a condition was flagged
   $w->send; # wake up current and all future recv's
   $w->recv; # enters "main loop" till $condvar gets ->send
   # use a condvar in callback mode:
   $w->cb (sub { $_[0]->recv });

=head1 INTRODUCTION/TUTORIAL

This manpage is mainly a reference manual. If you are interested
in a tutorial or some gentle introduction, have a look at the
L<AnyEvent::Intro> manpage.

=head1 SUPPORT

An FAQ document is available as L<AnyEvent::FAQ>.

There also is a mailinglist for discussing all things AnyEvent, and an IRC
channel, too.

See the AnyEvent project page at the B<Schmorpforge Ta-Sa Software
Repository>, at L<http://anyevent.schmorp.de>, for more info.

=head1 WHY YOU SHOULD USE THIS MODULE (OR NOT)

Glib, POE, IO::Async, Event... CPAN offers event models by the dozen
nowadays. So what is different about AnyEvent?

Executive Summary: AnyEvent is I<compatible>, AnyEvent is I<free of
policy> and AnyEvent is I<small and efficient>.

First and foremost, I<AnyEvent is not an event model> itself, it only
interfaces to whatever event model the main program happens to use, in a
pragmatic way. For event models and certain classes of immortals alike,
the statement "there can only be one" is a bitter reality: In general,
only one event loop can be active at the same time in a process. 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 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
supports (including stuff like IO::Async, as long as those use one of the
supported event loops. It is easy to add new event loops to AnyEvent, too,
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

L<AnyEvent> provides a uniform interface to various event loops. This
allows module authors to use event loop functionality without forcing
module users to use a specific event loop implementation (since more
than one event loop cannot coexist peacefully).

The interface itself is vaguely similar, but not identical to the L<Event>
module.

During the first call of any watcher-creation method, the module tries
to detect the currently loaded event loop by probing whether one of the
following modules is already loaded: L<EV>, L<AnyEvent::Loop>,
L<Event>, L<Glib>, L<Tk>, L<Event::Lib>, L<Qt>, L<POE>. The first one
found is used. If none are detected, the module tries to load the first
four modules in the order given; but note that if L<EV> is not
available, the pure-perl L<AnyEvent::Loop> should always work, so
the other two are not normally tried.

Because AnyEvent first checks for modules that are already loaded, loading
an event model explicitly before first using AnyEvent will likely make
that model the default. For example:

   use Tk;
   use AnyEvent;

   # .. AnyEvent will likely default to Tk

The I<likely> means that, if any module loads another event model and
starts using it, all bets are off - this case should be very rare though,
as very few modules hardcode event loops without announcing this very
loudly.

The pure-perl implementation of AnyEvent is called C<AnyEvent::Loop>. Like
other event modules you can load it explicitly and enjoy the high
availability of that event loop :)

=head1 WATCHERS

lib/AnyEvent.pm  view on Meta::CPAN

detected. This requirement can be dropped by relying on L<Coro::AnyEvent>
, which allows you to do a blocking C<< ->recv >> from any thread
that doesn't run the event loop itself. L<Coro::AnyEvent> is loaded
automatically when L<Coro> is used with L<AnyEvent>, so code does not need
to do anything special to take advantage of that: any code that would
normally block your program because it calls C<recv>, be executed in an
C<async> thread instead without blocking other threads.

Not all event models support a blocking wait - some die in that case
(programs might want to do that to stay interactive), so I<if you are
using this from a module, never require a blocking wait>. Instead, let the
caller decide whether the call will block or not (for example, by coupling
condition variables with some kind of request results and supporting
callbacks so the caller knows that getting the result will not block,
while still supporting blocking waits if the caller so desires).

You can ensure that C<< ->recv >> never blocks by setting a callback and
only calling C<< ->recv >> from within that callback (or at a later
time). This will work even when the event loop does not support blocking
waits otherwise.

=item $bool = $cv->ready

Returns true when the condition is "true", i.e. whether C<send> or
C<croak> have been called.

=item $cb = $cv->cb ($cb->($cv))

This is a mutator function that returns the callback set (or C<undef> if
not) and optionally replaces it before doing so.

The callback will be called when the condition becomes "true", i.e. when
C<send> or C<croak> are called, with the only argument being the
condition variable itself. If the condition is already true, the
callback is called immediately when it is set. Calling C<recv> inside
the callback or at any later time is guaranteed not to block.

Additionally, when the callback is invoked, it is also removed from the
condvar (reset to C<undef>), so the condvar does not keep a reference to
the callback after invocation.

=back

=head1 SUPPORTED EVENT LOOPS/BACKENDS

The following backend classes are part of the AnyEvent distribution (every
class has its own manpage):

=over 4

=item Backends that are autoprobed when no other event loop can be found.

EV is the preferred backend when no other event loop seems to be in
use. If EV is not installed, then AnyEvent will fall back to its own
pure-perl implementation, which is available everywhere as it comes with
AnyEvent itself.

   AnyEvent::Impl::EV        based on EV (interface to libev, best choice).
   AnyEvent::Impl::Perl      pure-perl AnyEvent::Loop, fast and portable.

=item Backends that are transparently being picked up when they are used.

These will be used if they are already loaded when the first watcher
is created, in which case it is assumed that the application is using
them. This means that AnyEvent will automatically pick the right backend
when the main program loads an event module before anything starts to
create watchers. Nothing special needs to be done by the main program.

   AnyEvent::Impl::Event     based on Event, very stable, few glitches.
   AnyEvent::Impl::Glib      based on Glib, slow but very stable.
   AnyEvent::Impl::Tk        based on Tk, very broken.
   AnyEvent::Impl::UV        based on UV, innovated square wheels.
   AnyEvent::Impl::EventLib  based on Event::Lib, leaks memory and worse.
   AnyEvent::Impl::POE       based on POE, very slow, some limitations.
   AnyEvent::Impl::Irssi     used when running within irssi.
   AnyEvent::Impl::IOAsync   based on IO::Async.
   AnyEvent::Impl::Cocoa     based on Cocoa::EventLoop.
   AnyEvent::Impl::FLTK      based on FLTK (fltk 2 binding).

=item Backends with special needs.

Qt requires the Qt::Application to be instantiated first, but will
otherwise be picked up automatically. As long as the main program
instantiates the application before any AnyEvent watchers are created,
everything should just work.

   AnyEvent::Impl::Qt        based on Qt.

=item Event loops that are indirectly supported via other backends.

Some event loops can be supported via other modules:

There is no direct support for WxWidgets (L<Wx>) or L<Prima>.

B<WxWidgets> has no support for watching file handles. However, you can
use WxWidgets through the POE adaptor, as POE has a Wx backend that simply
polls 20 times per second, which was considered to be too horrible to even
consider for AnyEvent.

B<Prima> is not supported as nobody seems to be using it, but it has a POE
backend, so it can be supported through POE.

AnyEvent knows about both L<Prima> and L<Wx>, however, and will try to
load L<POE> when detecting them, in the hope that POE will pick them up,
in which case everything will be automatic.

=item Known event loops outside the AnyEvent distribution

The following event loops or programs support AnyEvent by providing their
own AnyEvent backend. They will be picked up automatically.

   urxvt::anyevent           available to rxvt-unicode extensions

=back

=head1 GLOBAL VARIABLES AND FUNCTIONS

These are not normally required to use AnyEvent, but can be useful to
write AnyEvent extension modules.

=over 4

lib/AnyEvent.pm  view on Meta::CPAN

when it depends on a module that uses an AnyEvent. If the program itself
uses AnyEvent, but does not care which event loop is used, all it needs
to do is C<use AnyEvent>. In either case, AnyEvent will choose the best
available loop implementation.

If the main program relies on a specific event model - for example, in
Gtk2 programs you have to rely on the Glib module - you should load the
event module before loading AnyEvent or any module that uses it: generally
speaking, you should load it as early as possible. The reason is that
modules might create watchers when they are loaded, and AnyEvent will
decide on the event model to use as soon as it creates watchers, and it
might choose the wrong one unless you load the correct one yourself.

You can chose to use a pure-perl implementation by loading the
C<AnyEvent::Loop> module, which gives you similar behaviour
everywhere, but letting AnyEvent chose the model is generally better.

=head2 MAINLOOP EMULATION

Sometimes (often for short test scripts, or even standalone programs who
only want to use AnyEvent), you do not want to run a specific event loop.

In that case, you can use a condition variable like this:

   AnyEvent->condvar->recv;

This has the effect of entering the event loop and looping forever.

Note that usually your program has some exit condition, in which case
it is better to use the "traditional" approach of storing a condition
variable somewhere, waiting for it, and sending it when the program should
exit cleanly.


=head1 OTHER MODULES

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 as part of AnyEvent, the others are available via CPAN (see
L<http://search.cpan.org/search?m=module&q=anyevent%3A%3A*> for
a longer non-exhaustive list), and the list is heavily biased towards
modules of the AnyEvent author himself :)

=over 4

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

Contains various utility functions that replace often-used blocking
functions such as C<inet_aton> with event/callback-based versions.

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

Provides various utility functions for (internet protocol) sockets,
addresses and name resolution. Also functions to create non-blocking tcp
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.

And they are quite tiny and fast as well - "abusing" L<AnyEvent::Fork>
just to exec external programs can easily beat using C<fork> and C<exec>
(or even C<system>) in most programs.

=item L<AnyEvent::Filesys::Notify>

AnyEvent is good for non-blocking stuff, but it can't detect file or
path changes (e.g. "watch this directory for new files", "watch this
file for changes"). The L<AnyEvent::Filesys::Notify> module promises to
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:

   async {
      Coro::AnyEvent::sleep 5; # creates a 5s timer and waits for it
      print "5 seconds later!\n";

      Coro::AnyEvent::readable *STDIN; # uses an I/O watcher
      my $line = <STDIN>; # works for ttys

      AnyEvent::HTTP::http_get "url", Coro::rouse_cb;
      my ($body, $hdr) = Coro::rouse_wait;
   };

=back

=cut

package AnyEvent;

BEGIN {
   require "AnyEvent/constants.pl";
   &AnyEvent::common_sense;
}

use Carp ();

our $VERSION = 7.17;
our $MODEL;
our @ISA;
our @REGISTRY;
our $VERBOSE;
our %PROTOCOL; # (ipv4|ipv6) => (1|2), higher numbers are preferred
our $MAX_SIGNAL_LATENCY = $ENV{PERL_ANYEVENT_MAX_SIGNAL_LATENCY} || 10; # executes after the BEGIN block below (tainting!)

BEGIN {
   eval "sub TAINT (){" . (${^TAINT}*1) . "}";

   delete @ENV{grep /^PERL_ANYEVENT_/, keys %ENV}
      if ${^TAINT};

   $ENV{"PERL_ANYEVENT_$_"} = $ENV{"AE_$_"}
      for grep s/^AE_// && !exists $ENV{"PERL_ANYEVENT_$_"}, keys %ENV;

lib/AnyEvent.pm  view on Meta::CPAN

           or AnyEvent::log fatal => "Backend autodetection failed - did you properly install AnyEvent?";
      }
   }

   # free memory only needed for probing
   undef @models;
   undef @REGISTRY;

   push @{"$MODEL\::ISA"}, "AnyEvent::Base";

   # now nuke some methods that are overridden by the backend.
   # SUPER usage is not allowed in these.
   for (qw(time signal child idle)) {
      undef &{"AnyEvent::Base::$_"}
         if defined &{"$MODEL\::$_"};
   }

   _isa_set;

   # we're officially open!

   if ($ENV{PERL_ANYEVENT_STRICT}) {
      require AnyEvent::Strict;
   }

   if ($ENV{PERL_ANYEVENT_DEBUG_WRAP}) {
      require AnyEvent::Debug;
      AnyEvent::Debug::wrap ($ENV{PERL_ANYEVENT_DEBUG_WRAP});
   }

   if (length $ENV{PERL_ANYEVENT_DEBUG_SHELL}) {
      require AnyEvent::Socket;
      require AnyEvent::Debug;

      my $shell = $ENV{PERL_ANYEVENT_DEBUG_SHELL};
      $shell =~ s/\$\$/$$/g;

      my ($host, $service) = AnyEvent::Socket::parse_hostport ($shell);
      $AnyEvent::Debug::SHELL = AnyEvent::Debug::shell ($host, $service);
   }

   # now the anyevent environment is set up as the user told us to, so
   # call the actual user code - post detects

   (shift @post_detect)->() while @post_detect;
   undef @post_detect;

   *post_detect = sub(&) {
      shift->();

      undef
   };

   $MODEL
}

for my $name (@methods) {
   *$name = sub {
      detect;
      # we use goto because
      # a) it makes the thunk more transparent
      # b) it allows us to delete the thunk later
      goto &{ UNIVERSAL::can AnyEvent => "SUPER::$name" }
   };
}

# utility function to dup a filehandle. this is used by many backends
# to support binding more than one watcher per filehandle (they usually
# allow only one watcher per fd, so we dup it to get a different one).
sub _dupfh($$;$$) {
   my ($poll, $fh, $r, $w) = @_;

   # cygwin requires the fh mode to be matching, unix doesn't
   my ($rw, $mode) = $poll eq "r" ? ($r, "<&") : ($w, ">&");

   open my $fh2, $mode, $fh
      or die "AnyEvent->io: cannot dup() filehandle in mode '$poll': $!,";

   # we assume CLOEXEC is already set by perl in all important cases

   ($fh2, $rw)
}

=head1 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 by using function call syntax and a fixed number of parameters.

See the L<AE> manpage for details.

=cut

package AE;

our $VERSION = $AnyEvent::VERSION;

sub _reset() {
   eval q{
      # fall back to the main API by default - backends and AnyEvent::Base
      # implementations can overwrite these.

      sub io($$$) {
         AnyEvent->io (fh => $_[0], poll => $_[1] ? "w" : "r", cb => $_[2])
      }

      sub timer($$$) {
         AnyEvent->timer (after => $_[0], interval => $_[1], cb => $_[2])
      }

      sub signal($$) {
         AnyEvent->signal (signal => $_[0], cb => $_[1])
      }

      sub child($$) {
         AnyEvent->child (pid => $_[0], cb => $_[1])
      }

      sub idle($) {
         AnyEvent->idle (cb => $_[0]);
      }



( run in 0.914 second using v1.01-cache-2.11-cpan-39bf76dae61 )