AnyEvent

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

          how that module sucks.
        - add google public ipv6 dns as fallback servers, so AE::DNS can finally
          support ipv6-only operation even with defaults (also use ::1 instead
          of 127.0.0.1).
	- give better guidelines on how to chose a logging level.
        - AnyEvent::Log can now cap (limit) log message priority by context.
        - AE::log will now save and restore $! and $@, so callers don't have to.
        - AE::Strict now checks that registered fds are still valid at regular
          intervals.
        - skip frequently called 'require' calls if the module appears loaded.
	- increase signal latency test timer considerably for poor little osx,
          which can't be bothered with basic posix functionality such as signal
          delivery.
        - mention some debugging aids in the tutorial.
        - new env variable PERL_ANYEVENT_MAX_SIGNAL_LATENCY.
        - private (%namespace) log contexts in PERL_ANYEVENT_LOG now have the name
          of the context as title.
        - AnyEvent::Strict would not restore read-write access to $_ when a callback
          died - this is a user bug, but since AE::Strict exists to help dbeugging...
	- detect the extremely evil IO::Async::Loop::AnyEvent module and refuse
          to work with it - the author is well aware of the issues but refuses

Changes  view on Meta::CPAN

          watcher instrumentation/wrapping (see AnyEvent::Debug::wrap).
        - new env variable, PERL_ANYEVENT_HOSTS, to override the place where
          /etc/hosts can be found.
        - an empty PERL_ANYEVENT_RESOLV_CONF now selects the default
          configuration.
        - env variables can now be specified using AE_xyz instead of
          PERL_ANYEVENT_xyz, subject to some rules.
        - lots of new AnyEvent::Debug functionality.
        - AnyEvent::Strict now checks for modifications of $_ by the callback
          (by setting it to readonly while executing the callback, if possible).
        - IO::Async sometimes cancels the wrong timer when you call cancel_timer.
          Invest extra overhead to work around this peculiar behaviour.
        - split the pure perl backend into a loop module and an impl
          module (AnyEvent::Loop and AnyEvent::Impl::Perl).
        - some read types (regex, netstring, json, storable) could
          errornously keep an AE::Handle object alive on their own
          (reported by Mohammad Toossi).
        - AnyEvent::Socket::resolve_sockaddr and all functions using it now
          supports /etc/hosts overrides.
        - add more workarounds around child watcher bugs in IO::Async
          and (newly introduced) in POE.

Changes  view on Meta::CPAN

	- speed up AnyEvent::Socket::format_address and ::format_ipv6.
        - the AnyEvent::Util::fh_nonblocking function worked only
          by lucky accident on win32.
        - smaller and faster AnyEvent::Util::fh_nonblocking.
        - when the (required!) Time::HiRes module is missing, AnyEvent
          did not fall back to built-in time properly.
        - do not load Fcntl at runtime, saving memory and loading time.
        - precompile a number of constants and use them instead of runtime
          detection and eval.
        - free detection code after detection and similar memory optimisations.
        - Perl backend timer interval best effort drift has been improved
          (same algorithm as EV).
        - update unicode idna mapping table.

5.24  Tue Jan  5 11:39:43 CET 2010
	- cygwin never reports errors from failed connects. 1.5 just gives
          you continous readyness and EAGAIN, 1.7 is even more broken and
          just hangs. work around both issues in a cygwin-specific hack.
	- improve idle watcher documentation slightly.

5.23  Sun Dec 20 23:48:00 CET 2009

Changes  view on Meta::CPAN

          segfault in Net::SSLeay.
        - AnyEvent::Handle can now call tcp_connect itself (new parameters
          connect, on_prepare, on_connect and on_connect_error). Updated
          tutorial accordingly.
	- add AnyEvent::Impl::Irssi backend.

4.86 Mon Jul 20 23:52:29 CEST 2009
	- since the verbose warning is not enough, explicitly document
          that versions before 1.33 of Net::SSLeay are not secure.
	- work around signal handling races in Event and (...) Event::Lib.
        - try to align signal-race timer to full-second boundaries.
        - work around Tk not liking negative timeouts.
        - don't complain of different grades of environmental unfriendlyness
          in IO::Async.

4.85 Sat Jul 18 06:16:14 CEST 2009
        - nail the signal race problem in perl once and for all
          (see $AnyEvent::MAX_SIGNAL_LATENCY).
        - take advantage of Async::Interrupt if it is available.
        - load Time::HiRes and Guard modules on demand only.
        - add optional/recommended modules section to AnyEvent

Changes  view on Meta::CPAN

        - 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
          to avoid spamming out warning messages.
        - fix Qt timers without interval.
        - avoid Qt zero-timeout special case, in old libqt's.

4.352 Mon Apr 20 16:31:11 CEST 2009
	- fix AnyEvent::Strict error messages for child watchers.
        - fix/update Makefile.PL "recommends" versions.
        - 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

Changes  view on Meta::CPAN

	- INCOMPATIBLE CHANGE: AnyEvent::Util::fork_call now has a prototype
          which is incompatible to previous invocation syntax.
        - work around more windows perl bugs in fork_call. I cannot imagine
          why anybody would bother implementing fork in such an obviously
          unusable way.
	- avoid calling $do_retry if the request has already finished in
          AnyEvent::DNS, thus avoiding an exception (reported by Anatoly
          K. Sharifulin).

4.2  Sat Jul 12 22:42:11 CEST 2008
	- support an "interval" argument for repeating timers.
        - fix a bug in the pure perl event loop that caused timers to
          be delayed under some circumstances.
        - implement optional argument checking via PERL_ANYEVENT_STRICT.
	- not importing anything from Event causes it to malfunction
          and not use Time::HiRes, work around this bug.
        - more bug workarounds against the endlessly broken Tk module,
          seems to work now on 32 bit machines, but less so on 64 bit.
        - minor optimisations applied to most backends.

4.161 Fri Jul  4 14:24:48 CEST 2008
        - fixed the t/handle/02_write.t, it read after write, with the

Changes  view on Meta::CPAN

        - EXPERIMENTAL:
          new pure-perl model added, AnyEvent now always finds a suitable
          event model.
        - improved documentation.
        - reduced cpu overhead.

1.02 Fri Jan 13 14:15:40 CET 2006
	- add COPYING to clarify license.

1.01 Sun Jan  8 05:48:09 CET 2006
	- correctly cancel Event timers, avoid memory leaks.

1.0  Sun Jan  8 05:40:58 CET 2006
	- allow third-party interfaces to be added at runtime.
        - fix version number.

0.9  Fri Dec 30 02:25:41 CET 2005
	- fixed errors in the documentation.
        - going back to using $VERSION as "load check",
          as suggested by Jörn Reder. Let's see why I stopped using
          this method.

README  view on Meta::CPAN


SYNOPSIS
       use AnyEvent;

       # 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
       my $w = AnyEvent->timer (after => $seconds, cb => sub { ...  });
       my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ...);

       print AnyEvent->now;  # prints current event loop time
       print AnyEvent->time; # think Time::HiRes::time or simply CORE::time.

       # POSIX signal
       my $w = AnyEvent->signal (signal => "TERM", cb => sub { ... });

       # child process exit
       my $w = AnyEvent->child (pid => $pid, cb => sub {
          my ($pid, $status) = @_;

README  view on Meta::CPAN


    First and foremost, *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 *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.

README  view on Meta::CPAN

    callbacks must not "die". The former is good programming practice in
    Perl and the latter stems from the fact that exception handling differs
    widely between event loops.

    To disable a watcher you have to destroy it (e.g. by setting the
    variable you store it in to "undef" or otherwise deleting all references
    to it).

    All watchers are created by calling a method on the "AnyEvent" class.

    Many watchers either are used with "recursion" (repeating timers for
    example), or need to refer to their watcher object in other ways.

    One way to achieve that is this pattern:

       my $w; $w = AnyEvent->type (arg => value ..., cb => sub {
          # you can use $w here, for example to undef it
          undef $w;
       });

    Note that "my $w; $w =" combination. This is necessary because in Perl,

README  view on Meta::CPAN

    Example: wait for readability of STDIN, then read a line and disable the
    watcher.

       my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
          chomp (my $input = <STDIN>);
          warn "read: $input\n";
          undef $w;
       });

  TIME WATCHERS
       $w = AnyEvent->timer (after => <seconds>, cb => <callback>);

       $w = AnyEvent->timer (
          after    => <fractional_seconds>,
          interval => <fractional_seconds>,
          cb       => <callback>,
       );

    You can create a time watcher by calling the "AnyEvent->timer" method
    with the following mandatory arguments:

    "after" specifies after how many seconds (fractional values are
    supported) the callback should be invoked. "cb" is the callback to
    invoke in that case.

    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 time watcher callbacks.

    The callback will normally be invoked only once. If you specify another
    parameter, "interval", as a strictly positive number (> 0), then the
    callback will be invoked regularly at that interval (in fractional
    seconds) after the first invocation. If "interval" is specified with a
    false value, then it is treated as if it were not specified at all.

    The callback will be rescheduled before invoking the callback, but no
    attempt is made to avoid timer drift in most backends, so the interval
    is only approximate.

    Example: fire an event after 7.7 seconds.

       my $w = AnyEvent->timer (after => 7.7, cb => sub {
          warn "timeout\n";
       });

       # to cancel the timer:
       undef $w;

    Example 2: fire an event after 0.5 seconds, then roughly every second.

       my $w = AnyEvent->timer (after => 0.5, interval => 1, cb => sub {
          warn "timeout\n";
       });

   TIMING ISSUES
    There are two ways to handle timers: based on real time (relative, "fire
    in 10 seconds") and based on wallclock time (absolute, "fire at 12
    o'clock").

    While most event loops expect timers to specified in a relative way,
    they use absolute time internally. This makes a difference when your
    clock "jumps", for example, when ntp decides to set your clock backwards
    from the wrong date of 2014-01-01 to 2008-01-01, a watcher that is
    supposed to fire "after a second" might actually take six years to
    finally fire.

    AnyEvent cannot compensate for this. The only event loop that is
    conscious of these issues is EV, which offers both relative (ev_timer,
    based on true relative time) and absolute (ev_periodic, based on
    wallclock time) timers.

    AnyEvent always prefers relative timers, if available, matching the
    AnyEvent API.

    AnyEvent has two additional methods that return the "current time":

    AnyEvent->time
        This returns the "current wallclock time" as a fractional number of
        seconds since the Epoch (the same thing as "time" or
        "Time::HiRes::time" return, and the result is guaranteed to be
        compatible with those).

        It progresses independently of any event loop processing, i.e. each
        call will check the system clock, which usually gets updated
        frequently.

    AnyEvent->now
        This also returns the "current wallclock time", but unlike "time",
        above, this value might change only once per event loop iteration,
        depending on the event loop (most return the same time as "time",
        above). This is the time that AnyEvent's timers get scheduled
        against.

        *In almost all cases (in all cases if you don't care), this is the
        function to call when you want to know the current time.*

        This function is also often faster then "AnyEvent->time", and thus
        the preferred method if you want some timestamp (for example,
        AnyEvent::Handle uses this to update its activity timeouts).

        The rest of this section is only of relevance if you try to be very
        exact with your timing; you can skip it without a bad conscience.

        For a practical example of when these times differ, consider
        Event::Lib and EV and the following set-up:

        The event loop is running and has just invoked one of your callbacks
        at time=500 (assume no other callbacks delay processing). In your
        callback, you wait a second by executing "sleep 1" (blocking the
        process for a second) and then (at time=501) you create a relative
        timer that fires after three seconds.

        With Event::Lib, "AnyEvent->time" and "AnyEvent->now" will both
        return 501, because that is the current time, and the timer will be
        scheduled to fire at time=504 (501 + 3).

        With EV, "AnyEvent->time" returns 501 (as that is the current time),
        but "AnyEvent->now" returns 500, as that is the time the last event
        processing phase started. With EV, your timer gets scheduled to run
        at time=503 (500 + 3).

        In one sense, Event::Lib is more exact, as it uses the current time
        regardless of any delays introduced by event processing. However,
        most callbacks do not expect large delays in processing, so this
        causes a higher drift (and a lot more system calls to get the
        current time).

        In another sense, EV is more exact, as your timer will be scheduled
        at the same time, regardless of how long event processing actually
        took.

        In either case, if you care (and in most cases, you don't), then you
        can get whatever behaviour you want with any event loop, by taking
        the difference between "AnyEvent->time" and "AnyEvent->now" into
        account.

    AnyEvent->now_update
        Some event loops (such as EV or AnyEvent::Loop) cache the current
        time for each loop iteration (see the discussion of AnyEvent->now,
        above).

        When a callback runs for a long time (or when the process sleeps),
        then this "current" time will differ substantially from the real
        time, which might affect timers and time-outs.

        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,

README  view on Meta::CPAN

    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
    seconds by default, but can be overriden via
    $ENV{PERL_ANYEVENT_MAX_SIGNAL_LATENCY} or $AnyEvent::MAX_SIGNAL_LATENCY

README  view on Meta::CPAN

    Condition variables are represented by hash refs in perl, and the keys
    used by AnyEvent itself are all named "_ae_XXX" to make subclassing easy
    (it is often useful to build your own transaction class on top of
    AnyEvent). To subclass, use "AnyEvent::CondVar" as base class and call
    its "new" method in your own "new" method.

    There are two "sides" to a condition variable - the "producer side"
    which eventually calls "-> send", and the "consumer side", which waits
    for the send to occur.

    Example: wait for a timer.

       # condition: "wait till the timer is fired"
       my $timer_fired = AnyEvent->condvar;

       # 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 { $timer_fired->send },
       );

       # this "blocks" (while handling events) till the callback
       # calls ->send
       $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;

       ...

README  view on Meta::CPAN


    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:

           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;
           };

SIMPLIFIED AE API

README  view on Meta::CPAN

        requests that are sent to the DNS server.

    "PERL_ANYEVENT_MAX_SIGNAL_LATENCY"
        Perl has inherently racy signal handling (you can basically choose
        between losing signals and memory corruption) - pure perl event
        loops (including "AnyEvent::Loop", when "Async::Interrupt" isn't
        available) therefore have to poll regularly to avoid losing signals.

        Some event loops are racy, but don't poll regularly, and some event
        loops are written in C but are still racy. For those event loops,
        AnyEvent installs a timer that regularly wakes up the event loop.

        By default, the interval for this timer is 10 seconds, but you can
        override this delay with this environment variable (or by setting
        the $AnyEvent::MAX_SIGNAL_LATENCY variable before creating signal
        watchers).

        Lower values increase CPU (and energy) usage, higher values can
        introduce long delays when reaping children or waiting for signals.

        The AnyEvent::Async module, if available, will be used to avoid this
        polling (with most event loops).

README  view on Meta::CPAN

    interpreter inside *rxvt-unicode*, and it is updated and maintained as
    part of the *rxvt-unicode* distribution.

    *rxvt-unicode* also cheats a bit by not providing blocking access to
    condition variables: code blocking while waiting for a condition will
    "die". This still works with most modules/usages, and blocking calls
    must not be done in an interactive application, so it makes sense.

EXAMPLE PROGRAM
    The following program uses an I/O watcher to read data from STDIN, a
    timer to display a message once per second, and a condition variable to
    quit the program when the user enters quit:

       use AnyEvent;

       my $cv = AnyEvent->condvar;

       my $io_watcher = AnyEvent->io (
          fh   => \*STDIN,
          poll => 'r',
          cb   => sub {
             warn "io event <$_[0]>\n";   # will always output <r>
             chomp (my $input = <STDIN>); # read a line
             warn "read: $input\n";       # output what has been read
             $cv->send if $input =~ /^q/i; # quit program if /^q/i
          },
       );

       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

REAL-WORLD EXAMPLE
    Consider the Net::FCP module. It features (among others) the following
    API calls, which are to freenet what HTTP GET requests are to http:

       my $data = $fcp->client_get ($url); # blocks

README  view on Meta::CPAN


       $quit->recv;

BENCHMARKS
    To give you an idea of the performance and overheads that AnyEvent adds
    over the event loops themselves and to give you an impression of the
    speed of various event loops I prepared some benchmarks.

  BENCHMARKING ANYEVENT OVERHEAD
    Here is a benchmark of various supported event models used natively and
    through AnyEvent. The benchmark creates a lot of timers (with a zero
    timeout) and I/O watchers (watching STDOUT, a pty, to become writable,
    which it is), lets them fire exactly once and destroys them again.

    Source code for this benchmark is found as eg/bench in the AnyEvent
    distribution. It uses the AE interface, which makes a real difference
    for the EV and Perl backends only.

   Explanation of the columns
    *watcher* is the number of event watchers created/destroyed. Since
    different event models feature vastly different performances, each event

README  view on Meta::CPAN

    That does not mean that AnyEvent won't take advantage of some additional
    modules if they are installed.

    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
        handling: To my knowledge, there is no way to do completely
        race-free and quick signal handling in pure perl. To ensure that
        signals still get delivered, AnyEvent will start an interval timer
        to wake up perl (and catch the signals) with some delay (default is
        10 seconds, look for $AnyEvent::MAX_SIGNAL_LATENCY).

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

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

        Some event loops (POE, Event, Event::Lib) offer signal watchers
        natively, and either employ their own workarounds (POE) or use
        AnyEvent's workaround (using $AnyEvent::MAX_SIGNAL_LATENCY).
        Installing Async::Interrupt does nothing for those backends.

    EV  This module isn't really "optional", as it is simply one of the
        backend event loops that AnyEvent can use. However, it is simply the
        best event loop available in terms of features, speed and stability:
        It supports the AnyEvent API optimally, implements all the watcher
        types in XS, does automatic timer adjustments even when no monotonic
        clock is available, can take avdantage of advanced kernel interfaces
        such as "epoll" and "kqueue", and is the fastest backend *by far*.
        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

README  view on Meta::CPAN

    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 (see below).

    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 prrocess is usually
    preferred, because it is much easier and cleaner, at the expense of
    having to have another binary.

    In addition to logical problems with fork, there are also implementation
    problems. For example, on POSIX systems, you cannot fork at all in Perl
    code if a thread (I am talking of pthreads here) was ever created in the
    process, and this is just the tip of the iceberg. In general, using fork
    from Perl is difficult, and attempting to use fork without an exec to

eg/bench  view on Meta::CPAN


my $nr = $ARGV[0] || 1000;
my $M = $ARGV[1] || "AnyEvent";

#$nr *= .01;

my $todo;

my $cv;

my (@io, @timer);

AnyEvent::detect;

my $cb = sub {
   $cv->broadcast unless --$todo;
};

$| = 1;

print "name $ARGV[2]\n";
print "watchers ", $nr * 2, "\n";

my $m = qx<ps h -orss $$>;
my $c = time;

my $fh = \*STDOUT;

for (1..$nr) {
   if ($M eq "EV") {
      push @io, EV::io $fh, EV::WRITE, $cb;
      push @timer, EV::timer 0, 0, $cb;
   } elsif ($M eq "Event") {
      push @io, Event->io (fd => $fh, poll => "w", cb => $cb);
      push @timer, Event->timer (after => 0, cb => $cb);
   } else {
      push @io, AnyEvent->io (fh => $fh, poll => "w", cb => $cb);
      push @timer, AnyEvent->timer (after => 0, cb => $cb);
   }
}

$c = (time - $c) / $nr / 2 * 1e6;
$m = int 0.5 + (qx<ps h -orss $$> - $m) * 1024 / $nr / 2;

printf "bytes %d\n", $m;
printf "create %.2f\n", $c;

$cv   = AnyEvent->condvar;

eg/bench  view on Meta::CPAN


$cv->wait;

$i = (time - $i) / $nr / 2 * 1e6;

printf "invoke %.2f\n", $i;

my $d = time;

if ($M eq "Event") {
   $_->cancel for (@io, @timer);
}
@io = @timer = ();

{
   my $w = AnyEvent->timer (after => 0, cb => sub { });
   AnyEvent->one_event;
}

$d = (time - $d) / $nr / 2 * 1e6;

printf "destroy %.2f\n", $d;


eg/bench2  view on Meta::CPAN


my @conn; @conn = map {
   socketpair my $a, my $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die "$!";
   my $self; $self = {
      r => $a,
      w => $b,
      rw => AnyEvent->io (fh => $a, poll => "r", cb => sub {
               ++$count;
               sysread $a, my $buf, 1;
               syswrite $conn[rand @conn]{w}, $buf, 1;
               $self->{to} = AnyEvent->timer (after => 3600, cb => sub { die });
            }),
      to => AnyEvent->timer (after => 3600, cb => sub { die }),
   };
   $self
} 1 .. $nr;

$c = (time - $c) / $nr * 1e6;

printf "create %.2f\n", $c;

for (1 .. $ARGV[1] || $nr * 0.01) {
   syswrite $conn[rand @conn]{w}, $_, 1;
}

my $i = time;

my $stop = AnyEvent->timer (after => 1, cb => sub {
   $i = (time - $i) / $count * 1e6;
   printf "request %.2f\n", $i;
   exit;
});

AnyEvent->condvar->wait;



lib/AE.pm  view on Meta::CPAN


AE - simpler/faster/newer/cooler AnyEvent API

=head1 SYNOPSIS

  use AnyEvent; # not AE

  # file handle or descriptor readable
  my $w = AE::io $fh, 0, sub { ...  };

  # one-shot or repeating timers
  my $w = AE::timer $seconds,         0, sub { ... }; # once
  my $w = AE::timer $seconds, $interval, sub { ... }; # repeated

  print AE::now;  # prints current event loop time
  print AE::time; # think Time::HiRes::time or simply CORE::time.

  # POSIX signal
  my $w = AE::signal TERM => sub { ... };

  # child process exit
  my $w = AE::child $pid, sub {
     my ($pid, $status) = @_;

lib/AE.pm  view on Meta::CPAN

specified by C<$watch_write>) can be done on the file handle/descriptor.

Example: wait until STDIN becomes readable.

  $stdin_ready = AE::io *STDIN, 0, sub { scalar <STDIN> };

Example: wait until STDOUT becomes writable and print something.

  $stdout_ready = AE::io *STDOUT, 1, sub { print STDOUT "woaw\n" };

=item $w = AE::timer $after, $interval, $cb

Creates a timer watcher that invokes the callback C<$cb> after at least
C<$after> second have passed (C<$after> can be negative or C<0>).

If C<$interval> is C<0>, then the callback will only be invoked once,
otherwise it must be a positive number of seconds that specifies the
interval between successive invocations of the callback.

Example: print "too late" after at least one second has passed.

  $timer_once = AE::timer 1, 0, sub { print "too late\n" };

Example: print "blubb" once a second, starting as soon as possible.

  $timer_repeated = AE::timer 0, 1, sub { print "blubb\n" };

=item $w = AE::signal $signame, $cb

Invoke the callback C<$cb> each time one or more occurrences of the
named signal C<$signame> are detected.

=item $w = AE::child $pid, $cb

Invokes the callback C<$cb> when the child with the given C<$pid> exits
(or all children, when C<$pid> is zero).

lib/AnyEvent.pm  view on Meta::CPAN

=head1 SYNOPSIS

   use AnyEvent;

   # 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
   my $w = AnyEvent->timer (after => $seconds, cb => sub { ...  });
   my $w = AnyEvent->timer (after => $seconds, interval => $seconds, cb => ...);

   print AnyEvent->now;  # prints current event loop time
   print AnyEvent->time; # think Time::HiRes::time or simply CORE::time.

   # POSIX signal
   my $w = AnyEvent->signal (signal => "TERM", cb => sub { ... });

   # child process exit
   my $w = AnyEvent->child (pid => $pid, cb => sub {
      my ($pid, $status) = @_;

lib/AnyEvent.pm  view on Meta::CPAN


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.

lib/AnyEvent.pm  view on Meta::CPAN

callbacks must not C<die> >>. The former is good programming practice in
Perl and the latter stems from the fact that exception handling differs
widely between event loops.

To disable a watcher you have to destroy it (e.g. by setting the
variable you store it in to C<undef> or otherwise deleting all references
to it).

All watchers are created by calling a method on the C<AnyEvent> class.

Many watchers either are used with "recursion" (repeating timers for
example), or need to refer to their watcher object in other ways.

One way to achieve that is this pattern:

   my $w; $w = AnyEvent->type (arg => value ..., cb => sub {
      # you can use $w here, for example to undef it
      undef $w;
   });

Note that C<my $w; $w => combination. This is necessary because in Perl,

lib/AnyEvent.pm  view on Meta::CPAN

watcher.

   my $w; $w = AnyEvent->io (fh => \*STDIN, poll => 'r', cb => sub {
      chomp (my $input = <STDIN>);
      warn "read: $input\n";
      undef $w;
   });

=head2 TIME WATCHERS

   $w = AnyEvent->timer (after => <seconds>, cb => <callback>);

   $w = AnyEvent->timer (
      after    => <fractional_seconds>,
      interval => <fractional_seconds>,
      cb       => <callback>,
   );

You can create a time watcher by calling the C<< AnyEvent->timer >>
method with the following mandatory arguments:

C<after> specifies after how many seconds (fractional values are
supported) the callback should be invoked. C<cb> is the callback to invoke
in that case.

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 time watcher callbacks.

The callback will normally be invoked only once. If you specify another
parameter, C<interval>, as a strictly positive number (> 0), then the
callback will be invoked regularly at that interval (in fractional
seconds) after the first invocation. If C<interval> is specified with a
false value, then it is treated as if it were not specified at all.

The callback will be rescheduled before invoking the callback, but no
attempt is made to avoid timer drift in most backends, so the interval is
only approximate.

Example: fire an event after 7.7 seconds.

   my $w = AnyEvent->timer (after => 7.7, cb => sub {
      warn "timeout\n";
   });

   # to cancel the timer:
   undef $w;

Example 2: fire an event after 0.5 seconds, then roughly every second.

   my $w = AnyEvent->timer (after => 0.5, interval => 1, cb => sub {
      warn "timeout\n";
   });

=head3 TIMING ISSUES

There are two ways to handle timers: based on real time (relative, "fire
in 10 seconds") and based on wallclock time (absolute, "fire at 12
o'clock").

While most event loops expect timers to specified in a relative way, they
use absolute time internally. This makes a difference when your clock
"jumps", for example, when ntp decides to set your clock backwards from
the wrong date of 2014-01-01 to 2008-01-01, a watcher that is supposed to
fire "after a second" might actually take six years to finally fire.

AnyEvent cannot compensate for this. The only event loop that is conscious
of these issues is L<EV>, which offers both relative (ev_timer, based
on true relative time) and absolute (ev_periodic, based on wallclock time)
timers.

AnyEvent always prefers relative timers, if available, matching the
AnyEvent API.

AnyEvent has two additional methods that return the "current time":

=over 4

=item AnyEvent->time

This returns the "current wallclock time" as a fractional number of
seconds since the Epoch (the same thing as C<time> or C<Time::HiRes::time>
return, and the result is guaranteed to be compatible with those).

It progresses independently of any event loop processing, i.e. each call
will check the system clock, which usually gets updated frequently.

=item AnyEvent->now

This also returns the "current wallclock time", but unlike C<time>, above,
this value might change only once per event loop iteration, depending on
the event loop (most return the same time as C<time>, above). This is the
time that AnyEvent's timers get scheduled against.

I<In almost all cases (in all cases if you don't care), this is the
function to call when you want to know the current time.>

This function is also often faster then C<< AnyEvent->time >>, and
thus the preferred method if you want some timestamp (for example,
L<AnyEvent::Handle> uses this to update its activity timeouts).

The rest of this section is only of relevance if you try to be very exact
with your timing; you can skip it without a bad conscience.

For a practical example of when these times differ, consider L<Event::Lib>
and L<EV> and the following set-up:

The event loop is running and has just invoked one of your callbacks at
time=500 (assume no other callbacks delay processing). In your callback,
you wait a second by executing C<sleep 1> (blocking the process for a
second) and then (at time=501) you create a relative timer that fires
after three seconds.

With L<Event::Lib>, C<< AnyEvent->time >> and C<< AnyEvent->now >> will
both return C<501>, because that is the current time, and the timer will
be scheduled to fire at time=504 (C<501> + C<3>).

With L<EV>, C<< AnyEvent->time >> returns C<501> (as that is the current
time), but C<< AnyEvent->now >> returns C<500>, as that is the time the
last event processing phase started. With L<EV>, your timer gets scheduled
to run at time=503 (C<500> + C<3>).

In one sense, L<Event::Lib> is more exact, as it uses the current time
regardless of any delays introduced by event processing. However, most
callbacks do not expect large delays in processing, so this causes a
higher drift (and a lot more system calls to get the current time).

In another sense, L<EV> is more exact, as your timer will be scheduled at
the same time, regardless of how long event processing actually took.

In either case, if you care (and in most cases, you don't), then you
can get whatever behaviour you want with any event loop, by taking the
difference between C<< AnyEvent->time >> and C<< AnyEvent->now >> into
account.

=item AnyEvent->now_update

Some event loops (such as L<EV> or L<AnyEvent::Loop>) cache the current
time for each loop iteration (see the discussion of L<< AnyEvent->now >>,
above).

When a callback runs for a long time (or when the process sleeps), then
this "current" time will differ substantially from the real time, which
might affect timers and time-outs.

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. C<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 C<<
AnyEvent->now_update >> each time the web server process wakes up again
(e.g. at the start of your script, or in a handler).

lib/AnyEvent.pm  view on Meta::CPAN

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
means in some cases, signals will be delayed. The maximum time
a signal might be delayed is 10 seconds by default, but can

lib/AnyEvent.pm  view on Meta::CPAN

Condition variables are represented by hash refs in perl, and the keys
used by AnyEvent itself are all named C<_ae_XXX> to make subclassing
easy (it is often useful to build your own transaction class on top of
AnyEvent). To subclass, use C<AnyEvent::CondVar> as base class and call
its C<new> method in your own C<new> method.

There are two "sides" to a condition variable - the "producer side" which
eventually calls C<< -> send >>, and the "consumer side", which waits
for the send to occur.

Example: wait for a timer.

   # condition: "wait till the timer is fired"
   my $timer_fired = AnyEvent->condvar;

   # 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 { $timer_fired->send },
   );

   # this "blocks" (while handling events) till the callback
   # calls ->send
   $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;

   ...

lib/AnyEvent.pm  view on Meta::CPAN

=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

lib/AnyEvent.pm  view on Meta::CPAN

sub _postpone_exec {
   undef $POSTPONE_W;

   &{ shift @POSTPONE }
      while @POSTPONE;
}

sub postpone(&) {
   push @POSTPONE, shift;

   $POSTPONE_W ||= AE::timer (0, 0, \&_postpone_exec);

   ()
}

sub log($$;@) {
   # only load the big bloated module when we actually are about to log something
   if ($_[0] <= ($VERBOSE || 1)) { # also catches non-numeric levels(!) and fatal
      local ($!, $@);
      require AnyEvent::Log; # among other things, sets $VERBOSE to 9
      # AnyEvent::Log overwrites this function

lib/AnyEvent.pm  view on Meta::CPAN

sub _isa_hook($$;$) {
   my ($i, $pkg, $reset_ae) = @_;

   $isa_hook[$i] = $pkg ? [$pkg, $reset_ae] : undef;

   _isa_set;
}

# all autoloaded methods reserve the complete glob, not just the method slot.
# due to bugs in perls method cache implementation.
our @methods = qw(io timer time now now_update signal child idle condvar);

sub detect() {
   return $MODEL if $MODEL; # some programs keep references to detect

   # IO::Async::Loop::AnyEvent is extremely evil, refuse to work with it
   # the author knows about the problems and what it does to AnyEvent as a whole
   # (and the ability of others to use AnyEvent), but simply wants to abuse AnyEvent
   # anyway.
   AnyEvent::log fatal => "IO::Async::Loop::AnyEvent detected - that module is broken by\n"
                        . "design, abuses internals and breaks AnyEvent - will not continue."

lib/AnyEvent.pm  view on Meta::CPAN


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])
      }

lib/AnyEvent.pm  view on Meta::CPAN

}

our ($SIGPIPE_R, $SIGPIPE_W, %SIG_CB, %SIG_EV, $SIG_IO);
our (%SIG_ASY, %SIG_ASY_W);
our ($SIG_COUNT, $SIG_TW);

# install a dummy wakeup watcher to reduce signal catching latency
# used by Impls
sub _sig_add() {
   unless ($SIG_COUNT++) {
      # try to align timer on a full-second boundary, if possible
      my $NOW = AE::now;

      $SIG_TW = AE::timer
         $MAX_SIGNAL_LATENCY - ($NOW - int $NOW),
         $MAX_SIGNAL_LATENCY,
         sub { } # just for the PERL_ASYNC_CHECK
      ;
   }
}

sub _sig_del {
   undef $SIG_TW
      unless --$SIG_COUNT;

lib/AnyEvent.pm  view on Meta::CPAN

sub signal {
   eval q{ # poor man's autoloading {}
      # probe for availability of Async::Interrupt 
      if (_have_async_interrupt) {
         AnyEvent::log 8 => "Using Async::Interrupt for race-free signal handling.";

         $SIGPIPE_R = new Async::Interrupt::EventPipe;
         $SIG_IO = AE::io $SIGPIPE_R->fileno, 0, \&_signal_exec;

      } else {
         AnyEvent::log 8 => "Using emulated perl signal handling with latency timer.";

         if (AnyEvent::WIN32) {
            require AnyEvent::Util;

            ($SIGPIPE_R, $SIGPIPE_W) = AnyEvent::Util::portable_pipe ();
            AnyEvent::Util::fh_nonblocking ($SIGPIPE_R, 1) if $SIGPIPE_R;
            AnyEvent::Util::fh_nonblocking ($SIGPIPE_W, 1) if $SIGPIPE_W; # just in case
         } else {
            pipe $SIGPIPE_R, $SIGPIPE_W;
            fcntl $SIGPIPE_R, AnyEvent::F_SETFL, AnyEvent::O_NONBLOCK if $SIGPIPE_R;

lib/AnyEvent.pm  view on Meta::CPAN

         delete $PID_CB{$pid} unless keys %{ $PID_CB{$pid} };

         undef $CHLD_W unless keys %PID_CB;
      };
   };
   die if $@;

   &child
}

# idle emulation is done by simply using a timer, regardless
# of whether the process is idle or not, and not letting
# the callback use more than 50% of the time.
sub idle {
   eval q{ # poor man's autoloading {}
      *idle = sub {
         my (undef, %arg) = @_;

         my ($cb, $w, $rcb) = $arg{cb};

         $rcb = sub {
            if ($cb) {
               $w = AE::time;
               &$cb;
               $w = AE::time - $w;

               # never use more then 50% of the time for the idle watcher,
               # within some limits
               $w = 0.0001 if $w < 0.0001;
               $w = 5      if $w > 5;

               $w = AE::timer $w, 0, $rcb;
            } else {
               # clean up...
               undef $w;
               undef $rcb;
            }
         };

         $w = AE::timer 0.05, 0, $rcb;

         bless \\$cb, "AnyEvent::Base::idle"
      };

      *AnyEvent::Base::idle::DESTROY = sub {
         undef $${$_[0]};
      };
   };
   die if $@;

lib/AnyEvent.pm  view on Meta::CPAN


=item C<PERL_ANYEVENT_MAX_SIGNAL_LATENCY>

Perl has inherently racy signal handling (you can basically choose between
losing signals and memory corruption) - pure perl event loops (including
C<AnyEvent::Loop>, when C<Async::Interrupt> isn't available) therefore
have to poll regularly to avoid losing signals.

Some event loops are racy, but don't poll regularly, and some event loops
are written in C but are still racy. For those event loops, AnyEvent
installs a timer that regularly wakes up the event loop.

By default, the interval for this timer is C<10> seconds, but you can
override this delay with this environment variable (or by setting
the C<$AnyEvent::MAX_SIGNAL_LATENCY> variable before creating signal
watchers).

Lower values increase CPU (and energy) usage, higher values can introduce
long delays when reaping children or waiting for signals.

The L<AnyEvent::Async> module, if available, will be used to avoid this
polling (with most event loops).

lib/AnyEvent.pm  view on Meta::CPAN

inside I<rxvt-unicode>, and it is updated and maintained as part of the
I<rxvt-unicode> distribution.

I<rxvt-unicode> also cheats a bit by not providing blocking access to
condition variables: code blocking while waiting for a condition will
C<die>. This still works with most modules/usages, and blocking calls must
not be done in an interactive application, so it makes sense.

=head1 EXAMPLE PROGRAM

The following program uses an I/O watcher to read data from STDIN, a timer
to display a message once per second, and a condition variable to quit the
program when the user enters quit:

   use AnyEvent;

   my $cv = AnyEvent->condvar;

   my $io_watcher = AnyEvent->io (
      fh   => \*STDIN,
      poll => 'r',
      cb   => sub {
         warn "io event <$_[0]>\n";   # will always output <r>
         chomp (my $input = <STDIN>); # read a line
         warn "read: $input\n";       # output what has been read
         $cv->send if $input =~ /^q/i; # quit program if /^q/i
      },
   );

   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

=head1 REAL-WORLD EXAMPLE

Consider the L<Net::FCP> module. It features (among others) the following
API calls, which are to freenet what HTTP GET requests are to http:

lib/AnyEvent.pm  view on Meta::CPAN


=head1 BENCHMARKS

To give you an idea of the performance and overheads that AnyEvent adds
over the event loops themselves and to give you an impression of the speed
of various event loops I prepared some benchmarks.

=head2 BENCHMARKING ANYEVENT OVERHEAD

Here is a benchmark of various supported event models used natively and
through AnyEvent. The benchmark creates a lot of timers (with a zero
timeout) and I/O watchers (watching STDOUT, a pty, to become writable,
which it is), lets them fire exactly once and destroys them again.

Source code for this benchmark is found as F<eg/bench> in the AnyEvent
distribution. It uses the L<AE> interface, which makes a real difference
for the EV and Perl backends only.

=head3 Explanation of the columns

I<watcher> is the number of event watchers created/destroyed. Since

lib/AnyEvent.pm  view on Meta::CPAN

This section explains which additional modules will be used, and how they
affect AnyEvent's operation.

=over 4

=item L<Async::Interrupt>

This slightly arcane module is used to implement fast signal handling: To
my knowledge, there is no way to do completely race-free and quick
signal handling in pure perl. To ensure that signals still get
delivered, AnyEvent will start an interval timer to wake up perl (and
catch the signals) with some delay (default is 10 seconds, look for
C<$AnyEvent::MAX_SIGNAL_LATENCY>).

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

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

lib/AnyEvent.pm  view on Meta::CPAN

and either employ their own workarounds (POE) or use AnyEvent's workaround
(using C<$AnyEvent::MAX_SIGNAL_LATENCY>). Installing L<Async::Interrupt>
does nothing for those backends.

=item L<EV>

This module isn't really "optional", as it is simply one of the backend
event loops that AnyEvent can use. However, it is simply the best event
loop available in terms of features, speed and stability: It supports
the AnyEvent API optimally, implements all the watcher types in XS, does
automatic timer adjustments even when no monotonic clock is available,
can take avdantage of advanced kernel interfaces such as C<epoll> and
C<kqueue>, and is the fastest backend I<by far>. You can even embed
L<Glib>/L<Gtk2> in it (or vice versa, see L<EV::Glib> and L<Glib::EV>).

If you only use backends that rely on another event loop (e.g. C<Tk>),
then this module will do nothing for you.

=item L<Guard>

The guard module, when used, will be used to implement

lib/AnyEvent.pm  view on Meta::CPAN

usually happens when the first AnyEvent watcher is created, or the library
is loaded).

If you have to fork, you must either do so I<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 (see below).

The problem of doing event processing in the parent I<and> the child
is much more complicated: even for backends that I<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 C<exec>
to start worker children from some kind of manage prrocess is usually
preferred, because it is much easier and cleaner, at the expense of having
to have another binary.

In addition to logical problems with fork, there are also implementation
problems. For example, on POSIX systems, you cannot fork at all in Perl
code if a thread (I am talking of pthreads here) was ever created in the
process, and this is just the tip of the iceberg. In general, using fork
from Perl is difficult, and attempting to use fork without an exec to

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

   $do_retry = sub {
      my $retry_cfg = $self->{retry}[$retry++]
         or do {
            # failure
            $self->_free_id ($req->[2], $retry > 1);
            undef $do_retry; return $req->[1]->();
         };

      my ($server, $timeout) = @$retry_cfg;
      
      $self->{id}{$req->[2]} = [(AE::timer $timeout, 0, sub {
         $NOW = time;

         # timeout, try next
         &$do_retry if $do_retry;
      }), sub {
         my ($res) = @_;

         if ($res->{tc}) {
            # success, but truncated, so use tcp
            AnyEvent::Socket::tcp_connect (AnyEvent::Socket::format_address ($server), DOMAIN_PORT, sub {

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

   $NOW = time;

   # first clear id reuse queue
   delete $self->{id}{ (shift @{ $self->{reuse_q} })->[1] }
      while @{ $self->{reuse_q} } && $self->{reuse_q}[0][0] <= $NOW;

   while ($self->{outstanding} < $self->{max_outstanding}) {

      if (@{ $self->{reuse_q} } >= 30000) {
         # we ran out of ID's, wait a bit
         $self->{reuse_to} ||= AE::timer $self->{reuse_q}[0][0] - $NOW, 0, sub {
            delete $self->{reuse_to};
            $self->_scheduler;
         };
         last;
      }

      if (my $req = shift @{ $self->{queue} }) {
         # found a request in the queue, execute it
         while () {
            $req->[2] = int rand 65536;

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


=cut

package AnyEvent::Debug::Wrap;

use AnyEvent (); BEGIN { AnyEvent::common_sense }
use Scalar::Util ();
use Carp ();

sub _reset {
   for my $name (qw(io timer signal child idle)) {
      my $super = "SUPER::$name";

      *$name = sub {
         my ($self, %arg) = @_;

         my $w;

         my $t = $TRACE;

         my ($pkg, $file, $line, $sub);

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


These wrapper objects can be stringified and have some methods defined on
them.

For debugging, of course, it can be helpful to look into these objects,
which is why this is documented here, but this might change at any time in
future versions.

Each object is a relatively standard hash with the following members:

   type   => name of the method used ot create the watcher (e.g. C<io>, C<timer>).
   w      => the actual watcher
   rfile  => reference to the filename of the file the watcher was created in
   line   => line number where it was created
   sub    => function name (or a special string) which created the watcher
   cur    => if created inside another watcher callback, this is the string rep of the other watcher
   now    => the timestamp (AE::now) when the watcher was created
   arg    => the arguments used to create the watcher (sans C<cb>)
   cb     => the original callback used to create the watcher
   called => the number of times the callback was called

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


Programmers new to event-based programming often forget that you can
actually do other stuff while "waiting" for an event to occur and
therefore forget to actually wait when they do not, in fact, have anything
else to do.

Here is an example:

   use AnyEvent;

   my $timer = AnyEvent->timer (after => 5, cb => sub { say "hi" });

The expectation might be for the program to print "hi" after 5 seconds
and then probably to exit. However, if you run this, your program will
exit almost instantly: Creating the timer does not wait for it, instead
the C<timer> method returns immediately and perl executes the rest of the
program. But there is nothing left to execute, so perl exits.

To force AnyEvent to wait for something, use a condvar:

   use AnyEvent;

   my $quit_program = AnyEvent->condvar;
   my $timer = AnyEvent->timer (after => 5, cb => sub { $quit_program->send });

   $quit_program->recv;

Here the program doesn't immediately exit, because it first waits for
the "quit_program" condition.

In most cases, your main program should call the event library "loop"
function directly:

   use EV;

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

The session in C<< $handle->{tls} >> can still be examined in this
callback, even when the handshake was not successful.

TLS handshake failures will not cause C<on_error> to be invoked when this
callback is in effect, instead, the error message will be passed to C<on_starttls>.

Without this callback, handshake failures lead to C<on_error> being
called as usual.

Note that you cannot just call C<starttls> again in this callback. If you
need to do that, start an zero-second timer instead whose callback can
then call C<< ->starttls >> again.

=item on_stoptls => $cb->($handle)

When a SSLv3/TLS shutdown/close notify/EOF is detected and this callback is
set, then it will be invoked after freeing the TLS session. If it is not,
then a TLS shutdown condition will be treated like a normal EOF condition
on the handle.

The session in C<< $handle->{tls} >> can still be examined in this

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

            # callback could have changed timeout value, optimise
            return unless $self->{$timeout};

            # calculate new after
            $after = $self->{$timeout};
         }

         Scalar::Util::weaken $self;
         return unless $self; # ->error could have destroyed $self

         $self->{$tw} ||= AE::timer $after, 0, sub {
            delete $self->{$tw};
            $cb->($self);
         };
      } else {
         delete $self->{$tw};
      }
   }
}

#############################################################################

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


      push @linger, AE::io $fh, 1, sub {
         my $len = syswrite $fh, $wbuf, length $wbuf;

         if ($len > 0) {
            substr $wbuf, 0, $len, "";
         } elsif (defined $len || ($! != EAGAIN && $! != EINTR && $! != EWOULDBLOCK && $! != WSAEWOULDBLOCK)) {
            @linger = (); # end
         }
      };
      push @linger, AE::timer $linger, 0, sub {
         @linger = ();
      };
   }
}

=item $handle->destroy

Shuts down the handle object as much as possible - this call ensures that
no further callbacks will be invoked and as many resources as possible
will be freed. Any method you will call on the handle object after

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

It does not support blocking waits.

=head1 BUGS

Right now, L<Cocoa::EventLoop> (and this module) are in an early
development phase and has some shortcomings and likely bugs.

For example, there seems to be no way to just handle a single event
with Cocoa (is there nothing they can implement properly?), so this
module currently wakes up at least ten times a second when waiting for
events. Also, events caused by timers might get delayed by up to 0.1
seconds.

=cut

package AnyEvent::Impl::Cocoa;

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

use Cocoa::EventLoop;

sub io {
   my ($class, %arg) = @_;

   Cocoa::EventLoop->io (%arg)
}

sub timer {
   my ($class, %arg) = @_;

   Cocoa::EventLoop->timer (%arg)
}

# does not support blocking waits

#sub loop {
#   Cocoa::EventLoop->run;
#}

=head1 AUTHORS

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

=cut

package AnyEvent::Impl::EV;

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

*AE::time       = \&EV::time;
*AE::now        = \&EV::now;
*AE::now_update = \&EV::now_update;
*AE::timer      = \&EV::timer;
*AE::signal     = \&EV::signal;
*AE::idle       = \&EV::idle;

# cannot override directly, as EV doesn't allow arguments
sub time       { EV::time       }
sub now        { EV::now        }
sub now_update { EV::now_update }

*AE::io = defined &EV::_ae_io # 3.8+, but keep just in case it is dropped
   ? \&EV::_ae_io
   : sub($$$) { EV::io $_[0], $_[1] ? EV::WRITE : EV::READ, $_[2] };

sub timer {
   my ($class, %arg) = @_;

   EV::timer $arg{after}, $arg{interval}, $arg{cb}
}

sub io {
   my ($class, %arg) = @_;

   EV::io
      $arg{fh},
      $arg{poll} eq "r" ? EV::READ : EV::WRITE,
      $arg{cb}
}

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

use Event qw(unloop); # we have to import something to make Event use Time::HiRes

sub io {
   my (undef, %arg) = @_;
   $arg{fd} = delete $arg{fh};
   $arg{poll} .= "e" if AnyEvent::WIN32; # work around windows connect bug
   my $cb = $arg{cb}; $arg{cb} = sub { &$cb }; # event doesn't like callable objects
   bless \(Event->io (%arg)), __PACKAGE__
}

sub timer {
   my (undef, %arg) = @_;
   $arg{after} = 0 if $arg{after} < 0;
   my $cb = $arg{cb}; $arg{cb} = sub { &$cb }; # event doesn't like callable objects
   bless \Event->timer (%arg, repeat => $arg{interval}), __PACKAGE__
}

sub idle {
   my (undef, %arg) = @_;
   my $cb = $arg{cb}; $arg{cb} = sub { &$cb }; # event doesn't like callable objects
   bless \Event->idle (repeat => 1, min => 0, %arg), __PACKAGE__
}

sub DESTROY {
   ${$_[0]}->cancel;

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

problems.

It also doesn't work around the Windows bug of not signalling TCP
connection failures.

It also doesn't work with many special devices on Linux (F</dev/random>
works, F</dev/urandom> fails, F</dev/tty> works, F</dev/null> fails and so
on).

Event::Lib does not support idle watchers. They could be emulated using
low-priority timers but as the priority range (and availability) is not
queryable nor guaranteed, and the default priority is likely the lowest
one, this module cannot use them.

Avoid Event::Lib if you can.

=cut

package AnyEvent::Impl::EventLib;

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

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

   # - only one callback per fd/poll combination
   my ($fh, $mode) = AnyEvent::_dupfh $arg{poll}, $arg{fh}, EV_READ, EV_WRITE;

   # event_new errornously takes a reference to fh and cb instead of making a copy
   # fortunately, going through %arg/_dupfh already makes a copy, so it happpens to work
   my $w = event_new $fh, $mode | EV_PERSIST, $ccb, $arg{cb};
   event_add $w;
   bless \\$w, __PACKAGE__
}

sub timer {
   my (undef, %arg) = @_;

   my $ival = $arg{interval};
   my $cb   = $arg{cb};

   my $w; $w = timer_new $ccb,
                  $ival
                     ? sub { event_add $w, $ival; &$cb }
                     : sub { undef $w           ; &$cb };

   event_add $w, $arg{after} || 1e-10; # work around 0-bug in Event::Lib

   bless \\$w, __PACKAGE__
}

sub DESTROY {

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


This module provides transparent support for AnyEvent. You don't have to
do anything to make FLTK work with AnyEvent except by loading FLTK before
creating the first AnyEvent watcher.

This implementation is not to be confused with AnyEvent::Impl::FLTK by
Sanko Robinson. That implementation is completely broken, and the author
is apparently unreachable.

In any case, FLTK suffers from typical GUI-ToolKit diseases, such as O(n)
or worse for every operation (adding a timer, destroying a timer etc.),
the typical Not-Well-Tested Perl Interface disases such as non-random
memory corruption and the typical Event-Loop-as-an-Afterthrough issues,
such as multiple watchers on the same fd silently overwriting the others.

It doesn't have native idle, signal or child watchers, so all of these are
emulated.

=cut

package AnyEvent::Impl::FLTK;

use AnyEvent (); BEGIN { AnyEvent::common_sense }
use FLTK 0.532 ();
use Scalar::Util ();

#*AE::timer      = \&EV::timer;
#*AE::signal     = \&EV::signal;
#*AE::idle       = \&EV::idle;

# FLTK::get_time_secs returns a glob :/
# on unix, fltk uses gettimeofday, so we are likely compatible
# on windows, fltk uses GetTickCount, to which we are unlikely to be compatible with.
#sub time { FLTK::get_time_secs }
#*now = \&time;

sub timer_interval_cb {
   my $id = shift; # add_timeout kills @_, so we have to make a copy :(
   $id->[0] = FLTK::add_timeout $id->[1], \&timer_interval_cb, $id;
   &{ $id->[2] }
}

sub timer {
   my ($class, %arg) = @_;

   my $cb = $arg{cb};

   if ($arg{interval}) {
      my $id = [undef, $arg{interval}, $cb];

      $id->[0] = FLTK::add_timeout $arg{after}, \&timer_interval_cb, $id;

      return bless $id, "AnyEvent::Impl::FLTK::timer"
   } else {
      # non-repeating timers can be done very efficiently
      # also, FLTK doesn't like callable objects
      return FLTK::add_timeout $arg{after}, sub { &$cb }
   }
}

sub AnyEvent::Impl::FLTK::timer::DESTROY {
   undef $_[0][0];
}

sub io {
   my ($class, %arg) = @_;

   # only one watcher/fd :(

   my $cb = $arg{cb};
   my ($fh, $ev) = AnyEvent::_dupfh $arg{poll}, $arg{fh},

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

   # this module gets loaded automatically as required

=head1 DESCRIPTION

This module provides transparent support for AnyEvent. You don't have to
do anything to make Glib work with AnyEvent except by loading Glib before
creating the first AnyEvent watcher.

Glib is probably the most inefficient event loop that has ever seen the
light of the world: Glib not only scans all its watchers (really, ALL of
them, whether I/O-related, timer-related or what not) during each loop
iteration, it also does so multiple times and rebuilds the poll list for
the kernel each time again, dynamically even. Newer versions of libglib
fortunately do not call malloc/free on every single watcher invocation,
though.

Glib also enforces certain undocumented behaviours, for example, you
cannot always remove active child watchers, and the conditions on when
it is valid to do so are not documented. Of course, if you get it wrong,
you get "GLib-CRITICAL" messages. This makes it extremely hard to write
"correct" glib programs, as you have to study the source code to get it

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

   defined $fd or $fd = $arg{fh};

   my $source = add_watch Glib::IO
      $fd,
      $io_cond{$arg{poll}},
      sub { &$cb; 1 };

   bless \\$source, $class
}

sub timer {
   my ($class, %arg) = @_;
   
   my $cb   = $arg{cb};
   my $ival = $arg{interval} * 1000;

   my $source; $source = add Glib::Timeout $arg{after} < 0 ? 0 : $arg{after} * 1000,
      $ival ? sub {
                remove Glib::Source $source;
                $source = add Glib::Timeout $ival, sub { &$cb; 1 };
                &$cb;

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

  use IO::Async::Loop;

  # optionally set another event loop
  use AnyEvent::Impl::IOAsync;
  my $loop = new IO::Async::Loop;
  AnyEvent::Impl::IOAsync::set_loop $loop;

=head1 DESCRIPTION

This module provides support for IO::Async as AnyEvent backend. It supports
I/O, timers, signals and child process watchers. Idle watchers are emulated.
I/O watchers need to dup their fh because IO::Async only supports IO handles,
not plain file descriptors.

=head1 FUNCTIONS AND VARIABLES

The only user-servicible part in this module is the C<set_loop> function
and C<$LOOP> variable:

=over 4

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


There are a few remaining problems that require emulation or workarounds:

=over 4

=item No support for multiple watchers per event

In most (all? documentation?) cases you cannot have multiple watchers
for the same event (what's the point of having all these fancy notifier
classes when you cannot have multiple notifiers for the same event? That's
like only allowing one timer per second or so...).

For I/O watchers, AnyEvent has to dup() every file handle, as IO::Async
fails to support the same or different file handles pointing to the same
fd (the good thing is that it is documented, but why not fix it instead?).

=back

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

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


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

The method naming is chaotic: C<watch_child> creates a child watcher,
but C<watch_io> is an internal method; C<detach_signal> removes a signal
watcher, but C<detach_child> forks a subprocess and so on).

=item Unpleasant surprises on GNU/Linux

When you develop your program on FreeBSD and run it on GNU/Linux, you
might have unpleasant surprises, as IO::Async::Loop will by default use

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

use Scalar::Util ();

use IO::Async::Loop 0.33;

our $LOOP = new IO::Async::Loop;

sub set_loop($) {
   $LOOP = $_[0];
}

sub timer {
   my ($class, %arg) = @_;
   
   my $cb = $arg{cb};

   my $id;

   if (my $ival = $arg{interval}) {
      my $ival_cb; $ival_cb = sub {
         $id = $LOOP->enqueue_timer (delay => $ival, code => $ival_cb);
         &$cb;
      };
      $id = $LOOP->enqueue_timer (delay => $arg{after}, code => $ival_cb);

      # we have to weaken afterwards, but when enqueue dies, we have a memleak.
      # still, we do anything for speed...
      Scalar::Util::weaken $ival_cb;

   } else {
      # IO::Async has problems with overloaded objects
      $id = $LOOP->enqueue_timer (delay => $arg{after}, code => sub {
         undef $id; # IO::Async <= 0.43 bug workaround
         &$cb;
      });
   }

   bless \\$id, "AnyEvent::Impl::IOAsync::timer"
}

sub AnyEvent::Impl::IOAsync::timer::DESTROY {
   # Need to be well-behaved during global destruction
   $LOOP->cancel_timer (${${$_[0]}})
      if defined ${${$_[0]}}; # IO::Async <= 0.43 bug workaround
}

sub io {
   my ($class, %arg) = @_;

   # Ensure we have a real IO handle, and not just a UNIX fd integer
   my ($fh) = AnyEvent::_dupfh $arg{poll}, $arg{fh};

   my $event = $arg{poll} eq "r" ? "on_read_ready" : "on_write_ready";

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

to never call C<recv> on a condvar that hasn't been signalled yet.

=item * Child exits will be handled by AnyEvent.

AnyEvent will take over child handling, as Irssi only polls for children
once/second and cannot handle unspecific child watchers.

This I<should> have no negative effect, as AnyEvent will emit a pidwait
signal just like irssi itself would.

=item * Artificial timer delays.

Irssi artificially enforces timers to have at least a 10ms delay (by
croaking, even).

This means that some applications will be limited to a rate of 100Hz (for
example, L<Coro::AnyEvent> thread scheduling).

=item * Irssi leaks memory like hell.

Yeah.

=back

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

      $cb,
      undef;

   bless \\$source, "AnyEvent::Impl::Irssi::io"
}

sub AnyEvent::Impl::Irssi::io::DESTROY {
   Irssi::input_remove $${$_[0]};
}

sub timer {
   my ($class, %arg) = @_;
   
   my $cb    = $arg{cb};
   my $ival  = $arg{interval} * 1000;
   my $after = $arg{after} * 1000;

   my $source; $source = Irssi::timeout_add_once $after > 10 ? $after : 10,
      ($ival ? sub {
                 $source = Irssi::timeout_add $ival > 10 ? $ival : 10, $cb, undef;
                 &$cb;
                 0
               }
             : $cb),
      undef;

   bless \\$source, "AnyEvent::Impl::Irssi::timer"
}

sub AnyEvent::Impl::Irssi::timer::DESTROY {
   Irssi::timeout_remove $${$_[0]};
}

my $_pidwait = sub {
   my ($rpid, $rstatus) = @_;

   AnyEvent::Base->_emit_childstatus ($rpid, $rstatus);
};

Irssi::signal_add pidwait => $_pidwait;

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

While this is not good to performance, at least regarding speed, with a
modern Linux kernel, the overhead is actually quite small.

=item Timing deficiencies

POE manages to not have a function that returns the current time. This is
extremely problematic, as POE can use different time functions, which can
differ by more than a second - and user code is left guessing which one is
used.

In addition, most timer functions in POE want an absolute timestamp, which
is hard to create if all you have is a relative time and no function to
return the "current time".

And of course POE doesn't handle time jumps at all (not even when using
an event loop that happens to do that, such as L<EV>, as it does its own
unoptimised timer management).

AnyEvent works around the unavailability of the current time using
relative timers exclusively, in the hope that POE gets it right at least
internally.

=item Lack of defined event ordering

POE cannot guarantee the order of callback invocation for timers, and
usually gets it wrong. That is, if you have two timers, one timing out
after another (all else being equal), the callbacks might be called in
reverse order.

How one manages to even implement stuff that way escapes me.

=item Child watchers

POE offers child watchers - which is a laudable thing, as few event loops
do. Unfortunately, they cannot even implement AnyEvent's simple child
watchers: they are not generic enough (the POE implementation isn't even

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

all scalars (or even strings) are valid counter names. Take your guess,
failure is of course completely silent. I found this out the hard way, as
the first name I came up with was silently ignored.

   get_next_event_time() returns the time the next event is due, in a form
   compatible with the UNIX time() function.

And surely, one would hope that POE supports sub-second accuracy as
documented elsewhere, unlike the explanation above implies. Yet:

   POE::Kernel timers support subsecond accuracy, but don’t expect too
   much here. Perl is not the right language for realtime programming.

... of course, Perl is not the right language to expect sub-second
accuracy - the manpage author must hate Perl to spread so much FUD in
so little space. The Deliantra game server logs with 100µs-accuracy
because Perl is fast enough to require this, and is still able to deliver
map updates with little jitter at exactly the right time. It does not,
however, use POE.

   Furthermore, since the Kernel keeps track of everything sessions do, it

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

   my $session = POE::Session->create (
      inline_states => {
         _start => sub { $_[KERNEL]->$pee ($fh => "ready") },
         ready  => sub { $cb->() },
         stop   => sub { $_[KERNEL]->$pee ($fh) },
      },
   );
   bless \\$session, "AnyEvent::Impl::POE"
}

sub timer {
   my ($class, %arg) = @_;

   my $after = delete $arg{after};
   my $ival  = delete $arg{interval};
   my $cb    = delete $arg{cb}; my $cb = sub { &$cb }; # POE doesn't like callable objects

   my $session = POE::Session->create (
      inline_states => {
         _start => sub {
            $_[KERNEL]->delay_set (timeout => $after);

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

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

our $VERSION = $AnyEvent::VERSION;

# time() is provided via AnyEvent::Base

*AE::now        = \&AnyEvent::Loop::now;
*AE::now_update = \&AnyEvent::Loop::now_update;
*AE::io         = \&AnyEvent::Loop::io;
*AE::timer      = \&AnyEvent::Loop::timer;
*AE::idle       = \&AnyEvent::Loop::idle;
*_poll          = \&AnyEvent::Loop::one_event;
*loop           = \&AnyEvent::Loop::run; # compatibility with AnyEvent < 6.0
*now_update     = \&AnyEvent::Loop::now_update;

sub now { $AnyEvent::Loop::NOW }

sub AnyEvent::CondVar::Base::_wait {
   AnyEvent::Loop::one_event until exists $_[0]{_ae_sent};
}

sub io {
   my (undef, %arg) = @_;

   AnyEvent::Loop::io $arg{fh}, $arg{poll} eq "w", $arg{cb}
}

sub timer {
   my (undef, %arg) = @_;

   AnyEvent::Loop::timer $arg{after}, $arg{interval}, $arg{cb}
}

sub idle {
   my (undef, %arg) = @_;

   AnyEvent::Loop::idle $arg{cb}
}

=head1 SEE ALSO

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

   this->{cb}->();
   this->setEnabled (1);
}

package AnyEvent::Impl::Qt::Timer;

use Qt;
use Qt::isa qw(Qt::Timer);
use Qt::slots cb => [];

# having to go through these contortions just to get a timer event is
# considered an advantage over other gui toolkits how?

sub NEW {
   my ($class, $after, $interval, $cb) = @_;
   shift->SUPER::NEW ();
   this->{interval} = $interval;
   this->{cb}       = $cb;
   this->connect (this, SIGNAL "timeout()", SLOT "cb()");
   this->start ($after, 1);
}

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


   # work around these bugs in Qt:
   # - adding a callback might destroy other callbacks
   # - only one callback per fd/poll combination
   my ($fh, $qt) = AnyEvent::_dupfh $arg{poll}, $arg{fh},
                      Qt::SocketNotifier::Read (), Qt::SocketNotifier::Write ();

   AnyEvent::Impl::Qt::Io $fh, $qt, $arg{cb}
}

sub timer {
   my ($class, %arg) = @_;
   
   # old Qt treats 0 timeout as "idle"
   AnyEvent::Impl::Qt::Timer
      $arg{after} * 1000 || 1,
      $arg{interval} ? $arg{interval} * 1000 || 1 : undef,
      $arg{cb}
}

# newer Qt have no idle mode for timers anymore...
#sub idle {
#   my ($class, %arg) = @_;
#   
#   AnyEvent::Impl::Qt::Timer 0, 0, $arg{cb}
#}

#sub loop {
#   Qt::app->exec;
#}

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

   # work around another bug: watchers don't get removed when
   # the fh is closed, contrary to documentation. also, trying
   # to unregister a read callback will make it impossible
   # to remove the write callback.
   # if your program segfaults here then you need to destroy
   # your watchers before program exit. sorry, no way around
   # that.
   $mw->fileevent ($fh, $tk => "");
}

sub timer {
   my (undef, %arg) = @_;
   
   my $after = $arg{after} < 0 ? 0 : $arg{after} * 1000;
   my $cb = $arg{cb};
   my $id;

   if ($arg{interval}) {
      my $ival = $arg{interval} * 1000;
      my $rcb = sub {
         $id = Tk::after $mw, $ival, [$_[0], $_[0]];

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

   bless \\$id, "AnyEvent::Impl::Tk::after"
}

sub idle {
   my (undef, %arg) = @_;

   my $cb = $arg{cb};
   my $id;
   my $rcb = sub {
      # in their endless stupidity, they decided to give repeating idle watchers
      # strictly higher priority than timers :/
      $id = Tk::after $mw, 0 => [sub {
         $id = Tk::after $mw, idle => [$_[0], $_[0]];
      }, $_[0]];
      &$cb;
   };

   $id = Tk::after $mw, idle => [$rcb, $rcb];
   bless \\$id, "AnyEvent::Impl::Tk::after"
}

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

   return unless $h->{w};
   my $rc = $h->{stop}($h->{w});
   warnlog $rc if $rc;
   UV::close $h->{w};
}

sub idle {
   my ($class, %arg) = @_;

   AnyEvent::Impl::UV::handle->new (
      UV::timer_init,
      \&UV::idle_start,
      \&UV::idle_stop,
      $arg{cb}
   );
}

sub timer {
   my ($class, %arg) = @_;

   AnyEvent::Impl::UV::handle->new (
      UV::timer_init,
      \&UV::timer_start,
      \&UV::timer_stop,
      $arg{after} * 1000, $arg{interval} * 1000, $arg{cb}
   );
}

sub now { UV::now }

sub _poll {
   UV::run UV::RUN_ONCE;
}

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

=item - write their own event loop (because it guarantees the availability
of an event loop everywhere - even on windows with no extra modules
installed).

=item - choose one specific event loop (because AnyEvent works with most
event loops available for Perl).

=back

If the module author uses L<AnyEvent> for all his (or her) event needs
(IO events, timers, signals, ...) then all other modules can just use
his module and don't have to choose an event loop or adapt to his event
loop. The choice of the event loop is ultimately made by the program
author who uses all the modules and writes the main program. And even
there he doesn't have to choose, he can just let L<AnyEvent> choose the
most efficient event loop available on the system.

Read more about this in the main documentation of the L<AnyEvent> module.


=head1 Introduction to Event-Based Programming

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

on standard input), serial lines, all sorts of other devices, basically
almost everything that has a file descriptor but isn't a file itself. (As
usual, "sane" excludes windows - on that platform you would need different
functions for all of these, complicating code immensely - think "socket
only" on windows).

However, I/O is not everything - the second most important event source is
the clock. For example when doing an HTTP request you might want to time
out when the server doesn't answer within some predefined amount of time.

In AnyEvent, timer event watchers are created by calling the C<<
AnyEvent->timer >> method:

   use AnyEvent;

   my $cv = AnyEvent->condvar;

   my $wait_one_and_a_half_seconds = AnyEvent->timer (
      after => 1.5,  # after how many seconds to invoke the cb?
      cb    => sub { # the callback to invoke
         $cv->send;
      },
   );

   # can do something else here

   # now wait till our time has come
   $cv->recv;

Unlike I/O watchers, timers are only interested in the amount of seconds
they have to wait. When (at least) that amount of time has passed,
AnyEvent will invoke your callback.

Unlike I/O watchers, which will call your callback as many times as there
is data available, timers are normally one-shot: after they have "fired"
once and invoked your callback, they are dead and no longer do anything.

To get a repeating timer, such as a timer firing roughly once per second,
you can specify an C<interval> parameter:

   my $once_per_second = AnyEvent->timer (
      after => 0,    # first invoke ASAP
      interval => 1, # then invoke every second
      cb    => sub { # the callback to invoke
         $cv->send;
      },
   );

=head3 More esoteric sources

AnyEvent also has some other, more esoteric event sources you can tap

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

outstanding events, polled for new events and didn't find any, i.e., when
your process is otherwise idle. They are useful if you want to do some
non-trivial data processing that can be done when your program doesn't
have anything better to do.

All these watcher types are described in detail in the main L<AnyEvent>
manual page.

Sometimes you also need to know what the current time is: C<<
AnyEvent->now >> returns the time the event toolkit uses to schedule
relative timers, and is usually what you want. It is often cached (which
means it can be a bit outdated). In that case, you can use the more costly
C<< AnyEvent->time >> method which will ask your operating system for the
current time, which is slower, but also more up to date.


=head1 Network programming and AnyEvent

So far you have seen how to register event watchers and handle events.

This is a great foundation to write network clients and servers, and might

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

This module expects that only a tiny amount of fds is active at any one
time. This is relatively typical of larger servers (but not the case where
C<select> traditionally is fast), at the expense of the "dense activity
case" where most of the fds are active (which suits C<select>).

The optimal implementation of the "dense" case is not much faster, though,
so the module should behave very well in most cases, subject to the bad
scalability of C<select> in the presence of a large number of inactive
file descriptors.

=item lots of timer changes/iteration, or none at all

This module sorts the timer list using perl's C<sort>, even though a total
ordering is not required for timers internally.

This sorting is expensive, but means sorting can be avoided unless the
timer list has changed in a way that requires a new sort.

This means that adding lots of timers is very efficient, as well as not
changing the timers. Advancing timers (e.g. recreating a timeout watcher
on activity) is also relatively efficient, for example, if you have a
large number of timeout watchers that time out after 10 seconds, then the
timer list will be sorted only once every 10 seconds.

This should not have much of an impact unless you have hundreds or
thousands of timers, though, or your timers have very small timeouts.

=back

=head1 FUNCTIONS

The only user-visible functions provided by this module loop related -
watchers are created via the normal AnyEvent mechanisms.

=over 4

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

# fds[0] is for read, fds[1] is for write watchers
# fds[poll][V] is the bitmask for select
# fds[poll][W][fd] contains a list of i/o watchers
# an I/O watcher is a blessed arrayref containing [fh, poll(0/1), callback, queue-index]
# the queue-index is simply the index in the [W] array, which is only used to improve
# benchmark results in the synthetic "many watchers on one fd" benchmark.
my @fds = ([], []);
sub V() { 0 }
sub W() { 1 }

my $need_sort = 1e300; # when to re-sort timer list
my @timer; # list of [ abs-timeout, Timer::[callback] ]
my @idle;  # list of idle callbacks

# the pure perl mainloop
sub one_event {
   _update_clock;

   # first sort timers if required (slow)
   if ($MNOW >= $need_sort) {
      $need_sort = 1e300;
      @timer = sort { $a->[0] <=> $b->[0] } @timer;
   }

   # handle all pending timers
   if (@timer && $timer[0][0] <= $MNOW) {
      do {
         my $timer = shift @timer;
         $timer->[1] && $timer->[1]($timer);
      } while @timer && $timer[0][0] <= $MNOW;

   } else {
      # poll for I/O events, we do not do this when there
      # were any pending timers to ensure that one_event returns
      # quickly when some timers have been handled
      my ($wait, @vec, $fds)
         = (@timer && $timer[0][0] < $need_sort ? $timer[0][0] : $need_sort) - $MNOW;

      $wait = $wait < MAXWAIT ? $wait + ROUNDUP : MAXWAIT;
      $wait = 0 if @idle;

      $fds = CORE::select
        $vec[0] = $fds[0][V],
        $vec[1] = $fds[1][V],
        AnyEvent::WIN32 ? $vec[2] = $fds[1][V] : undef,
        $wait;

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

               while (/1/g) {
                  # and use the resulting string position as fd
                  $_ && $_->[2]()
                     for @{ $fds->[W][(pos) - 1] || [] };
               }
            }
         }
      } elsif (AnyEvent::WIN32 && $fds && $! == AnyEvent::Util::WSAEINVAL) {
         # buggy microshit windoze asks us to route around it
         CORE::select undef, undef, undef, $wait if $wait;
      } elsif (!@timer || $timer[0][0] > $MNOW && !$fds) {
         $$$_ && $$$_->() for @idle = grep $$$_, @idle;
      }
   }
}

sub run {
   one_event while 1;
}

sub io($$$) {

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

      my $q = $fds->[W][$fd];
      my $last = pop @$q;

      if ($last != $self) {
         weaken ($q->[$self->[3]] = $last);
         $last->[3] = $self->[3];
      }
   }
}

sub timer($$$) {
   my ($after, $interval, $cb) = @_;
   
   my $self;

   if ($interval) {
      $self = [$MNOW + $after , sub {
         $_[0][0] = List::Util::max $_[0][0] + $interval, $MNOW;
         push @timer, $_[0];
         weaken $timer[-1];
         $need_sort = $_[0][0] if $_[0][0] < $need_sort;
         &$cb;
      }];
   } else {
      $self = [$MNOW + $after, $cb];
   }

   push @timer, $self;
   weaken $timer[-1];
   $need_sort = $self->[0] if $self->[0] < $need_sort;

   $self
}

sub idle($) {
   my $cb = shift;

   push @idle, \\$cb;
   weaken ${$idle[-1]};

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

         # socket creation
         socket $state{fh}, $domain, $type, $proto
            or return $state{next}();

         AnyEvent::fh_unblock $state{fh};
         
         my $timeout = $prepare && $prepare->($state{fh});

         $timeout ||= 30 if AnyEvent::WIN32;

         $state{to} = AE::timer $timeout, 0, sub {
            $! = Errno::ETIMEDOUT;
            $state{next}();
         } if $timeout;

         # now connect
         if (
            (connect $state{fh}, $sockaddr)
            || ($! == Errno::EINPROGRESS # POSIX
                || $! == Errno::EWOULDBLOCK
                # WSAEINPROGRESS intentionally not checked - it means something else entirely

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

            if (!ref $_ || $_ != $magic) {
               require AnyEvent::Debug;
               die "callback $cb (" . AnyEvent::Debug::cb2str ($cb) . ") modified \$_ without restoring it.\n";
            }
         }
      };
   }
}

our (@FD_INUSE, $FD_I);
our $FD_CHECK_W = AE::timer 4, 4, sub {
   my $cnt = (@FD_INUSE < 100 * 10 ? int @FD_INUSE * 0.1 : 100) || 10;

   if ($FD_I <= 0) {
      #pop @FD_INUSE while @FD_INUSE && !$FD_INUSE[-1];
      $FD_I = @FD_INUSE
         or return; # empty
   }

   $cnt = $FD_I if $cnt > $FD_I;

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

   bless [
      $fd,
      $class->SUPER::io (@_, cb => $cb)
   ], "AnyEvent::Strict::io";
}

sub AnyEvent::Strict::io::DESTROY {
   --$FD_INUSE[$_[0][0]];
}

sub timer {
   my $class = shift;
   my %arg = @_;

   ref $arg{cb}
      or confess "AnyEvent->timer called with illegal cb argument '$arg{cb}'";
   my $cb = wrap delete $arg{cb};
 
   exists $arg{after}
      or confess "AnyEvent->timer called without mandatory 'after' parameter";
   delete $arg{after};
 
   !$arg{interval} or $arg{interval} > 0
      or confess "AnyEvent->timer called with illegal interval argument '$arg{interval}'";
   delete $arg{interval};
 
   confess "AnyEvent->timer called with unsupported parameter(s) " . join ", ", keys %arg
      if keys %arg;

   $class->SUPER::timer (@_, cb => $cb)
}

sub signal {
   my $class = shift;
   my %arg = @_;

   ref $arg{cb}
      or confess "AnyEvent->signal called with illegal cb argument '$arg{cb}'";
   my $cb = wrap delete $arg{cb};
 

t/01_basic.t  view on Meta::CPAN

BEGIN { require AnyEvent::Impl::Perl unless $ENV{PERL_ANYEVENT_MODEL} }

$| = 1; print "1..6\n";

print "ok 1\n";

my $cv = AnyEvent->condvar;

print "ok 2\n";

my $timer1 = AnyEvent->timer (after => 0.1, cb => sub { print "ok 5\n"; $cv->broadcast });

print "ok 3\n";

AnyEvent->timer (after => 0.01, cb => sub { print "not ok 5\n" });

print "ok 4\n";

$cv->wait;

print "ok 6\n";

t/02_signals.t  view on Meta::CPAN


use AnyEvent;
BEGIN { require AnyEvent::Impl::Perl unless $ENV{PERL_ANYEVENT_MODEL} }

$| = 1; print "1..5\n";

print "ok 1\n";

my $cv = AnyEvent->condvar;

my $error = AnyEvent->timer (after => 5, cb => sub {
   print <<EOF;
Bail out! No signal caught.
EOF
   exit 0;
});

my $sw = AnyEvent->signal (signal => 'INT', cb => sub {
  print "ok 3\n";
  $cv->broadcast;
});

t/03_child.t  view on Meta::CPAN

for my $it ("", 1, 2, 3, 4) {
   print "ok ${it}1\n";

   AnyEvent::detect; # force-load event model

   my $pid = fork;

   defined $pid or die "unable to fork";

   # work around Tk bug until it has been fixed.
   #my $timer = AnyEvent->timer (after => 2, cb => sub { });

   my $cv = AnyEvent->condvar;

   unless ($pid) {
      print "ok ${it}2 # child $$\n";

      # POE hits a race condition when the child dies too quickly
      # because it checks for child exit before installing the signal handler.
      # seen in version 1.352 - earlier versions had the same bug, but
      # polled for child exits regularly, so only caused a delay.

t/03_child.t  view on Meta::CPAN


   # Glib is the only model that doesn't support pid == 0
   my $pid0 = $AnyEvent::MODEL eq "AnyEvent::Impl::Glib" ? $pid2 : 0;

   my $w2 = AnyEvent->child (pid => $pid0, cb => sub {
      print $pid2 == $_[0] ? "" : "not ", "ok ${it}5 # $pid2 == $_[0]\n";
      print 7 == ($_[1] >> 8) ? "" : "not ", "ok ${it}6 # 7 == $_[1] >> 8 ($_[1])\n";
      $cv2->broadcast;
   });

   my $error = AnyEvent->timer (after => 5, cb => sub {
      print <<EOF;
Bail out! No child exit detected. This is either a bug in AnyEvent or a bug in your Perl (mostly some windows distributions suffer from that): child watchers might not work properly on this platform. You can force installation of this module if you d...
EOF
      exit 0;
   });

   $cv2->recv;

   print "ok ${it}7\n";
   print "ok ${it}8\n";



( run in 2.468 seconds using v1.01-cache-2.11-cpan-49f99fa48dc )