AnyEvent

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

TODO: document TCP_*** constants
TODO: add debug/trace logging to some modules
TODO: use the eval-with-cb-call trick also to speed up JSON?
TODO: FAQ: common pitfalls? invoke-before-return
TODO: FAQ: scope-ids? hosts file order?
TODO: AnyEvent::Handle with AnyEvent::IO?
TODO: invalid. and localhost. specialcasing inside AEDNS and not AESocket (rfc6761)
TODO: maybe implement env variable to give hosts precedence
TODO: more formats for parse_ipv6 (single ipv6 address without port, ...p80, ...#80)
TODO: inet_aton maybe pack C4? no, add a comment why not
TODO: socket prepare callbacks, can they easily signal failure as well?
TODO: Олег Г <verdrehung@gmail.com>, empty A record response causes
AnyEvent::resolve_sockaddr to eventually call pack_sockaddr with undef -
broken dns server, but maybe improve the response.

7.17 Wed Sep 18 03:04:49 CEST 2019
	- work around antique openssl version in RHEL 7  by formatting
          dh parameters differently (reported by several people).
	- add t/13_weaken.t.

7.16 Fri Jul 19 18:00:21 CEST 2019

Changes  view on Meta::CPAN

          by Maxime Soulé).
        - log a (single) notice message if SNI is not supported.
        - upgrade to UTS-46:9.0.0 draft and switch to non-transitional
          behaviour, beating thunderbird, ie, edge, chrome and safari to it :)
          (see also https://bugzilla.mozilla.org/show_bug.cgi?id=1218179)
        - turns out the UTS-46 IDNA testcase failures were indeed bugs in the
          testcases and the specification and not in the code - the post-9.0.0
          unicode files have all known problems fixed, so finally the AnyEvent
          IDNA implementation can pass the full IDNA testsuite - without needing
          a single fix :)
        - guarantee (and document) that condvar callbacks will be removed
          on invocation - important to avoid circular references.

7.12 Wed Jan 27 19:12:26 CET 2016
	- use common name as hostname for tls connects, if Net::SSLeay
          supports SNI.
        - fix documentation of tls_autostart read type in AnyEvent::Handle,
          analyzed by Felix Ostmann.

7.11 Thu Jul 16 14:36:00 CEST 2015
	- AnyEvent::Socket::parse_ipv6 could accept malformed ipv6

Changes  view on Meta::CPAN

5.01 Mon Aug 10 03:16:32 CEST 2009
	- last release broke EV child watchers :/.

5.0  Sun Aug  9 17:32:09 CEST 2009
	- officially introduce and document the AE API.
        - lowering the timeout at runtime did not have immediate effect
          in AnyEvent::Handle.
        - AE::Handle now has separate and independent read and write timeout
          settings.
        - probe for Guard module when AnyEvent::Util is loaded, not at
          runtime (Event doesn't like eval "use" from callbacks, and it avoids
          exporting the probe function).
        - Impl::IOAsync's io watchers did not use the filehandle emulation
          code to work around it's watcher limits.
        - work around IO::Async's problems with overloaded objects.
        - try to disable wearnings inside IO::Async, it's just too buggy.
        - do no longer use Event by default, only EV or Perl, Event is too buggy.
	- hackishly provide fast AE:: interface when EV or Perl is the backend.
        - inherit VERSION from AnyEvent::VERSION in most modules.

4.91 Thu Aug  6 15:42:45 CEST 2009

Changes  view on Meta::CPAN


4.83 Fri Jul 17 16:56:26 CEST 2009
	- implement AnyEvent::Socket::getprotobyname.
	- AnyEvent::CondVar's will now detect recursive blocking
          waits and will croak, as too many people fall into
          this trap.
        - AnyEvent::Handle will now call ->destroy on itself after
          executing the on_error callback, instead of doing some
          half-baked internal shutdown, for fatal errors.
        - clarify on_eof behaviour w.r.t. the read queue and
          on_read callbacks.
	- ignore some possible spurious wake-ups in tcp_connect.

4.82 Sat Jul 11 00:34:55 CEST 2009
	- POE and Event backends didn't accept some callable objects as 
          callbacks.
	- use Config module instead of POSIX module to detect signal names
          in AnyEvent::Strict and AnyEvent::Impl::EventLib, as the POSIX
          module doesn't even have all POSIX signals :/.
        - use more workarounds around the many refcnt/corruption bugs in
          Event::Lib.
        - work around a race condition in perl's select, causing t/03_child.t
          to rarely fail.

4.81 Thu Jul  9 10:30:30 CEST 2009
        - AnyEvent::Handle didn't properly diagnose write errors

Changes  view on Meta::CPAN

          secure default configuration, lots of documentation and,
          predefined diffie-hellman keys for perfect forward security
          and much more. get it while it's still fresh!
        - use AnyEvent::TLS in AnyEvent::Handle for context management.
	- load AnyEvent::Handle only on demand in AnyEvent::DNS,
          so AnyEvent::Socket users have smaller memory footprint
          in the common case.
        - add AnyEvent::Handle->push_shutdown method.
        - add an additional error message parameter to AnyEvent::Handle's
          on_error callback (for TLS, $! is still available).
        - add AnyEvent::Handle on_starttls/on_stoptls callbacks.
        - make AnyEvent::Handle more robust against early connection
          failures (during new), and return C<undef> in that case
          from the constructor.
        - AnyEvent::Handle will now try to load only JSON::XS first,
          then fall back to JSON.
        - format_ipv4/format_ipv6 are now exported by default, for symmetry,
          and because it was documented that way.

4.451 Fri Jul  3 00:28:58 CEST 2009
	- do not clear rbuf when shutting down an AnyEvent::Handle

Changes  view on Meta::CPAN

        - run even without Time::HiRes in some cases now, but do not
          provide sub-second accuracy (all *supported* perl versions have
          Time::HiRes).

4.233 Fri Aug 22 01:48:05 CEST 2008
	- fix a bug in the testsuite, causing a hang.
        - clarified lots of AnyEvent::Handle constructor arguments.

4.232 Thu Aug 21 20:44:25 CEST 2008
	- fix a bug in AnyEvent::Handle that could cause two fatal error
          callbacks on EOF, which caused AnyEvent::HTTP to signal success twice
          (testcase by Leon Brocard).
        - clarified on_eof/on_error documentation a bit.

4.231 Tue Jul 29 13:12:15 CEST 2008
        - remove some debugging code left in AnyEvent::Util::fork_call
          (and no, it's impossible to implement with the broken windows
          perls without resource leaks or worse).

4.23 Tue Jul 29 12:19:59 CEST 2008
	- document the first parameter passed to condvar callbacks to be
          the callback.
        - add AnyEvent::Socket::{ntoa,aton} aliases.
        - optimize the AE::Handle->push_read (line) for the default
          eol marker.
        - optimize push_read (packstring|storable) for small packets.
        - invoke on_error callback when no on_eof callback is set.
        - fix a bug in push_read (storable) of unknown impact.

4.22 Sun Jul 20 16:34:13 CEST 2008
	- new function AnyEvent::Socket::parse_hostport.

Changes  view on Meta::CPAN

        - support Wx and Prima through POE.
        - optimise perl backend to use 20% less memory and take advantage
          of typical timeout behaviour. It can now compete with
          select/poll-based C event loops in most cases (it is usually
          faster than Event and Glib :).
        - roughly cut EV memory use in half and increase its speed by 30%,
          by removing undocumented functionality. Did something similar
          to other event loops where possible.

3.2  Thu Apr 24 10:10:40 CEST 2008
	- do not die when anyevent watchers are destroyed while running callbacks
          in the pureperl backend (could only happen when two watchers are registered
          for the same fh/poll combo).
        - support autoloading for child watchers, was broken in all versions.
	- implement PERL_ANYEVENT_MODEL env variable.
        - (experimental) implement interface to the (very crashy/buggy) Event::Lib module.
        - (experimental) implement interface to the Qt module (cannot be autoprobed).
        - this release is IO:AnyEvent-proof.

3.12 Tue Apr 22 07:11:46 CEST 2008
	- reinstate AUTHOR section that got lost somehow.

Changes  view on Meta::CPAN

        - moved default condvar implementation into base module, simplifying
          most implementation modules.

2.1  Fri Nov 24 15:50:48 CET 2006
	- better docs.
        - simple testsuite.
        - added AnyEvent->one_event method for special purposes.

2.0  Wed Nov  1 02:21:30 CET 2006
	- INCOMPATIBLE CHANGE: poll can now either be "r" or "w" but not both.
	- INCOMPATIBLE CHANGE: io watcher callbacks have no arguments anymore.
        - 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

README  view on Meta::CPAN

WATCHERS
    AnyEvent has the central concept of a *watcher*, which is an object that
    stores relevant data for each kind of event you are waiting for, such as
    the callback to call, the file handle to watch, etc.

    These watchers are normal Perl objects with normal Perl lifetime. After
    creating a watcher it will immediately "watch" for events and invoke the
    callback when the event occurs (of course, only when the event model is
    in control).

    Note that callbacks must not permanently change global variables
    potentially in use by the event loop (such as $_ or $[) and that
    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

README  view on Meta::CPAN

    most character devices, pipes, fifos and so on, but not for example
    files or block devices.

    "poll" must be a string that is either "r" or "w", which creates a
    watcher waiting for "r"eadable or "w"ritable events, respectively.

    "cb" is the callback to invoke each time the file handle becomes ready.

    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 I/O watcher callbacks.

    The I/O watcher might use the underlying file descriptor or a copy of
    it. You must not close a file handle as long as any watcher is active on
    the underlying file descriptor.

    Some event loops issue spurious readiness notifications, so you should
    always use non-blocking calls when reading/writing from/to your file
    handles.

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

README  view on Meta::CPAN


    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.

README  view on Meta::CPAN

        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

README  view on Meta::CPAN


  SIGNAL WATCHERS
       $w = AnyEvent->signal (signal => <uppercase_signal_name>, cb => <callback>);

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

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

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

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

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

    Example: exit on SIGINT

README  view on Meta::CPAN

    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
    - see the "ENVIRONMENT VARIABLES" section for details.

    All these problems can be avoided by installing the optional
    Async::Interrupt module, which works with most event loops. It will not
    work with inherently broken event loops such as Event or Event::Lib (and

README  view on Meta::CPAN

       });

  CONDITION VARIABLES
       $cv = AnyEvent->condvar;

       $cv->send (<list>);
       my @res = $cv->recv;

    If you are familiar with some event loops you will know that all of them
    require you to run some blocking "loop", "run" or similar function that
    will actively watch for new events and call your callbacks.

    AnyEvent is slightly different: it expects somebody else to run the
    event loop and will only block when necessary (usually when told by the
    user).

    The tool to do that is called a "condition variable", so called because
    they represent a condition that must become true.

    Now is probably a good time to look at the examples further below.

README  view on Meta::CPAN


    After creation, the condition variable is "false" until it becomes
    "true" by calling the "send" method (or calling the condition variable
    as if it were a callback, read about the caveats in the description for
    the "->send" method).

    Since condition variables are the most complex part of the AnyEvent API,
    here are some different mental models of what they are - pick the ones
    you can connect to:

    *   Condition variables are like callbacks - you can call them (and pass
        them instead of callbacks). Unlike callbacks however, you can also
        wait for them to be called.

    *   Condition variables are signals - one side can emit or send them,
        the other side can wait for them, or install a handler that is
        called when the signal fires.

    *   Condition variables are like "Merge Points" - points in your program
        where you merge multiple independent results/control flows into one.

    *   Condition variables represent a transaction - functions that start

README  view on Meta::CPAN


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

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

    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.

README  view on Meta::CPAN

       $timer_fired->recv;

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

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

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

       use AnyEvent::CouchDB;

       ...

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

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

README  view on Meta::CPAN

        not need to do anything special to take advantage of that: any code
        that would normally block your program because it calls "recv", be
        executed in an "async" thread instead without blocking other
        threads.

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

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

    $bool = $cv->ready
        Returns true when the condition is "true", i.e. whether "send" or

lib/AnyEvent.pm  view on Meta::CPAN


AnyEvent has the central concept of a I<watcher>, which is an object that
stores relevant data for each kind of event you are waiting for, such as
the callback to call, the file handle to watch, etc.

These watchers are normal Perl objects with normal Perl lifetime. After
creating a watcher it will immediately "watch" for events and invoke the
callback when the event occurs (of course, only when the event model
is in control).

Note that B<callbacks must not permanently change global variables>
potentially in use by the event loop (such as C<$_> or C<$[>) and that B<<
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

lib/AnyEvent.pm  view on Meta::CPAN

most character devices, pipes, fifos and so on, but not for example files
or block devices.

C<poll> must be a string that is either C<r> or C<w>, which creates a
watcher waiting for "r"eadable or "w"ritable events, respectively.

C<cb> is the callback to invoke each time the file handle becomes ready.

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 I/O watcher callbacks.

The I/O watcher might use the underlying file descriptor or a copy of it.
You must not close a file handle as long as any watcher is active on the
underlying file descriptor.

Some event loops issue spurious readiness notifications, so you should
always use non-blocking calls when reading/writing from/to your file
handles.

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

lib/AnyEvent.pm  view on Meta::CPAN


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.

lib/AnyEvent.pm  view on Meta::CPAN

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.

lib/AnyEvent.pm  view on Meta::CPAN

=head2 SIGNAL WATCHERS

   $w = AnyEvent->signal (signal => <uppercase_signal_name>, cb => <callback>);

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

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

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

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

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

Example: exit on SIGINT

lib/AnyEvent.pm  view on Meta::CPAN


=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
be overriden via C<$ENV{PERL_ANYEVENT_MAX_SIGNAL_LATENCY}> or
C<$AnyEvent::MAX_SIGNAL_LATENCY> - see the L<ENVIRONMENT VARIABLES>
section for details.

All these problems can be avoided by installing the optional
L<Async::Interrupt> module, which works with most event loops. It will not

lib/AnyEvent.pm  view on Meta::CPAN


=head2 CONDITION VARIABLES

   $cv = AnyEvent->condvar;

   $cv->send (<list>);
   my @res = $cv->recv;

If you are familiar with some event loops you will know that all of them
require you to run some blocking "loop", "run" or similar function that
will actively watch for new events and call your callbacks.

AnyEvent is slightly different: it expects somebody else to run the event
loop and will only block when necessary (usually when told by the user).

The tool to do that is called a "condition variable", so called because
they represent a condition that must become true.

Now is probably a good time to look at the examples further below.

Condition variables can be created by calling the C<< AnyEvent->condvar

lib/AnyEvent.pm  view on Meta::CPAN

After creation, the condition variable is "false" until it becomes "true"
by calling the C<send> method (or calling the condition variable as if it
were a callback, read about the caveats in the description for the C<<
->send >> method).

Since condition variables are the most complex part of the AnyEvent API, here are
some different mental models of what they are - pick the ones you can connect to:

=over 4

=item * Condition variables are like callbacks - you can call them (and pass them instead
of callbacks). Unlike callbacks however, you can also wait for them to be called.

=item * Condition variables are signals - one side can emit or send them,
the other side can wait for them, or install a handler that is called when
the signal fires.

=item * Condition variables are like "Merge Points" - points in your program
where you merge multiple independent results/control flows into one.

=item * Condition variables represent a transaction - functions that start
some kind of transaction can return them, leaving the caller the choice

lib/AnyEvent.pm  view on Meta::CPAN

called or can synchronously C<< ->recv >> for the results.

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

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

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

lib/AnyEvent.pm  view on Meta::CPAN

   $timer_fired->recv;

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

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

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

   use AnyEvent::CouchDB;

   ...

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

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

lib/AnyEvent.pm  view on Meta::CPAN

automatically when L<Coro> is used with L<AnyEvent>, so code does not need
to do anything special to take advantage of that: any code that would
normally block your program because it calls C<recv>, be executed in an
C<async> thread instead without blocking other threads.

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

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

=item $bool = $cv->ready

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

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

            if length > $Carp::MaxArgLen;
         return $_;
      }
   }
}

=item AnyEvent::Debug::backtrace [$skip]

Creates a backtrace (actually an AnyEvent::Debug::Backtrace object
that you can stringify), not unlike the Carp module would. Unlike the
Carp module it resolves some references (such as callbacks) to more
user-friendly strings, has a more succinct output format and most
importantly: doesn't leak memory like hell.

The reason it creates an object is to save time, as formatting can be
done at a later time. Still, creating a backtrace is a relatively slow
operation.

=cut

sub backtrace(;$) {

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

   EV::loop;

=head2 Why is my C<tcp_connect> callback never called?

Tricky: C<tcp_connect> (and a few other functions in L<AnyEvent::Socket>)
is critically sensitive to the caller context.

In void context, it will just do its thing and eventually call the
callback. In any other context, however, it will return a special "guard"
object - when it is destroyed (e.g. when you don't store it but throw it
away), tcp_connect will no longer try to connect or call any callbacks.

Often this happens when the C<tcp_connect> call is at the end of a function:

   sub do_connect {
      tcp_connect "www.example.com", 80, sub {
         ... lengthy code
      };
   }

Then the caller decides whether there is a void context or not. One can

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

on the other side will then look at the queue.

AnyEvent to GUI communications can also use a L<Thread::Queue>, but to
wake up the GUI thread, it would instead use C<< Win32::GUI::PostMessage
$WINDOW, 1030, 0, "" >>, and the GUI thread would listen for these
messages by using C<< $WINDOW->Hook (1030 (), sub { ... }) >>.

=head2 My callback dies and...

It must not - part of the contract betwene AnyEvent and user code is that
callbacks do not throw exceptions (and don't do even more evil things,
such as using C<last> outside a loop :). If your callback might die
sometimes, you need to use C<eval>.

If you want to track down such a case and you can reproduce it, you can
enable wrapping (by calling C<< L<AnyEvent::Debug>::wrap >> or by setting
C<PERL_ANYEVENT_DEBUG_WRAP=1> before starting your program). This will
wrap every callback into an eval and will report any exception complete
with a backtrace and some information about which watcher died, where it
was created and so on.

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

The L<AnyEvent::Intro> tutorial contains some well-documented
AnyEvent::Handle examples.

In the following, where the documentation refers to "bytes", it means
characters. As sysread and syswrite are used for all I/O, their
treatment of characters applies to this module as well.

At the very minimum, you should specify C<fh> or C<connect>, and the
C<on_error> callback.

All callbacks will be invoked with the handle object as their first
argument.

=cut

package AnyEvent::Handle;

use Scalar::Util ();
use List::Util ();
use Carp ();
use Errno qw(EAGAIN EWOULDBLOCK EINTR);

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

Try to connect to the specified host and service (port), using
C<AnyEvent::Socket::tcp_connect>. The C<$host> additionally becomes the
default C<peername>.

You have to specify either this parameter, or C<fh>, above.

It is possible to push requests on the read and write queues, and modify
properties of the stream, even while AnyEvent::Handle is connecting.

When this parameter is specified, then the C<on_prepare>,
C<on_connect_error> and C<on_connect> callbacks will be called under the
appropriate circumstances:

=over 4

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

This (rarely used) callback is called before a new connection is
attempted, but after the file handle has been created (you can access that
file handle via C<< $handle->{fh} >>). It could be used to prepare the
file handle with parameters required for the actual connect (as opposed to

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

system error code (or C<ENOSPC>, C<EPIPE>, C<ETIMEDOUT>, C<EBADMSG> or
C<EPROTO>).

While not mandatory, it is I<highly> recommended to set this callback, as
you will not be notified of errors otherwise. The default just calls
C<croak>.

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

This sets the default read callback, which is called when data arrives
and no read request is in the queue (unlike read queue callbacks, this
callback will only be called when at least one octet of data is in the
read buffer).

To access (and remove data from) the read buffer, use the C<< ->rbuf >>
method or access the C<< $handle->{rbuf} >> member directly. Note that you
must not enlarge or modify the read buffer, you can only remove data at
the beginning from it.

You can also call C<< ->push_read (...) >> or any other function that
modifies the read queue. Or do both. Or ...

When an EOF condition is detected, AnyEvent::Handle will first try to
feed all the remaining data to the queued callbacks and C<on_read> before
calling the C<on_eof> callback. If no progress can be made, then a fatal
error will be raised (with C<$!> set to C<EPIPE>).

Note that, unlike requests in the read queue, an C<on_read> callback
doesn't mean you I<require> some data: if there is an EOF and there
are outstanding read requests then an error will be flagged. With an
C<on_read> callback, the C<on_eof> callback will be invoked.

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

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


If non-zero, then these enables an "inactivity" timeout: whenever this
many seconds pass without a successful read or write on the underlying
file handle (or a call to C<timeout_reset>), the C<on_timeout> callback
will be invoked (and if that one is missing, a non-fatal C<ETIMEDOUT>
error will be raised).

There are three variants of the timeouts that work independently of each
other, for both read and write (triggered when nothing was read I<OR>
written), just read (triggered when nothing was read), and just write:
C<timeout>, C<rtimeout> and C<wtimeout>, with corresponding callbacks
C<on_timeout>, C<on_rtimeout> and C<on_wtimeout>, and reset functions
C<timeout_reset>, C<rtimeout_reset>, and C<wtimeout_reset>.

Note that timeout processing is active even when you do not have any
outstanding read or write requests: If you plan to keep the connection
idle then you should disable the timeout temporarily or ignore the
timeout in the corresponding C<on_timeout> callback, in which case
AnyEvent::Handle will simply restart the timeout.

Zero (the default) disables the corresponding timeout.

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

When data could be written and the write buffer is shorter then the low
water mark, the C<on_drain> callback will be invoked once.

=over 4

=item $handle->on_drain ($cb)

Sets the C<on_drain> callback or clears it (see the description of
C<on_drain> in the constructor).

This method may invoke callbacks (and therefore the handle might be
destroyed after it returns).

=cut

sub on_drain {
   my ($self, $cb) = @_;

   $self->{on_drain} = $cb;

   $cb->($self)
      if $cb && $self->{low_water_mark} >= (length $self->{wbuf}) + (length $self->{_tls_wbuf});
}

=item $handle->push_write ($data)

Queues the given scalar to be written. You can push as much data as
you want (only limited by the available memory and C<wbuf_max>), as
C<AnyEvent::Handle> buffers it independently of the kernel.

This method may invoke callbacks (and therefore the handle might be
destroyed after it returns).

=cut

sub _drain_wbuf {
   my ($self) = @_;

   if (!$self->{_ww} && length $self->{wbuf}) {

      Scalar::Util::weaken $self;

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

replaces the C<on_drain> callback with:

   sub { shutdown $_[0]{fh}, 1 }

This simply shuts down the write side and signals an EOF condition to the
the peer.

You can rely on the normal read queue and C<on_eof> handling
afterwards. This is the cleanest way to close a connection.

This method may invoke callbacks (and therefore the handle might be
destroyed after it returns).

=cut

sub push_shutdown {
   my ($self) = @_;

   delete $self->{low_water_mark};
   $self->on_drain (sub { shutdown $_[0]{fh}, 1 });
}

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

ways, the "simple" way, using only C<on_read> and the "complex" way, using
a queue.

In the simple case, you just install an C<on_read> callback and whenever
new data arrives, it will be called. You can then remove some data (if
enough is there) from the read buffer (C<< $handle->rbuf >>). Or you can
leave the data there if you want to accumulate more (e.g. when only a
partial message has been received so far), or change the read queue with
e.g. C<push_read>.

In the more complex case, you want to queue multiple callbacks. In this
case, AnyEvent::Handle will call the first queued callback each time new
data arrives (also the first time it is queued) and remove it when it has
done its job (see C<push_read>, below).

This way you can, for example, push three line-reads, followed by reading
a chunk of data, and AnyEvent::Handle will execute them in order.

Example 1: EPP protocol parser. EPP sends 4 byte length info, followed by
the specified number of bytes which give an XML datagram.

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

            my $xml = $_[1];
            # handle xml
         });
      });
   });

Example 2: Implement a client for a protocol that replies either with "OK"
and another line or "ERROR" for the first request that is sent, and 64
bytes for the second request. Due to the availability of a queue, we can
just pipeline sending both requests and manipulate the queue as necessary
in the callbacks.

When the first callback is called and sees an "OK" response, it will
C<unshift> another line-read. This line-read will be queued I<before> the
64-byte chunk callback.

   # request one, returns either "OK + extra line" or "ERROR"
   $handle->push_write ("request 1\015\012");

   # we expect "ERROR" or "OK" as response, so push a line read
   $handle->push_read (line => sub {

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

         if $self->{on_read} || @{ $self->{_queue} };
   }
}

=item $handle->on_read ($cb)

This replaces the currently set C<on_read> callback, or clears it (when
the new callback is C<undef>). See the description of C<on_read> in the
constructor.

This method may invoke callbacks (and therefore the handle might be
destroyed after it returns).

=cut

sub on_read {
   my ($self, $cb) = @_;

   $self->{on_read} = $cb;
   $self->_drain_rbuf if $cb;
}

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

It must check whether enough data is in the read buffer already.

If not enough data is available, it must return the empty list or a false
value, in which case it will be called repeatedly until enough data is
available (or an error condition is detected).

If enough data was available, then the callback must remove all data it is
interested in (which can be none at all) and return a true value. After returning
true, it will be removed from the queue.

These methods may invoke callbacks (and therefore the handle might be
destroyed after it returns).

=cut

our %RH;

sub register_read_type($$) {
   $RH{$_[0]} = $_[1];
}

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


Whenever this type is used, C<push_read> will invoke the function with the
handle object, the original callback and the remaining arguments.

The function is supposed to return a callback (usually a closure) that
works as a plain read callback (see C<< ->push_read ($cb) >>), so you can
mentally treat the function as a "configurable read type to read callback"
converter.

It should invoke the original callback when it is done reading (remember
to pass C<$handle> as first argument as all other callbacks do that,
although there is no strict requirement on this).

For examples, see the source of this module (F<perldoc -m
AnyEvent::Handle>, search for C<register_read_type>)).

=item $handle->stop_read

=item $handle->start_read

In rare cases you actually do not want to read anything from the
socket. In this case you can call C<stop_read>. Neither C<on_read> nor
any queued callbacks will be executed then. To start reading again, call
C<start_read>.

Note that AnyEvent::Handle will automatically C<start_read> for you when
you change the C<on_read> callback or push/unshift a read callback, and it
will automatically C<stop_read> for you when neither C<on_read> is set nor
there are any read requests in the queue.

In older versions of this module (<= 5.3), these methods had no effect,
as TLS does not support half-duplex connections. In current versions they
work as expected, as this behaviour is required to avoid certain resource

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


The TLS connection object will end up in C<< $handle->{tls} >>, the TLS
context in C<< $handle->{tls_ctx} >> after this call and can be used or
changed to your liking. Note that the handshake might have already started
when this function returns.

Due to bugs in OpenSSL, it might or might not be possible to do multiple
handshakes on the same stream. It is best to not attempt to use the
stream after stopping TLS.

This method may invoke callbacks (and therefore the handle might be
destroyed after it returns).

=cut

our %TLS_CACHE; #TODO not yet documented, should we?

sub starttls {
   my ($self, $tls, $ctx) = @_;

   Carp::croak "It is an error to call starttls on an AnyEvent::Handle object while TLS is already active, caught"

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

   $self->start_read; # make sure we actually do read
}

=item $handle->stoptls

Shuts down the SSL connection - this makes a proper EOF handshake by
sending a close notify to the other side, but since OpenSSL doesn't
support non-blocking shut downs, it is not guaranteed that you can re-use
the stream afterwards.

This method may invoke callbacks (and therefore the handle might be
destroyed after it returns).

=cut

sub stoptls {
   my ($self) = @_;

   if ($self->{tls} && $self->{fh}) {
      Net::SSLeay::shutdown ($self->{tls});

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

      };
      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
destroying it in this way will be silently ignored (and it will return the
empty list).

Normally, you can just "forget" any references to an AnyEvent::Handle
object and it will simply shut down. This works in fatal error and EOF
callbacks, as well as code outside. It does I<NOT> work in a read or write
callback, so when you want to destroy the AnyEvent::Handle object from
within such an callback. You I<MUST> call C<< ->destroy >> explicitly in
that case.

Destroying the handle object in this way has the advantage that callbacks
will be removed as well, so if those are the only reference holders (as
is common), then one doesn't need to do anything special to break any
reference cycles.

The handle might still linger in the background and write out remaining
data, as specified by the C<linger> option, however.

=cut

sub destroy {

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

   #nop
}

=item $handle->destroyed

Returns false as long as the handle hasn't been destroyed by a call to C<<
->destroy >>, true otherwise.

Can be useful to decide whether the handle is still valid after some
callback possibly destroyed the handle. For example, C<< ->push_write >>,
C<< ->starttls >> and other methods can call user callbacks, which in turn
can destroy the handle, so work can be avoided by checking sometimes:

   $hdl->starttls ("accept");
   return if $hdl->destroyed;
   $hdl->push_write (...

Note that the call to C<push_write> will silently be ignored if the handle
has been destroyed, so often you can just ignore the possibility of the
handle being destroyed.

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



=head1 NONFREQUENTLY ASKED QUESTIONS

=over 4

=item I C<undef> the AnyEvent::Handle reference inside my callback and
still get further invocations!

That's because AnyEvent::Handle keeps a reference to itself when handling
read or write callbacks.

It is only safe to "forget" the reference inside EOF or error callbacks,
from within all other callbacks, you need to explicitly call the C<<
->destroy >> method.

=item Why is my C<on_eof> callback never called?

Probably because your C<on_error> callback is being called instead: When
you have outstanding requests in your read queue, then an EOF is
considered an error as you clearly expected some data.

To avoid this, make sure you have an empty read queue whenever your handle
is supposed to be "idle" (i.e. connection closes are O.K.). You can set

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


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

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

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

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

=cut

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

Note: the AnyEvent author has not found recent releases of Event::Lib to
be even remotely working (not even the examples from the manpage or the
testsuite work), so this event backend should be avoided (or somebody
should step up and maintain it, hint, hint).

The L<Event::Lib> module suffers from the same limitations and bugs as
libevent, most notably it kills already-installed watchers on a file
descriptor and it is unable to support fork. These are not fatal issues,
and are worked-around by this module, but the L<Event::Lib> perl module
itself has many additional bugs such as taking references to file handles
and callbacks instead of making a copy or freeing still-allocated scalars,
causing memory corruption and random crashes. Only Tk rivals it in its
brokenness.

This adaptor module employs the same workaround around the watcher
problems as Tk and should therefore be avoided. (This was done for
simplicity, one could in theory work around the problems with lower
overhead by managing our own watchers).

Event::Lib also leaks file handles and memory and tends to just exit on
problems.

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

=cut

package AnyEvent::Impl::EventLib;

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

use Event::Lib;

# Event::Lib doesn't always take a reference to the callback, so closures
# cause memory corruption and segfaults. it also has an issue actually
# calling callbacks, so this exists as workaround.
sub ccb {
   # Event:Lib accesses $_[0] after the callback, when it might be freed,
   # so we keep it referenced until after the callback. This still accesses
   # a freed scalar, but at least it'll not crash.
   my $keep_it = $_[0];

   $_[2]();
}

my $ccb = \&ccb;

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

   # work around these bugs in Event::Lib:
   # - adding a callback might destroy other callbacks
   # - 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__
}

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

place in a correct program (this is not a singular case though).

AnyEvent consequently patches the POE kernel so it thinks it already
ran. Other workarounds, even the one cited in the POE documentation
itself, have serious side effects, such as throwing away events.

The author of POE verified that this is indeed true, and has no plans to
change this.

POE has other weird messages, and sometimes weird behaviour, for example,
it doesn't support overloaded code references as callbacks for no apparent
reason.

=item One POE session per Event

AnyEvent has to create one POE::Session per event watcher, which is
immensely slow and makes watchers very large. The reason for this is
lacking lifetime management (mostly undocumented, too). Without one
session/watcher it is not possible to easily keep the kernel from running
endlessly.

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

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
generic enough to let properly designed back-end use their native child

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


use AnyEvent::Impl::Qt::Timer;
use AnyEvent::Impl::Qt::Io;

our $app = Qt::Application \@ARGV; # REQUIRED!

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

   # 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) = @_;
   

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


our $mw = new MainWindow -title => "AnyEvent Dummy Window";
$mw->withdraw;

END { undef $mw }

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

   # work around these bugs in Tk:
   # - removing a callback will destroy other callbacks
   # - removing a callback might crash
   # - adding a callback might destroy other callbacks
   # - only one callback per fh
   # - only one callback per fh/poll combination
   my ($fh, $tk) = AnyEvent::_dupfh $arg{poll}, $arg{fh}, "readable", "writable";

   $mw->fileevent ($fh, $tk => $arg{cb});

   bless [$fh, $tk], "AnyEvent::Impl::Tk::io"
}

sub AnyEvent::Impl::Tk::io::DESTROY {

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

>> called a "watcher" object - thus named because it "watches" your
file handle (or other event sources) for the event you are interested in.

In the example above, we create an I/O watcher by calling the C<<
AnyEvent->io >> method. A lack of further interest in some event is
expressed by simply forgetting about its watcher, for example by
C<undef>-ing the only variable it is stored in. AnyEvent will
automatically clean up the watcher if it is no longer used, much like
Perl closes your file handles if you no longer use them anywhere.

=head3 A short note on callbacks

A common issue that hits people is the problem of passing parameters
to callbacks. Programmers used to languages such as C or C++ are often
used to a style where one passes the address of a function (a function
reference) and some data value, e.g.:

   sub callback {
      my ($arg) = @_;

      $arg->method;
   }

   my $arg = ...;

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

not be invoked out of the blue; you have to run the event loop first.
Also, event-based programs need to block sometimes too, such as when
there is nothing to do, and everything is waiting for new events to
arrive.

In AnyEvent, this is done using condition variables. Condition variables
are named "condition variables" because they represent a condition that is
initially false and needs to be fulfilled.

You can also call them "merge points", "sync points", "rendezvous ports"
or even callbacks and many other things (and they are often called these
names in other frameworks). The important point is that you can create them
freely and later wait for them to become true.

Condition variables have two sides - one side is the "producer" of the
condition (whatever code detects and flags the condition), the other side
is the "consumer" (the code that waits for that condition).

In our example in the previous section, the producer is the event callback
and there is no consumer yet - let's change that right now:

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


In the example using condition variables, we used those to start waiting
for events, and in fact, condition variables are the solution:

   my $quit_program = AnyEvent->condvar;

   # create AnyEvent watchers (or not) here

   $quit_program->recv;

If any of your watcher callbacks decide to quit (this is often
called an "unloop" in other frameworks), they can just call C<<
$quit_program->send >>. Of course, they could also decide not to and
call C<exit> instead, or they could decide never to quit (e.g. in a
long-running daemon program).

If you don't need some clean quit functionality and just want to run the
event loop, you can do this:

   AnyEvent->condvar->recv;

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

Instead of having an extra mechanism to signal errors, connection errors
are signalled by crafting a special "response status line", like this:

   HTTP/1.0 500 Connection refused

This means the caller cannot distinguish (easily) between
locally-generated errors and server errors, but it simplifies error
handling for the caller a lot.

The error callback also destroys the handle explicitly, because we are not
interested in continuing after any errors. In AnyEvent::Handle callbacks
you have to call C<destroy> explicitly to destroy a handle. Outside of
those callbacks you can just forget the object reference and it will be
automatically cleaned up.

Last but not least, we set an C<on_eof> callback that is called when the
other side indicates it has stopped writing data, which we will use to
gracefully shut down the handle and report the results. This callback is
only called when the read queue is empty - if the read queue expects
some data and the handle gets an EOF from the other side this will be an
error - after all, you did expect more to come.

If you wanted to write a server using AnyEvent::Handle, you would use

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

=item AnyEvent::Log::format_time $timestamp

Formats a timestamp as returned by C<< AnyEvent->now >> or C<<
AnyEvent->time >> or many other functions in the same way as
C<AnyEvent::Log> does.

In your main program (as opposed to in your module) you can override
the default timestamp display format by loading this module and then
redefining this function.

Most commonly, this function can be used in formatting callbacks.

=item AnyEvent::Log::default_format $time, $ctx, $level, $msg

Format a log message using the given timestamp, logging context, log level
and log message.

This is the formatting function used to format messages when no custom
function is provided.

In your main program (as opposed to in your module) you can override the

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

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

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


The application should try these in the order given.

Example:

   resolve_sockaddr "google.com", "http", 0, undef, undef, sub { ... };

=cut

our %HOSTS;          # $HOSTS{$nodename}[$ipv6] = [@aliases...]
our @HOSTS_CHECKING; # callbacks to call when hosts have been loaded
our $HOSTS_MTIME;

sub _parse_hosts($) {
   %HOSTS = ();

   for (split /\n/, $_[0]) {
      s/#.*$//;
      s/^[ \t]+//;
      y/A-Z/a-z/;

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


   use AnyEvent::Strict;
   # strict mode now switched on

=head1 DESCRIPTION

This module implements AnyEvent's strict mode.

Loading it makes AnyEvent check all arguments to AnyEvent-methods, at the
expense of being slower (often the argument checking takes longer than the
actual function). It also wraps all callbacks to check for modifications
of C<$_>, which indicates a programming bug inside the watcher callback.

Normally, you don't load this module yourself but instead use it
indirectly via the C<PERL_ANYEVENT_STRICT> environment variable (see
L<AnyEvent>). However, this module can be loaded manually at any time.

=cut

package AnyEvent::Strict;

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

#      if ref $ref;
   
   if ($self->{debug}) {
      #d# Net::SSLeay::set_info_callback ($session, 50000);
   }

   if ($self->{verify_mode}) {
      Scalar::Util::weaken $self;
      Scalar::Util::weaken $ref;

      # we have to provide a dummy callbacks as at least Net::SSLeay <= 1.35
      # try to call it even if specified as 0 or undef.
      Net::SSLeay::set_verify
         $session,
         $self->{verify_mode},
         sub { $self->verify ($session, $ref, $cn, @_) };
   }

   $session
}

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

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

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

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

Win32 spoilers: Due to the endlessly sucky and broken native windows
perls (there is no way to cleanly exit a child process on that platform
that doesn't also kill the parent), you have to make sure that your main
program doesn't exit as long as any C<fork_calls> are still in progress,
otherwise the program won't exit. Also, on most windows platforms some
memory will leak for every invocation. We are open for improvements that
don't require XS hackery.



( run in 0.475 second using v1.01-cache-2.11-cpan-9b1e4054eb1 )