EV

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

        - (libev) due to a thinko, instead of disabling everything but
          select on the borked OS X platform, everything but select was
          allowed (reported by Emanuele Giaquinta).
        - (libev) actually verify that local and remote port are matching in
          libev's socketpair emulation, which makes denial-of-service
          attacks harder (but not impossible - it's windows). Make sure
          it even works under vista, which thinks that getpeer/sockname
          should return fantasy port numbers.

3.51 Wed Dec 24 23:01:59 CET 2008
        - do not cache the arguments passed to callbacks if the refcount
          indicates that the callback has stolen them.
	- (libev) try to avoid librt on GNU/Linux.
        - (libev) check port_getn return value dfferently, might potentially
          avoid problems.
        - (libev) fix a bug with stat watchers possibly causing freezes.
        - (libev) work around OS X 10.5 breaking poll, now select is the
          only viable choice left on that pile of garbage.
	- play tester whore: disable some tests that typically fail only
          on cpan tester machines.

Changes  view on Meta::CPAN


3.42 Mon May 26 07:36:46 CEST 2008
	- (libev) work around another bug in windows perls and
           windows itself: failed connects do NOT set read or write
           flags in select, but this version of libev will.

3.41 Thu May 22 01:39:40 CEST 2008
	- (libev) fix many heap-related bugs (timers, periodics).
        - (libev) improve timing stability of timers and periodics.
        - expose ev_loop_verify to perl code.
        - clarify documentation for periodic reschedule callbacks.
        - verify that the passed callback argument is indeed a code
          reference, for earlier error reporting and a nice calling
          speed increase (as well as saving memory).

3.4  Tue May 20 21:51:55 CEST 2008
        - (libev) work around both a windows bug and a bug in perl's
          select on windows when not waiting for any file descriptors.
	- bundle ev.pod into the tarball, just to increase its size
          (and for the poor internetless person).
          

Changes  view on Meta::CPAN

        - provide considerably finer control over configuration.

0.7  Fri Nov  9 20:37:58 CET 2007
	- move AnyEvent adaptor into the AnyEvent module.
        - use private copy of evdns.[ch].
        - many minor fixes.

0.6  Thu Nov  8 18:23:43 CET 2007
	- (libev) better native win32 support.
        - fix idle watchers.
        - implement and document periodic reschedule callbacks.
        - do not run dns test on !linux platforms (actually to exclude win32).
        - fix (unused in EV :) poll backend.

0.51 Tue Nov  6 19:50:22 CET 2007
	- fix kqueue/poll compilation issue.
        - work around design issues in kqueue.
        - enable kqueue by default, seems to work.

0.5  Tue Nov  6 17:37:44 CET 2007
	- add signal and pid mutators.

EV.pm  view on Meta::CPAN

   
   undef $w; # destroy event watcher again
   
   my $w = EV::periodic 0, 60, 0, sub {
      warn "is called every minute, on the minute, exactly";
   };
   
   # IO
   
   my $w = EV::io *STDIN, EV::READ, sub {
      my ($w, $revents) = @_; # all callbacks receive the watcher and event mask
      warn "stdin is readable, you entered: ", <STDIN>;
   };
   
   # SIGNALS
   
   my $w = EV::signal 'QUIT', sub {
      warn "sigquit received\n";
   };
   
   # CHILD/PID STATUS CHANGES

EV.pm  view on Meta::CPAN


=item $backend = $loop->backend

Returns an integer describing the backend used by libev (EV::BACKEND_SELECT
or EV::BACKEND_EPOLL).

=item $active = EV::run [$flags]

=item $active = $loop->run ([$flags])

Begin checking for events and calling callbacks. It returns when a
callback calls EV::break or the flags are nonzero (in which case the
return value is true) or when there are no active watchers which reference
the loop (keepalive is true), in which case the return value will be
false. The return value can generally be interpreted as "if true, there is
more work left to do".

The $flags argument can be one of the following:

   0               as above
   EV::RUN_ONCE    block at most once (wait, but do not loop)

EV.pm  view on Meta::CPAN

A watcher is an object that gets created to record your interest in some
event. For instance, if you want to wait for STDIN to become readable, you
would create an EV::io watcher for that:

   my $watcher = EV::io *STDIN, EV::READ, sub {
      my ($watcher, $revents) = @_;
      warn "yeah, STDIN should now be readable without blocking!\n"
   };

All watchers can be active (waiting for events) or inactive (paused). Only
active watchers will have their callbacks invoked. All callbacks will be
called with at least two arguments: the watcher and a bitmask of received
events.

Each watcher type has its associated bit in revents, so you can use the
same callback for multiple watchers. The event mask is named after the
type, i.e. EV::child sets EV::CHILD, EV::prepare sets EV::PREPARE,
EV::periodic sets EV::PERIODIC and so on, with the exception of I/O events
(which can set both EV::READ and EV::WRITE bits).

In the rare case where one wants to create a watcher but not start it at

EV.pm  view on Meta::CPAN

Call the callback when $signal is received (the signal can be specified by
number or by name, just as with C<kill> or C<%SIG>).

Only one event loop can grab a given signal - attempting to grab the same
signal from two EV loops will crash the program immediately or cause data
corruption.

EV will grab the signal for the process (the kernel only allows one
component to receive a signal at a time) when you start a signal watcher,
and removes it again when you stop it. Perl does the same when you
add/remove callbacks to C<%SIG>, so watch out.

You can have as many signal watchers per signal as you want.

The C<signal_ns> variant doesn't start (activate) the newly created watcher.

=item $w->set ($signal)

Reconfigures the watcher, see the constructor above for details. Can be
called at any time.

EV.pm  view on Meta::CPAN


=item $w = EV::check $callback

=item $w = EV::check_ns $callback

=item $w = $loop->check ($callback)

=item $w = $loop->check_ns ($callback)

Call the callback just after the process wakes up again (after it has
gathered events), but before any other callbacks have been invoked.

This can be used to integrate other event-based software into the EV
mainloop: You register a prepare callback and in there, you create io and
timer watchers as required by the other software. Here is a real-world
example of integrating Net::SNMP (with some details left out):

   our @snmp_watcher;

   our $snmp_prepare = EV::prepare sub {
      # do nothing unless active

EV.pm  view on Meta::CPAN

      @snmp_watcher = (
         (map { EV::io $_, EV::READ, sub { } }
             keys %{ $dispatcher->{_descriptors} }),

         EV::timer +($event->[Net::SNMP::Dispatcher::_ACTIVE]
                     ? $event->[Net::SNMP::Dispatcher::_TIME] - EV::now : 0),
                    0, sub { },
      );
   };

The callbacks are irrelevant (and are not even being called), the
only purpose of those watchers is to wake up the process as soon as
one of those events occurs (socket readable, or timer timed out). The
corresponding EV::check watcher will then clean up:

   our $snmp_check = EV::check sub {
      # destroy all watchers
      @snmp_watcher = ();

      # make the dispatcher handle any new stuff
      ... not shown
   };

The callbacks of the created watchers will not be called as the watchers
are destroyed before this can happen (remember EV::check gets called
first).

The C<check_ns> variant doesn't start (activate) the newly created watcher.

=item EV::CHECK constant issues

Like all other watcher types, there is a bitmask constant for use in
C<$revents> and other places. The C<EV::CHECK> is special as it has
the same name as the C<CHECK> sub called by Perl. This doesn't cause

README  view on Meta::CPAN

   
       undef $w; # destroy event watcher again
   
       my $w = EV::periodic 0, 60, 0, sub {
          warn "is called every minute, on the minute, exactly";
       };
   
       # IO
   
       my $w = EV::io *STDIN, EV::READ, sub {
          my ($w, $revents) = @_; # all callbacks receive the watcher and event mask
          warn "stdin is readable, you entered: ", <STDIN>;
       };
   
       # SIGNALS
   
       my $w = EV::signal 'QUIT', sub {
          warn "sigquit received\n";
       };
   
       # CHILD/PID STATUS CHANGES

README  view on Meta::CPAN

        Calling "suspend"/"resume" has the side effect of updating the event
        loop time (see "now_update").

    $backend = EV::backend
    $backend = $loop->backend
        Returns an integer describing the backend used by libev
        (EV::BACKEND_SELECT or EV::BACKEND_EPOLL).

    $active = EV::run [$flags]
    $active = $loop->run ([$flags])
        Begin checking for events and calling callbacks. It returns when a
        callback calls EV::break or the flags are nonzero (in which case the
        return value is true) or when there are no active watchers which
        reference the loop (keepalive is true), in which case the return
        value will be false. The return value can generally be interpreted
        as "if true, there is more work left to do".

        The $flags argument can be one of the following:

           0               as above
           EV::RUN_ONCE    block at most once (wait, but do not loop)

README  view on Meta::CPAN

    A watcher is an object that gets created to record your interest in some
    event. For instance, if you want to wait for STDIN to become readable,
    you would create an EV::io watcher for that:

       my $watcher = EV::io *STDIN, EV::READ, sub {
          my ($watcher, $revents) = @_;
          warn "yeah, STDIN should now be readable without blocking!\n"
       };

    All watchers can be active (waiting for events) or inactive (paused).
    Only active watchers will have their callbacks invoked. All callbacks
    will be called with at least two arguments: the watcher and a bitmask of
    received events.

    Each watcher type has its associated bit in revents, so you can use the
    same callback for multiple watchers. The event mask is named after the
    type, i.e. EV::child sets EV::CHILD, EV::prepare sets EV::PREPARE,
    EV::periodic sets EV::PERIODIC and so on, with the exception of I/O
    events (which can set both EV::READ and EV::WRITE bits).

    In the rare case where one wants to create a watcher but not start it at

README  view on Meta::CPAN

        Call the callback when $signal is received (the signal can be
        specified by number or by name, just as with "kill" or %SIG).

        Only one event loop can grab a given signal - attempting to grab the
        same signal from two EV loops will crash the program immediately or
        cause data corruption.

        EV will grab the signal for the process (the kernel only allows one
        component to receive a signal at a time) when you start a signal
        watcher, and removes it again when you stop it. Perl does the same
        when you add/remove callbacks to %SIG, so watch out.

        You can have as many signal watchers per signal as you want.

        The "signal_ns" variant doesn't start (activate) the newly created
        watcher.

    $w->set ($signal)
        Reconfigures the watcher, see the constructor above for details. Can
        be called at any time.

README  view on Meta::CPAN


        The "prepare_ns" variant doesn't start (activate) the newly created
        watcher.

   CHECK WATCHERS - customise your event loop even more!
    $w = EV::check $callback
    $w = EV::check_ns $callback
    $w = $loop->check ($callback)
    $w = $loop->check_ns ($callback)
        Call the callback just after the process wakes up again (after it
        has gathered events), but before any other callbacks have been
        invoked.

        This can be used to integrate other event-based software into the EV
        mainloop: You register a prepare callback and in there, you create
        io and timer watchers as required by the other software. Here is a
        real-world example of integrating Net::SNMP (with some details left
        out):

           our @snmp_watcher;

README  view on Meta::CPAN

              @snmp_watcher = (
                 (map { EV::io $_, EV::READ, sub { } }
                     keys %{ $dispatcher->{_descriptors} }),

                 EV::timer +($event->[Net::SNMP::Dispatcher::_ACTIVE]
                             ? $event->[Net::SNMP::Dispatcher::_TIME] - EV::now : 0),
                            0, sub { },
              );
           };

        The callbacks are irrelevant (and are not even being called), the
        only purpose of those watchers is to wake up the process as soon as
        one of those events occurs (socket readable, or timer timed out).
        The corresponding EV::check watcher will then clean up:

           our $snmp_check = EV::check sub {
              # destroy all watchers
              @snmp_watcher = ();

              # make the dispatcher handle any new stuff
              ... not shown
           };

        The callbacks of the created watchers will not be called as the
        watchers are destroyed before this can happen (remember EV::check
        gets called first).

        The "check_ns" variant doesn't start (activate) the newly created
        watcher.

    EV::CHECK constant issues
        Like all other watcher types, there is a bitmask constant for use in
        $revents and other places. The "EV::CHECK" is special as it has the
        same name as the "CHECK" sub called by Perl. This doesn't cause big

libev/Changes  view on Meta::CPAN

          so document what needs to be done in ev_loop_fork
          (analyzed by Benjamin Mahler).
	- remove superfluous sys/timeb.h include on win32
          (analyzed by Jason Madden).
        - updated libecb.

4.20 Sat Jun 20 13:01:43 CEST 2015
	- prefer noexcept over throw () with C++ 11.
        - update ecb.h due to incompatibilities with c11.
        - fix a potential aliasing issue when reading and writing
          watcher callbacks.

4.19 Thu Sep 25 08:18:25 CEST 2014
	- ev.h wasn't valid C++ anymore, which tripped compilers other than
          clang, msvc or gcc (analyzed by Raphael 'kena' Poss). Unfortunately,
          C++ doesn't support typedefs for function pointers fully, so the affected
          declarations have to spell out the types each time.
	- when not using autoconf, tighten the check for clock_gettime and related
          functionality.

4.18 Fri Sep  5 17:55:26 CEST 2014
	- events on files were not always generated properly with the
          epoll backend (testcase by Assaf Inbal).
	- mark event pipe fd as cloexec after a fork (analyzed by Sami Farin).
        - (ecb) support m68k, m88k and sh (patch by Miod Vallat).
        - use a reasonable fallback for EV_NSIG instead of erroring out
          when we can't detect the signal set size.
        - in the absence of autoconf, do not use the clock syscall
          on glibc >= 2.17 (avoids the syscall AND -lrt on systems
          doing clock_gettime in userspace).
        - ensure extern "C" function pointers are used for externally-visible
          loop callbacks (not watcher callbacks yet).
        - (ecb) work around memory barriers and volatile apparently both being
          broken in visual studio 2008 and later (analysed and patch by Nicolas Noble).

4.15 Fri Mar  1 12:04:50 CET 2013
        - destroying a non-default loop would stop the global waitpid
          watcher (Denis Bilenko).
	- queueing pending watchers of higher priority from a watcher now invokes
          them in a timely fashion (reported by Denis Bilenko).
	- add throw() to all libev functions that cannot throw exceptions, for
          further code size decrease when compiling for C++.
        - add throw () to callbacks that must not throw exceptions (allocator,
          syserr, loop acquire/release, periodic reschedule cbs).
	- fix event_base_loop return code, add event_get_callback, event_base_new,
          event_base_get_method calls to improve libevent 1.x emulation and add
          some libevent 2.x functionality (based on a patch by Jeff Davey).
        - add more memory fences to fix a bug reported by Jeff Davey. Better
          be overfenced than underprotected.
	- ev_run now returns a boolean status (true meaning watchers are
          still active).
	- ev_once: undef EV_ERROR in ev_kqueue.c, to avoid clashing with
          libev's EV_ERROR (reported by 191919).

libev/Changes  view on Meta::CPAN

          freezes on hash collisions (reported and analysed by Graham Leggett).
	- new config symbol, EV_USE_CLOCK_SYSCALL, to make libev use
          a direct syscall - slower, but no dependency on librt et al.
        - assume negative return values != -1 signals success of port_getn
          (http://cvs.epicsol.org/cgi/viewcvs.cgi/epic5/source/newio.c?rev=1.52)
          (no known failure reports, but it doesn't hurt).
        - fork detection in ev_embed now stops and restarts the watcher
          automatically.
        - EXPERIMENTAL: default the method to operator () in ev++.h,
          to make it nicer to use functors (requested by Benedek László).
        - fixed const object callbacks in ev++.h.
        - replaced loop_ref argument of watcher.set (loop) by a direct
          ev_loop * in ev++.h, to avoid clashes with functor patch.
        - do not try to watch the empty string via inotify.
        - inotify watchers could be leaked under certain circumstances.
        - OS X 10.5 is actually even more broken than earlier versions,
          so fall back to select on that piece of garbage.
        - fixed some weirdness in the ev_embed documentation.

3.49 Wed Nov 19 11:26:53 CET 2008
	- ev_stat watchers will now use inotify as a mere hint on

libev/README  view on Meta::CPAN

   - wallclock-based times (using absolute time, cron-like).
   - relative timers/timeouts (handle time jumps).
   - fast intra-thread communication between multiple
     event loops (with optional fast linux eventfd backend).
   - extremely easy to embed (fully documented, no dependencies,
     autoconf supported but optional).
   - very small codebase, no bloated library, simple code.
   - fully extensible by being able to plug into the event loop,
     integrate other event loops, integrate other event loop users.
   - very little memory use (small watchers, small event loop data).
   - optional C++ interface allowing method and function callbacks
     at no extra memory or runtime overhead.
   - optional Perl interface with similar characteristics (capable
     of running Glib/Gtk2 on libev).
   - support for other languages (multiple C++ interfaces, D, Ruby,
     Python) available from third-parties.

   Examples of programs that embed libev: the EV perl module, auditd,
   rxvt-unicode, gvpe (GNU Virtual Private Ethernet), the Deliantra MMORPG
   server (http://www.deliantra.net/), Rubinius (a next-generation Ruby
   VM), the Ebb web server, the Rev event toolkit.

libev/ev.pod  view on Meta::CPAN

   // a single header file is required
   #include <ev.h>

   #include <stdio.h> // for puts

   // every watcher type has its own typedef'd struct
   // with the name ev_TYPE
   ev_io stdin_watcher;
   ev_timer timeout_watcher;

   // all watcher callbacks have a similar signature
   // this callback is called when data is readable on stdin
   static void
   stdin_cb (EV_P_ ev_io *w, int revents)
   {
     puts ("stdin ready");
     // for one-shot events, one must manually stop the watcher
     // with its corresponding stop function.
     ev_io_stop (EV_A_ w);

     // this causes all nested ev_run's to stop iterating

libev/ev.pod  view on Meta::CPAN


=item unsigned int ev_backend (loop)

Returns one of the C<EVBACKEND_*> flags indicating the event backend in
use.

=item ev_tstamp ev_now (loop)

Returns the current "event loop time", which is the time the event loop
received events and started processing them. This timestamp does not
change as long as callbacks are being processed, and this is also the base
time used for relative timers. You can treat it as the timestamp of the
event occurring (or more correctly, libev finding out about it).

=item ev_now_update (loop)

Establishes the current time by querying the kernel, updating the time
returned by C<ev_now ()> in the progress. This is a costly operation and
is usually done automatically within C<ev_run ()>.

This function is rarely useful, but when some event callback runs for a

libev/ev.pod  view on Meta::CPAN

without a previous call to C<ev_suspend>.

Calling C<ev_suspend>/C<ev_resume> has the side effect of updating the
event loop time (see C<ev_now_update>).

=item bool ev_run (loop, int flags)

Finally, this is it, the event handler. This function usually is called
after you have initialised all your watchers and you want to start
handling events. It will ask the operating system for any new events, call
the watcher callbacks, and then repeat the whole process indefinitely: This
is why event loops are called I<loops>.

If the flags argument is specified as C<0>, it will keep handling events
until either no event watchers are active anymore or C<ev_break> was
called.

The return value is false if there are no more active watchers (which
usually means "all jobs done" or "deadlock"), and true in all other cases
(which usually means " you should call C<ev_run> again").

libev/ev.pod  view on Meta::CPAN


   ev_ref (loop);
   ev_signal_stop (loop, &exitsig);

=item ev_set_io_collect_interval (loop, ev_tstamp interval)

=item ev_set_timeout_collect_interval (loop, ev_tstamp interval)

These advanced functions influence the time that libev will spend waiting
for events. Both time intervals are by default C<0>, meaning that libev
will try to invoke timer/periodic callbacks and I/O callbacks with minimum
latency.

Setting these to a higher value (the C<interval> I<must> be >= C<0>)
allows libev to delay invocation of I/O and timer/periodic callbacks
to increase efficiency of loop iterations (or to increase power-saving
opportunities).

The idea is that sometimes your program runs just fast enough to handle
one (or very few) event(s) per loop iteration. While this makes the
program responsive, it also wastes a lot of CPU time to poll for new
events, especially with backends like C<select ()> which have a high
overhead for the actual polling but can deliver many events at once.

By setting a higher I<io collect interval> you allow libev to spend more

libev/ev.pod  view on Meta::CPAN


=item ev_set_loop_release_cb (loop, void (*release)(EV_P) throw (), void (*acquire)(EV_P) throw ())

Sometimes you want to share the same loop between multiple threads. This
can be done relatively simply by putting mutex_lock/unlock calls around
each call to a libev function.

However, C<ev_run> can run an indefinite time, so it is not feasible
to wait for it to return. One way around this is to wake up the event
loop via C<ev_break> and C<ev_async_send>, another way is to set these
I<release> and I<acquire> callbacks on the loop.

When set, then C<release> will be called just before the thread is
suspended waiting for new events, and C<acquire> is called just
afterwards.

Ideally, C<release> will just call your mutex_unlock function, and
C<acquire> will just call the mutex_lock function again.

While event loop modifications are allowed between invocations of
C<release> and C<acquire> (that's their only purpose after all), no

libev/ev.pod  view on Meta::CPAN

=item ev_set_userdata (loop, void *data)

=item void *ev_userdata (loop)

Set and retrieve a single C<void *> associated with a loop. When
C<ev_set_userdata> has never been called, then C<ev_userdata> returns
C<0>.

These two functions can be used to associate arbitrary data with a loop,
and are intended solely for the C<invoke_pending_cb>, C<release> and
C<acquire> callbacks described above, but of course can be (ab-)used for
any other purpose as well.

=item ev_verify (loop)

This function only does something when C<EV_VERIFY> support has been
compiled in, which is the default for non-minimal builds. It tries to go
through all internal structures and checks them for validity. If anything
is found to be inconsistent, it will print an error message to standard
error and call C<abort ()>.

libev/ev.pod  view on Meta::CPAN

=item C<EV_IDLE>

The C<ev_idle> watcher has determined that you have nothing better to do.

=item C<EV_PREPARE>

=item C<EV_CHECK>

All C<ev_prepare> watchers are invoked just I<before> C<ev_run> starts to
gather new events, and all C<ev_check> watchers are queued (not invoked)
just after C<ev_run> has gathered them, but before it queues any callbacks
for any received events. That means C<ev_prepare> watchers are the last
watchers invoked before the event loop sleeps or polls for new events, and
C<ev_check> watchers will be invoked before any other watchers of the same
or lower priority within an event loop iteration.

Callbacks of both watcher types can start and stop as many watchers as
they want, and all of them will be taken into account (for example, a
C<ev_prepare> watcher might start an idle watcher to keep C<ev_run> from
blocking).

libev/ev.pod  view on Meta::CPAN

ran out of memory, a file descriptor was found to be closed or any other
problem. Libev considers these application bugs.

You best act on it by reporting the problem and somehow coping with the
watcher being stopped. Note that well-written programs should not receive
an error ever, so when your watcher receives it, this usually indicates a
bug in your program.

Libev will usually signal a few "dummy" events together with an error, for
example it might indicate that a fd is readable or writable, and if your
callbacks is well-written it can just attempt the operation and cope with
the error from read() or write(). This will not work in multi-threaded
programs, though, as the fd could already be closed and reused for another
thing, so beware.

=back

=head2 GENERIC WATCHER FUNCTIONS

=over 4

libev/ev.pod  view on Meta::CPAN

callback invocation within a single event loop iteration: Higher priority
watchers are invoked before lower priority ones, but they all get invoked
before polling for new events.

Libev uses the second (only-for-ordering) model for all its watchers
except for idle watchers (which use the lock-out model).

The rationale behind this is that implementing the lock-out model for
watchers is not well supported by most kernel interfaces, and most event
libraries will just poll for the same events again and again as long as
their callbacks have not been executed, which is very inefficient in the
common case of one high-priority watcher locking out a mass of lower
priority ones.

Static (ordering) priorities are most useful when you have two or more
watchers handling the same resource: a typical usage example is having an
C<ev_io> watcher to receive data, and an associated C<ev_timer> to handle
timeouts. Under load, data might be received while the program handles
other jobs, but since timers normally get invoked first, the timeout
handler will be executed before checking for data. In that case, giving
the timer a lower priority than the I/O watcher ensures that I/O will be

libev/ev.pod  view on Meta::CPAN

you cache some data and want to flush it before blocking (for example,
in X programs you might want to do an C<XFlush ()> in an C<ev_prepare>
watcher).

This is done by examining in each prepare call which file descriptors
need to be watched by the other library, registering C<ev_io> watchers
for them and starting an C<ev_timer> watcher for any timeouts (many
libraries provide exactly this functionality). Then, in the check watcher,
you check for any events that occurred (by checking the pending status
of all watchers and stopping them) and call back into the library. The
I/O and timer callbacks will never actually be called (but must be valid
nevertheless, because you never know, you know?).

As another example, the Perl Coro module uses these hooks to integrate
coroutines into libev programs, by yielding to other active coroutines
during each prepare and only letting the process block if no coroutines
are ready to run (it's actually more complicated: it only runs coroutines
with priority higher than or equal to the event loop and one coroutine
of lower priority, but only once, using idle watchers to keep the event
loop from blocking if lower-priority coroutines are active, thus mapping
low-priority coroutines to idle/background tasks).

libev/ev.pod  view on Meta::CPAN

into libev. Here are some ideas on how to include libadns into libev
(there is a Perl module named C<EV::ADNS> that does this, which you could
use as a working example. Another Perl module named C<EV::Glib> embeds a
Glib main context into libev, and finally, C<Glib::EV> embeds EV into the
Glib event loop).

Method 1: Add IO watchers and a timeout watcher in a prepare handler,
and in a check watcher, destroy them and call into libadns. What follows
is pseudo-code only of course. This requires you to either use a low
priority for the check watcher or use C<ev_clear_pending> explicitly, as
the callbacks for the IO/timeout watchers might not have been called yet.

   static ev_io iow [nfd];
   static ev_timer tw;

   static void
   io_cb (struct ev_loop *loop, ev_io *w, int revents)
   {
   }

   // create io watchers for each fd and a timer before blocking

libev/ev.pod  view on Meta::CPAN

       }

     adns_afterpoll (adns, fds, nfd, timeval_from (ev_now (loop));
   }

Method 2: This would be just like method 1, but you run C<adns_afterpoll>
in the prepare watcher and would dispose of the check watcher.

Method 3: If the module to be embedded supports explicit event
notification (libadns does), you can also make use of the actual watcher
callbacks, and only destroy/create the watchers in the prepare watcher.

   static void
   timer_cb (EV_P_ ev_timer *w, int revents)
   {
     adns_state ads = (adns_state)w->data;
     update_now (EV_A);

     adns_processtimeouts (ads, &tv_now);
   }

libev/ev.pod  view on Meta::CPAN

     if (timeout >= 0)
       // create/start timer

     // poll
     ev_run (EV_A_ 0);

     // stop timer again
     if (timeout >= 0)
       ev_timer_stop (EV_A_ &to);

     // stop io watchers again - their callbacks should have set
     for (n = 0; n < nfds; ++n)
       ev_io_stop (EV_A_ iow [n]);

     return got_events;
   }


=head2 C<ev_embed> - when one backend isn't enough...

This is a rather advanced watcher type that lets you embed one event loop

libev/ev.pod  view on Meta::CPAN


As for prioritising I/O: under rare circumstances you have the case where
some fds have to be watched and handled very quickly (with low latency),
and even priorities and idle watchers might have too much overhead. In
this case you would put all the high priority stuff in one loop and all
the rest in a second one, and embed the second one in the first.

As long as the watcher is active, the callback will be invoked every
time there might be events pending in the embedded loop. The callback
must then call C<ev_embed_sweep (mainloop, watcher)> to make a single
sweep and invoke their callbacks (the callback doesn't need to invoke the
C<ev_embed_sweep> function directly, it could also start an idle watcher
to give the embedded loop strictly lower priority for example).

You can also set the callback to C<0>, in which case the embed watcher
will automatically execute the embedded loop sweep whenever necessary.

Fork detection will be handled transparently while the C<ev_embed> watcher
is active, i.e., the embedded loop will automatically be forked when the
embedding loop forks. In other cases, the user is responsible for calling
C<ev_loop_fork> on the embedded loop.

libev/ev.pod  view on Meta::CPAN


If C<fd> is less than 0, then no I/O watcher will be started and the
C<events> argument is being ignored. Otherwise, an C<ev_io> watcher for
the given C<fd> and C<events> set will be created and started.

If C<timeout> is less than 0, then no timeout watcher will be
started. Otherwise an C<ev_timer> watcher with after = C<timeout> (and
repeat = 0) will be started. C<0> is a valid timeout.

The callback has the type C<void (*cb)(int revents, void *arg)> and is
passed an C<revents> set like normal event callbacks (a combination of
C<EV_ERROR>, C<EV_READ>, C<EV_WRITE> or C<EV_TIMER>) and the C<arg>
value passed to C<ev_once>. Note that it is possible to receive I<both>
a timeout and an io event at the same time - you probably should give io
events precedence.

Example: wait up to ten seconds for data to appear on STDIN_FILENO.

   static void stdin_ready (int revents, void *arg)
   {
     if (revents & EV_READ)

libev/ev.pod  view on Meta::CPAN


   // exit main program, after modal loop is finished
   exit_main_loop = 1;

   // exit both
   exit_main_loop = exit_nested_loop = 1;

=head2 THREAD LOCKING EXAMPLE

Here is a fictitious example of how to run an event loop in a different
thread from where callbacks are being invoked and watchers are
created/added/removed.

For a real-world example, see the C<EV::Loop::Async> perl module,
which uses exactly this technique (which is suited for many high-level
languages).

The example uses a pthread mutex to protect the loop data, a condition
variable to wait for callback invocations, an async watcher to notify the
event loop thread and an unspecified mechanism to wake up the main thread.

libev/ev.pod  view on Meta::CPAN

The callback for the C<ev_async> watcher does nothing: the watcher is used
solely to wake up the event loop so it takes notice of any new watchers
that might have been added:

   static void
   async_cb (EV_P_ ev_async *w, int revents)
   {
      // just used for the side effects
   }

The C<l_release> and C<l_acquire> callbacks simply unlock/lock the mutex
protecting the loop data, respectively.

   static void
   l_release (EV_P)
   {
     userdata *u = ev_userdata (EV_A);
     pthread_mutex_unlock (&u->lock);
   }

   static void

libev/ev.pod  view on Meta::CPAN

Note that sending the C<ev_async> watcher is required because otherwise
an event loop currently blocking in the kernel will have no knowledge
about the newly added timer. By waking up the loop it will pick up any new
watchers in the next event loop iteration.

=head2 THREADS, COROUTINES, CONTINUATIONS, QUEUES... INSTEAD OF CALLBACKS

While the overhead of a callback that e.g. schedules a thread is small, it
is still an overhead. If you embed libev, and your main usage is with some
kind of threads or coroutines, you might want to customise libev so that
doesn't need callbacks anymore.

Imagine you have coroutines that you can switch to using a function
C<switch_to (coro)>, that libev runs in a coroutine called C<libev_coro>
and that due to some magic, the currently active coroutine is stored in a
global called C<current_coro>. Then you can build your own "wait for libev
event" primitive by changing C<EV_CB_DECLARE> and C<EV_CB_INVOKE> (note
the differing C<;> conventions):

   #define EV_CB_DECLARE(type)   struct my_coro *cb;
   #define EV_CB_INVOKE(watcher) switch_to ((watcher)->cb)

libev/ev.pod  view on Meta::CPAN

=back

=head1 C++ SUPPORT

=head2 C API

The normal C API should work fine when used from C++: both ev.h and the
libev sources can be compiled as C++. Therefore, code that uses the C API
will work fine.

Proper exception specifications might have to be added to callbacks passed
to libev: exceptions may be thrown only from watcher callbacks, all other
callbacks (allocator, syserr, loop acquire/release and periodic reschedule
callbacks) must not throw exceptions, and might need a C<noexcept>
specification. If you have code that needs to be compiled as both C and
C++ you can use the C<EV_NOEXCEPT> macro for this:

   static void
   fatal_error (const char *msg) EV_NOEXCEPT
   {
     perror (msg);
     abort ();
   }

   ...
   ev_set_syserr_cb (fatal_error);

The only API functions that can currently throw exceptions are C<ev_run>,
C<ev_invoke>, C<ev_invoke_pending> and C<ev_loop_destroy> (the latter
because it runs cleanup watchers).

Throwing exceptions in watcher callbacks is only supported if libev itself
is compiled with a C++ compiler or your C and C++ environments allow
throwing exceptions through C libraries (most do).

=head2 C++ API

Libev comes with some simplistic wrapper classes for C++ that mainly allow
you to use some convenience methods to start/stop watchers and also change
the callback model to a model using method callbacks on objects.

To use it,

   #include <ev++.h>

This automatically includes F<ev.h> and puts all of its definitions (many
of them macros) into the global namespace. All C++ specific things are
put into the C<ev> namespace. It should support all the same embedding
options as F<ev.h>, most notably C<EV_MULTIPLICITY>.

Care has been taken to keep the overhead low. The only data member the C++
classes add (compared to plain C-style watchers) is the event loop pointer
that the watcher is associated with (or no additional members at all if
you disable C<EV_MULTIPLICITY> when embedding libev).

Currently, functions, static and non-static member functions and classes
with C<operator ()> can be used as callbacks. Other types should be easy
to add as long as they only need one additional pointer for context. If
you need support for other types of functors please contact the author
(preferably after implementing it).

For all this to work, your C++ compiler either has to use the same calling
conventions as your C compiler (for static member functions), or you have
to embed libev and compile libev itself as C++.

Here is a list of things available in the C<ev> namespace:

libev/ev.pod  view on Meta::CPAN


There are others, and I stopped counting.

=back


=head1 MACRO MAGIC

Libev can be compiled with a variety of options, the most fundamental
of which is C<EV_MULTIPLICITY>. This option determines whether (most)
functions and callbacks have an initial C<struct ev_loop *> argument.

To make it easier to write programs that cope with either variant, the
following macros are defined:

=over 4

=item C<EV_A>, C<EV_A_>

This provides the loop I<argument> for functions, if one is required ("ev
loop argument"). The C<EV_A> form is used when this is the sole argument,

libev/ev.pod  view on Meta::CPAN

     SV *self; /* contains this struct */  \
     SV *cb_sv, *fh /* note no trailing ";" */

=item EV_CB_DECLARE (type)

=item EV_CB_INVOKE (watcher, revents)

=item ev_set_cb (ev, cb)

Can be used to change the callback member declaration in each watcher,
and the way callbacks are invoked and set. Must expand to a struct member
definition and a statement, respectively. See the F<ev.h> header file for
their default definitions. One possible use for overriding these is to
avoid the C<struct ev_loop *> as first argument in all cases, or to use
method calls instead of plain function calls in C++.

=back

=head2 EXPORTED API SYMBOLS

If you need to re-export the API (e.g. via a DLL) and you need a list of

libev/ev.pod  view on Meta::CPAN


See also L</THREAD LOCKING EXAMPLE>.

=head3 COROUTINES

Libev is very accommodating to coroutines ("cooperative threads"):
libev fully supports nesting calls to its functions from different
coroutines (e.g. you can call C<ev_run> on the same loop from two
different coroutines, and switch freely between both coroutines running
the loop, as long as you don't confuse yourself). The only exception is
that you must not do this from C<ev_periodic> reschedule callbacks.

Care has been taken to ensure that libev does not keep local state inside
C<ev_run>, and other calls do not usually allow for coroutine switches as
they do not call any callbacks.

=head2 COMPILER WARNINGS

Depending on your compiler and compiler settings, you might get no or a
lot of warnings when compiling libev code. Some people are apparently
scared by this.

However, these are unavoidable for many reasons. For one, each compiler
has different warnings, and each user has different tastes regarding
warning options. "Warn-free" code therefore cannot be a goal except when

libev/ev.pod  view on Meta::CPAN

backend-specific APIs, libev relies on a few additional extensions:

=over 4

=item C<void (*)(ev_watcher_type *, int revents)> must have compatible
calling conventions regardless of C<ev_watcher_type *>.

Libev assumes not only that all watcher pointers have the same internal
structure (guaranteed by POSIX but not by ISO C for example), but it also
assumes that the same (machine) code can be used to call any watcher
callback: The watcher callbacks have different type signatures, but libev
calls them using an C<ev_watcher *> internally.

=item null pointers and integer zero are represented by 0 bytes

Libev uses C<memset> to initialise structs and arrays to C<0> bytes, and
relies on this setting pointers and integers to null.

=item pointer accesses must be thread-atomic

Accessing a pointer value must be atomic, it must both be readable and



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