--- libev/ev.pod 2007/12/24 13:19:12 1.109 +++ libev/ev.pod 2009/03/04 12:51:37 1.226 @@ -4,55 +4,71 @@ =head1 SYNOPSIS - #include + #include =head2 EXAMPLE PROGRAM - #include + // a single header file is required + #include - ev_io stdin_watcher; - ev_timer timeout_watcher; + #include // for puts - /* called when data readable on stdin */ - static void - stdin_cb (EV_P_ struct ev_io *w, int revents) - { - /* puts ("stdin ready"); */ - ev_io_stop (EV_A_ w); /* just a syntax example */ - ev_unloop (EV_A_ EVUNLOOP_ALL); /* leave all loop calls */ - } - - static void - timeout_cb (EV_P_ struct ev_timer *w, int revents) - { - /* puts ("timeout"); */ - ev_unloop (EV_A_ EVUNLOOP_ONE); /* leave one loop call */ - } - - int - main (void) - { - struct ev_loop *loop = ev_default_loop (0); - - /* initialise an io watcher, then start it */ - ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ); - ev_io_start (loop, &stdin_watcher); - - /* simple non-repeating 5.5 second timeout */ - ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.); - ev_timer_start (loop, &timeout_watcher); + // every watcher type has its own typedef'd struct + // with the name ev_TYPE + ev_io stdin_watcher; + ev_timer timeout_watcher; - /* loop till timeout or data ready */ - ev_loop (loop, 0); + // 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_loop's to stop iterating + ev_unloop (EV_A_ EVUNLOOP_ALL); + } + + // another callback, this time for a time-out + static void + timeout_cb (EV_P_ ev_timer *w, int revents) + { + puts ("timeout"); + // this causes the innermost ev_loop to stop iterating + ev_unloop (EV_A_ EVUNLOOP_ONE); + } - return 0; - } + int + main (void) + { + // use the default event loop unless you have special needs + struct ev_loop *loop = ev_default_loop (0); + + // initialise an io watcher, then start it + // this one will watch for stdin to become readable + ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ); + ev_io_start (loop, &stdin_watcher); + + // initialise a timer watcher, then start it + // simple non-repeating 5.5 second timeout + ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.); + ev_timer_start (loop, &timeout_watcher); + + // now wait for events to arrive + ev_loop (loop, 0); + + // unloop was called, so exit + return 0; + } =head1 DESCRIPTION -The newest version of this document is also available as a html-formatted +The newest version of this document is also available as an html-formatted web page you might find easier to navigate when reading it for the first -time: L. +time: L. Libev is an event loop: you register interest in certain events (such as a file descriptor being readable or a timeout occurring), and it will manage @@ -86,12 +102,13 @@ =head2 CONVENTIONS -Libev is very configurable. In this manual the default configuration will -be described, which supports multiple event loops. For more info about -various configuration options please have a look at B section in -this manual. If libev was configured without support for multiple event -loops, then all functions taking an initial argument of name C -(which is always of type C) will not have this argument. +Libev is very configurable. In this manual the default (and most common) +configuration will be described, which supports multiple event loops. For +more info about various configuration options please have a look at +B section in this manual. If libev was configured without support +for multiple event loops, then all functions taking an initial argument of +name C (which is always of type C) will not have +this argument. =head2 TIME REPRESENTATION @@ -100,10 +117,31 @@ the beginning of 1970, details are complicated, don't ask). This type is called C, which is what you should use too. It usually aliases to the C type in C, and when you need to do any calculations on -it, you should treat it as some floatingpoint value. Unlike the name +it, you should treat it as some floating point value. Unlike the name component C might indicate, it is also used for time differences throughout libev. +=head1 ERROR HANDLING + +Libev knows three classes of errors: operating system errors, usage errors +and internal errors (bugs). + +When libev catches an operating system error it cannot handle (for example +a system call indicating a condition libev cannot fix), it calls the callback +set via C, which is supposed to fix the problem or +abort. The default is to print a diagnostic message and to call C. + +When libev detects a usage error such as a negative timer interval, then +it will print a diagnostic message and abort (via the C mechanism, +so C will disable this checking): these are programming errors in +the libev caller and need to be fixed there. + +Libev also has a few internal error-checking Cions, and also has +extensive consistency checking code. These do not trigger under normal +circumstances, as they indicate either a bug in libev or worse. + + =head1 GLOBAL FUNCTIONS These functions can be called anytime, even before initialising the @@ -121,7 +159,7 @@ Sleep for the given interval: The current thread will be blocked until either it is interrupted or the given time interval has passed. Basically -this is a subsecond-resolution C. +this is a sub-second-resolution C. =item int ev_version_major () @@ -144,9 +182,9 @@ Example: Make sure we haven't accidentally been linked against the wrong version. - assert (("libev version mismatch", - ev_version_major () == EV_VERSION_MAJOR - && ev_version_minor () >= EV_VERSION_MINOR)); + assert (("libev version mismatch", + ev_version_major () == EV_VERSION_MAJOR + && ev_version_minor () >= EV_VERSION_MINOR)); =item unsigned int ev_supported_backends () @@ -158,15 +196,15 @@ Example: make sure we have the epoll method, because yeah this is cool and a must have and can we have a torrent of it please!!!11 - assert (("sorry, no epoll, no sex", - ev_supported_backends () & EVBACKEND_EPOLL)); + assert (("sorry, no epoll, no sex", + ev_supported_backends () & EVBACKEND_EPOLL)); =item unsigned int ev_recommended_backends () Return the set of all backends compiled into this binary of libev and also recommended for this platform. This set is often smaller than the one returned by C, as for example kqueue is broken on -most BSDs and will not be autodetected unless you explicitly request it +most BSDs and will not be auto-detected unless you explicitly request it (assuming you know what you are doing). This is the set of backends that libev will probe for if you specify no backends explicitly. @@ -180,21 +218,24 @@ See the description of C watchers for more info. -=item ev_set_allocator (void *(*cb)(void *ptr, long size)) +=item ev_set_allocator (void *(*cb)(void *ptr, long size)) [NOT REENTRANT] Sets the allocation function to use (the prototype is similar - the -semantics is identical - to the realloc C function). It is used to -allocate and free memory (no surprises here). If it returns zero when -memory needs to be allocated, the library might abort or take some -potentially destructive action. The default is your system realloc -function. +semantics are identical to the C C89/SuS/POSIX function). It is +used to allocate and free memory (no surprises here). If it returns zero +when memory needs to be allocated (C), the library might abort +or take some potentially destructive action. + +Since some systems (at least OpenBSD and Darwin) fail to implement +correct C semantics, libev will use a wrapper around the system +C and C functions by default. You could override this function in high-availability programs to, say, free some memory if it cannot allocate memory, to use a special allocator, or even to sleep a while and retry until some memory is available. Example: Replace the libev allocator with one that waits a bit and then -retries). +retries (example requires a standards-compliant C). static void * persistent_realloc (void *ptr, size_t size) @@ -213,12 +254,12 @@ ... ev_set_allocator (persistent_realloc); -=item ev_set_syserr_cb (void (*cb)(const char *msg)); +=item ev_set_syserr_cb (void (*cb)(const char *msg)); [NOT REENTRANT] -Set the callback function to call on a retryable syscall error (such +Set the callback function to call on a retryable system call error (such as failed select, poll, epoll_wait). The message is a printable string indicating the system call or subsystem causing the problem. If this -callback is set, then libev will expect it to remedy the sitution, no +callback is set, then libev will expect it to remedy the situation, no matter what, when it returns. That is, libev will generally retry the requested operation, or, if the condition doesn't go away, do bad stuff (such as abort). @@ -239,16 +280,13 @@ =head1 FUNCTIONS CONTROLLING THE EVENT LOOP -An event loop is described by a C. The library knows two -types of such loops, the I loop, which supports signals and child -events, and dynamically created loops which do not. - -If you use threads, a common model is to run the default event loop -in your main thread (or in a separate thread) and for each thread you -create, you also create another event loop. Libev itself does no locking -whatsoever, so if you mix calls to the same event loop in different -threads, make sure you lock (this is usually a bad idea, though, even if -done correctly, because it's hideous and inefficient). +An event loop is described by a C (the C +is I optional in this case, as there is also an C +I). + +The library knows two types of such loops, the I loop, which +supports signals and child events, and dynamically created loops which do +not. =over 4 @@ -262,6 +300,17 @@ If you don't know what event loop to use, use the one returned from this function. +Note that this function is I thread-safe, so if you want to use it +from multiple threads, you have to lock (note also that this is unlikely, +as loops cannot be shared easily between threads anyway). + +The default loop is the only loop that can handle C and +C watchers, and to do this, it always registers a handler +for C. If this is a problem for your application you can either +create a dynamic loop with C that doesn't do that, or you +can simply overwrite the C signal handler I calling +C. + The flags argument can be used to specify special behaviour or specific backends to use, and is usually specified as C<0> (or C). @@ -276,7 +325,7 @@ =item C -If this flag bit is ored into the flag value (or the program runs setuid +If this flag bit is or'ed into the flag value (or the program runs setuid or setgid) then libev will I look at the environment variable C. Otherwise (the default), this environment variable will override the flags completely if it is found in the environment. This is @@ -292,15 +341,15 @@ This works by calling C on every iteration of the loop, and thus this might slow down your event loop if you do a lot of loop iterations and little real work, but is usually not noticeable (on my -Linux system for example, C is actually a simple 5-insn sequence -without a syscall and thus I fast, but my Linux system also has +GNU/Linux system for example, C is actually a simple 5-insn sequence +without a system call and thus I fast, but my GNU/Linux system also has C which is even faster). The big advantage of this flag is that you can forget about fork (and forget about forgetting to tell libev about forking) when you use this flag. -This flag setting cannot be overriden or specified in the C +This flag setting cannot be overridden or specified in the C environment variable. =item C (value 1, portable select backend) @@ -312,11 +361,15 @@ usually the fastest backend for a low number of (low-numbered :) fds. To get good performance out of this backend you need a high amount of -parallelity (most of the file descriptors should be busy). If you are +parallelism (most of the file descriptors should be busy). If you are writing a server, you should C in a loop to accept as many connections as possible during one iteration. You might also want to have a look at C to increase the amount of -readyness notifications you get per iteration. +readiness notifications you get per iteration. + +This backend maps C to the C set and C to the +C set (and to work around Microsoft Windows bugs, also onto the +C set on that platform). =item C (value 2, poll backend, available everywhere except on windows) @@ -327,40 +380,67 @@ i.e. O(total_fds). See the entry for C, above, for performance tips. +This backend maps C to C, and +C to C. + =item C (value 4, Linux) For few fds, this backend is a bit little slower than poll and select, but it scales phenomenally better. While poll and select usually scale like O(total_fds) where n is the total number of fds (or the highest fd), -epoll scales either O(1) or O(active_fds). The epoll design has a number -of shortcomings, such as silently dropping events in some hard-to-detect -cases and rewiring a syscall per fd change, no fork support and bad -support for dup. +epoll scales either O(1) or O(active_fds). + +The epoll mechanism deserves honorable mention as the most misdesigned +of the more advanced event mechanisms: mere annoyances include silently +dropping file descriptors, requiring a system call per change per file +descriptor (and unnecessary guessing of parameters), problems with dup and +so on. The biggest issue is fork races, however - if a program forks then +I parent and child process have to recreate the epoll set, which can +take considerable time (one syscall per file descriptor) and is of course +hard to detect. + +Epoll is also notoriously buggy - embedding epoll fds I work, but +of course I, and epoll just loves to report events for totally +I file descriptors (even already closed ones, so one cannot +even remove them from the set) than registered in the set (especially +on SMP systems). Libev tries to counter these spurious notifications by +employing an additional generation counter and comparing that against the +events to filter out spurious ones, recreating the set when required. While stopping, setting and starting an I/O watcher in the same iteration -will result in some caching, there is still a syscall per such incident -(because the fd could point to a different file description now), so its -best to avoid that. Also, C'ed file descriptors might not work -very well if you register events for both fds. - -Please note that epoll sometimes generates spurious notifications, so you -need to use non-blocking I/O or other means to avoid blocking when no data -(or space) is available. +will result in some caching, there is still a system call per such +incident (because the same I could point to a different +I now), so its best to avoid that. Also, C'ed +file descriptors might not work very well if you register events for both +file descriptors. Best performance from this backend is achieved by not unregistering all -watchers for a file descriptor until it has been closed, if possible, i.e. -keep at least one watcher active per fd at all times. +watchers for a file descriptor until it has been closed, if possible, +i.e. keep at least one watcher active per fd at all times. Stopping and +starting a watcher (without re-setting it) also usually doesn't cause +extra overhead. A fork can both result in spurious notifications as well +as in libev having to destroy and recreate the epoll object, which can +take considerable time and thus should be avoided. + +All this means that, in practice, C can be as fast or +faster than epoll for maybe up to a hundred file descriptors, depending on +the usage. So sad. -While nominally embeddeble in other event loops, this feature is broken in +While nominally embeddable in other event loops, this feature is broken in all kernel versions tested so far. +This backend maps C and C in the same way as +C. + =item C (value 8, most BSD clones) Kqueue deserves special mention, as at the time of this writing, it was broken on all BSDs except NetBSD (usually it doesn't work reliably with anything but sockets and pipes, except on Darwin, where of course -it's completely useless). For this reason it's not being "autodetected" -unless you explicitly specify it explicitly in the flags (i.e. using +it's completely useless). Unlike epoll, however, whose brokenness +is by design, these kqueue bugs can (and eventually will) be fixed +without API changes to existing programs. For this reason it's not being +"auto-detected" unless you explicitly specify it in the flags (i.e. using C) or libev was compiled on a known-to-be-good (-enough) system like NetBSD. @@ -371,9 +451,10 @@ It scales in the same way as the epoll backend, but the interface to the kernel is more efficient (which says nothing about its actual speed, of course). While stopping, setting and starting an I/O watcher does never -cause an extra syscall as with C, it still adds up to -two event changes per incident, support for C is very bad and it -drops fds silently in similarly hard-to-detect cases. +cause an extra system call as with C, it still adds up to +two event changes per incident. Support for C is very bad (but +sane, unlike epoll) and it drops fds silently in similarly hard-to-detect +cases This backend usually performs well under most conditions. @@ -381,8 +462,12 @@ everywhere, so you might need to test for this. And since it is broken almost everywhere, you should only use it when you have a lot of sockets (for which it usually works), by embedding it into another event loop -(e.g. C or C) and using it only for -sockets. +(e.g. C or C (but C is of course +also broken on OS X)) and, did I mention it, using it only for sockets. + +This backend maps C into an C kevent with +C, and C into an C kevent with +C. =item C (value 16, Solaris 8) @@ -396,7 +481,7 @@ This uses the Solaris 10 event port mechanism. As with everything on Solaris, it's really slow, but it still scales very well (O(active_fds)). -Please note that solaris event ports can deliver a lot of spurious +Please note that Solaris event ports can deliver a lot of spurious notifications, so you need to use non-blocking I/O or other means to avoid blocking when no data (or space) is available. @@ -405,6 +490,14 @@ descriptors a "slow" C or C backend might perform better. +On the positive side, with the exception of the spurious readiness +notifications, this backend actually performed fully to specification +in all tests and is fully embeddable, which is a rare feat among the +OS-specific backends (I vastly prefer correctness over speed hacks). + +This backend maps C and C in the same way as +C. + =item C Try all backends (even potentially broken ones that wouldn't be tried @@ -415,26 +508,26 @@ =back -If one or more of these are ored into the flags value, then only these -backends will be tried (in the reverse order as given here). If none are -specified, most compiled-in backend will be tried, usually in reverse -order of their flag values :) +If one or more of these are or'ed into the flags value, then only these +backends will be tried (in the reverse order as listed here). If none are +specified, all backends in C will be tried. -The most typical usage is like this: +Example: This is the most typical usage. - if (!ev_default_loop (0)) - fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?"); + if (!ev_default_loop (0)) + fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?"); -Restrict libev to the select and poll backends, and do not allow +Example: Restrict libev to the select and poll backends, and do not allow environment settings to be taken into account: - ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV); + ev_default_loop (EVBACKEND_POLL | EVBACKEND_SELECT | EVFLAG_NOENV); -Use whatever libev has to offer, but make sure that kqueue is used if -available (warning, breaks stuff, best use only with your own private -event loop and only if you know the OS supports your types of fds): +Example: Use whatever libev has to offer, but make sure that kqueue is +used if available (warning, breaks stuff, best use only with your own +private event loop and only if you know the OS supports your types of +fds): - ev_default_loop (ev_recommended_backends () | EVBACKEND_KQUEUE); + ev_default_loop (ev_recommended_backends () | EVBACKEND_KQUEUE); =item struct ev_loop *ev_loop_new (unsigned int flags) @@ -443,25 +536,29 @@ handle signal and child watchers, and attempts to do so will be greeted by undefined behaviour (or a failed assertion if assertions are enabled). +Note that this function I thread-safe, and the recommended way to use +libev with threads is indeed to create one loop per thread, and using the +default loop in the "main" or "initial" thread. + Example: Try to create a event loop that uses epoll and nothing else. - struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV); - if (!epoller) - fatal ("no epoll found here, maybe it hides under your chair"); + struct ev_loop *epoller = ev_loop_new (EVBACKEND_EPOLL | EVFLAG_NOENV); + if (!epoller) + fatal ("no epoll found here, maybe it hides under your chair"); =item ev_default_destroy () Destroys the default loop again (frees all memory and kernel state etc.). None of the active event watchers will be stopped in the normal sense, so e.g. C might still return true. It is your -responsibility to either stop all watchers cleanly yoursef I +responsibility to either stop all watchers cleanly yourself I calling this function, or cope with the fact afterwards (which is usually the easiest thing, you can just ignore the watchers and/or C them for example). -Note that certain global state, such as signal state, will not be freed by -this function, and related watchers (such as signal and child watchers) -would need to be stopped manually. +Note that certain global state, such as signal state (and installed signal +handlers), will not be freed by this function, and related watchers (such +as signal and child watchers) would need to be stopped manually. In general it is not advisable to call this function except in the rare occasion where you really need to free e.g. the signal handling @@ -475,14 +572,16 @@ =item ev_default_fork () -This function reinitialises the kernel state for backends that have -one. Despite the name, you can call it anytime, but it makes most sense -after forking, in either the parent or child process (or both, but that -again makes little sense). - -You I call this function in the child process after forking if and -only if you want to use the event library in both processes. If you just -fork+exec, you don't have to call it. +This function sets a flag that causes subsequent C iterations +to reinitialise the kernel state for backends that have one. Despite the +name, you can call it anytime, but it makes most sense after forking, in +the child process (or both child and parent, but that again makes little +sense). You I call it in the child before using any of the libev +functions, and it will only take effect at the next C iteration. + +On the other hand, you only need to call this function in the child +process if and only if you want to use the event library in the child. If +you just fork+exec, you don't have to call it at all. The function itself is quite fast and it's usually not a problem to call it just in case after a fork. To make this easy, the function will fit in @@ -490,15 +589,17 @@ pthread_atfork (0, 0, ev_default_fork); -At the moment, C and C are safe to use -without calling this function, so if you force one of those backends you -do not need to care. - =item ev_loop_fork (loop) Like C, but acts on an event loop created by C. Yes, you have to call this on every allocated event loop -after fork, and how you do this is entirely your own problem. +after fork that you want to re-use in the child, and how you do this is +entirely your own problem. + +=item int ev_is_default_loop (loop) + +Returns true when the given loop is, in fact, the default loop, and false +otherwise. =item unsigned int ev_loop_count (loop) @@ -523,6 +624,18 @@ 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 in the progress. This is a costly operation and +is usually done automatically within C. + +This function is rarely useful, but when some event callback runs for a +very long time without entering the event loop, updating libev's idea of +the current time is a good idea. + +See also "The special problem of time updates" in the C section. + =item ev_loop (loop, int flags) Finally, this is it, the event handler. This function usually is called @@ -534,51 +647,63 @@ Please note that an explicit C is usually better than relying on all watchers to be stopped when deciding when a program has -finished (especially in interactive programs), but having a program that -automatically loops as long as it has to and no longer by virtue of -relying on its watchers stopping correctly is a thing of beauty. +finished (especially in interactive programs), but having a program +that automatically loops as long as it has to and no longer by virtue +of relying on its watchers stopping correctly, that is truly a thing of +beauty. A flags value of C will look for new events, will handle -those events and any outstanding ones, but will not block your process in -case there are no events and will return after one iteration of the loop. +those events and any already outstanding ones, but will not block your +process in case there are no events and will return after one iteration of +the loop. A flags value of C will look for new events (waiting if -neccessary) and will handle those and any outstanding ones. It will block -your process until at least one new event arrives, and will return after -one iteration of the loop. This is useful if you are waiting for some -external event in conjunction with something not expressible using other -libev watchers. However, a pair of C/C watchers is +necessary) and will handle those and any already outstanding ones. It +will block your process until at least one new event arrives (which could +be an event internal to libev itself, so there is no guarantee that a +user-registered callback will be called), and will return after one +iteration of the loop. + +This is useful if you are waiting for some external event in conjunction +with something not expressible using other libev watchers (i.e. "roll your +own C"). However, a pair of C/C watchers is usually a better approach for this kind of thing. Here are the gory details of what C does: - Before the first iteration, call any pending watchers. - * If there are no active watchers (reference count is zero), return. - - Queue all prepare watchers and then call all outstanding watchers. - - If we have been forked, recreate the kernel state. + * If EVFLAG_FORKCHECK was used, check for a fork. + - If a fork was detected (by any means), queue and call all fork watchers. + - Queue and call all prepare watchers. + - If we have been forked, detach and recreate the kernel state + as to not disturb the other process. - Update the kernel state with all outstanding changes. - - Update the "event loop time". - - Calculate for how long to block. + - Update the "event loop time" (ev_now ()). + - Calculate for how long to sleep or block, if at all + (active idle watchers, EVLOOP_NONBLOCK or not having + any active watchers at all will result in not sleeping). + - Sleep if the I/O and timer collect interval say so. - Block the process, waiting for any events. - Queue all outstanding I/O (fd) events. - - Update the "event loop time" and do time jump handling. - - Queue all outstanding timers. - - Queue all outstanding periodics. - - If no events are pending now, queue all idle watchers. + - Update the "event loop time" (ev_now ()), and do time jump adjustments. + - Queue all expired timers. + - Queue all expired periodics. + - Unless any events are pending now, queue all idle watchers. - Queue all check watchers. - Call all queued watchers in reverse order (i.e. check watchers first). Signals and child watchers are implemented as I/O watchers, and will be handled here by queueing them when their watcher gets executed. - - If ev_unloop has been called or EVLOOP_ONESHOT or EVLOOP_NONBLOCK - were used, return, otherwise continue with step *. + - If ev_unloop has been called, or EVLOOP_ONESHOT or EVLOOP_NONBLOCK + were used, or there are no active watchers, return, otherwise + continue with step *. -Example: Queue some jobs and then loop until no events are outsanding +Example: Queue some jobs and then loop until no events are outstanding anymore. ... queue jobs here, make sure they register event watchers as long ... as they still have work to do (even an idle watcher will do..) ev_loop (my_loop, 0); - ... jobs done. yeah! + ... jobs done or somebody called unloop. yeah! =item ev_unloop (loop, how) @@ -587,49 +712,60 @@ C, which will make the innermost C call return, or C, which will make all nested C calls return. +This "unloop state" will be cleared when entering C again. + +It is safe to call C from otuside any C calls. + =item ev_ref (loop) =item ev_unref (loop) Ref/unref can be used to add or remove a reference count on the event loop: Every watcher keeps one reference, and as long as the reference -count is nonzero, C will not return on its own. If you have -a watcher you never unregister that should not keep C from -returning, ev_unref() after starting, and ev_ref() before stopping it. For -example, libev itself uses this for its internal signal pipe: It is not -visible to the libev user and should not keep C from exiting if -no event watchers registered by it are active. It is also an excellent +count is nonzero, C will not return on its own. + +If you have a watcher you never unregister that should not keep C +from returning, call ev_unref() after starting, and ev_ref() before +stopping it. + +As an example, libev itself uses this for its internal signal pipe: It is +not visible to the libev user and should not keep C from exiting +if no event watchers registered by it are active. It is also an excellent way to do this for generic recurring timers or from within third-party -libraries. Just remember to I and I. +libraries. Just remember to I and I +(but only if the watcher wasn't active before, or was active before, +respectively). Example: Create a signal watcher, but keep it from keeping C running when nothing else is active. - struct ev_signal exitsig; - ev_signal_init (&exitsig, sig_cb, SIGINT); - ev_signal_start (loop, &exitsig); - evf_unref (loop); + ev_signal exitsig; + ev_signal_init (&exitsig, sig_cb, SIGINT); + ev_signal_start (loop, &exitsig); + evf_unref (loop); Example: For some weird reason, unregister the above signal handler again. - ev_ref (loop); - ev_signal_stop (loop, &exitsig); + 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 are by default C<0>, meaning that libev will try to -invoke timer/periodic callbacks and I/O callbacks with minimum latency. +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 I be >= C<0>) -allows libev to delay invocation of I/O and timer/periodic callbacks to -increase efficiency of loop iterations. - -The background 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 +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. +=item EV_USE_EVENTFD + +If defined to be C<1>, then libev will assume that C is +available and will probe for kernel support at runtime. This will improve +C and C performance and reduce resource consumption. +If undefined, it will be enabled if the headers indicate GNU/Linux + Glibc +2.7 or newer, otherwise disabled. + =item EV_USE_SELECT If undefined or defined to be C<1>, libev will compile in support for the -C(2) backend. No attempt at auto-detection will be done: if no other method takes over, select will be it. Otherwise the select backend will not be compiled in. @@ -2436,11 +3274,11 @@ If defined to C<1>, then the select backend will use the system C structure. This is useful if libev doesn't compile due to a missing -C or C definition or it misguesses the bitset layout on -exotic systems. This usually limits the range of file descriptors to some -low limit such as 1024 or might have other limitations (winsocket only -allows 64 sockets). The C macro, set before compilation, might -influence the size of the C used. +C or C definition or it mis-guesses the bitset layout +on exotic systems. This usually limits the range of file descriptors to +some low limit such as 1024 or might have other limitations (winsocket +only allows 64 sockets). The C macro, set before compilation, +configures the maximum size of the C. =item EV_SELECT_IS_WINSOCKET @@ -2452,6 +3290,14 @@ it is assumed that all these functions actually work on fds, even on win32. Should not be defined on non-win32 platforms. +=item EV_FD_TO_WIN32_HANDLE + +If C is enabled, then libev needs a way to map +file descriptors to socket handles. When not defining this symbol (the +default), then libev will call C<_get_osfhandle>, which is usually +correct. In some cases, programs use their own file descriptor management, +in which case they can provide this function to map fds to socket handles. + =item EV_USE_POLL If defined to be C<1>, libev will compile in support for the C(2) @@ -2462,8 +3308,9 @@ If defined to be C<1>, libev will compile in support for the Linux C(7) backend. Its availability will be detected at runtime, -otherwise another method will be used as fallback. This is the -preferred backend for GNU/Linux systems. +otherwise another method will be used as fallback. This is the preferred +backend for GNU/Linux systems. If undefined, it will be enabled if the +headers indicate GNU/Linux + Glibc 2.4 or newer, otherwise disabled. =item EV_USE_KQUEUE @@ -2486,19 +3333,31 @@ =item EV_USE_DEVPOLL -reserved for future expansion, works like the USE symbols above. +Reserved for future expansion, works like the USE symbols above. =item EV_USE_INOTIFY If defined to be C<1>, libev will compile in support for the Linux inotify interface to speed up C watchers. Its actual availability will -be detected at runtime. +be detected at runtime. If undefined, it will be enabled if the headers +indicate GNU/Linux + Glibc 2.4 or newer, otherwise disabled. + +=item EV_ATOMIC_T + +Libev requires an integer type (suitable for storing C<0> or C<1>) whose +access is atomic with respect to other threads or signal contexts. No such +type is easily found in the C language, so you can provide your own type +that you know is safe for your purposes. It is used both for signal handler "locking" +as well as for signal and thread safety in C watchers. + +In the absence of this define, libev will use C +(from F), which is usually good enough on most platforms. =item EV_H The name of the F header file used to include it. The default if -undefined is C<< >> in F and C<"ev.h"> in F. This -can be used to virtually rename the F header file in case of conflicts. +undefined is C<"ev.h"> in F, F and F. This can be +used to virtually rename the F header file in case of conflicts. =item EV_CONFIG_H @@ -2509,7 +3368,7 @@ =item EV_EVENT_H Similarly to C, this macro can be used to override F's idea -of how the F header can be found. +of how the F header can be found, the default is C<"event.h">. =item EV_PROTOTYPES @@ -2540,8 +3399,8 @@ and time, so using the defaults of five priorities (-2 .. +2) is usually fine. -If your embedding app does not need any priorities, defining these both to -C<0> will save some memory and cpu. +If your embedding application does not need any priorities, defining these +both to C<0> will save some memory and CPU. =item EV_PERIODIC_ENABLE @@ -2558,7 +3417,8 @@ =item EV_EMBED_ENABLE If undefined or defined to be C<1>, then embed watchers are supported. If -defined to be C<0>, then they are not. +defined to be C<0>, then they are not. Embed watchers rely on most other +watcher types, which therefore must not be disabled. =item EV_STAT_ENABLE @@ -2570,11 +3430,17 @@ If undefined or defined to be C<1>, then fork watchers are supported. If defined to be C<0>, then they are not. +=item EV_ASYNC_ENABLE + +If undefined or defined to be C<1>, then async watchers are supported. If +defined to be C<0>, then they are not. + =item EV_MINIMAL If you need to shave off some kilobytes of code at the expense of some -speed, define this symbol to C<1>. Currently only used for gcc to override -some inlining decisions, saves roughly 30% codesize of amd64. +speed, define this symbol to C<1>. Currently this is used to override some +inlining decisions, saves roughly 30% code size on amd64. It also selects a +much smaller 2-heap for timer management over the default 4-heap. =item EV_PID_HASHSIZE @@ -2591,6 +3457,41 @@ watchers you might want to increase this value (I be a power of two). +=item EV_USE_4HEAP + +Heaps are not very cache-efficient. To improve the cache-efficiency of the +timer and periodics heaps, libev uses a 4-heap when this symbol is defined +to C<1>. The 4-heap uses more complicated (longer) code but has noticeably +faster performance with many (thousands) of watchers. + +The default is C<1> unless C is set in which case it is C<0> +(disabled). + +=item EV_HEAP_CACHE_AT + +Heaps are not very cache-efficient. To improve the cache-efficiency of the +timer and periodics heaps, libev can cache the timestamp (I) within +the heap structure (selected by defining C to C<1>), +which uses 8-12 bytes more per watcher and a few hundred bytes more code, +but avoids random read accesses on heap changes. This improves performance +noticeably with many (hundreds) of watchers. + +The default is C<1> unless C is set in which case it is C<0> +(disabled). + +=item EV_VERIFY + +Controls how much internal verification (see C) will +be done: If set to C<0>, no internal verification code will be compiled +in. If set to C<1>, then verification code will be compiled in, but not +called. If set to C<2>, then the internal verification code will be +called once per loop, which can slow down libev. If set to C<3>, then the +verification code will be called very frequently, which will slow down +libev considerably. + +The default is C<1>, unless C is set, in which case it will be +C<0>. + =item EV_COMMON By default, all watchers have a C member. By redefining @@ -2600,9 +3501,9 @@ For example, the perl EV module uses something like this: - #define EV_COMMON \ - SV *self; /* contains this struct */ \ - SV *cb_sv, *fh /* note no trailing ";" */ + #define EV_COMMON \ + SV *self; /* contains this struct */ \ + SV *cb_sv, *fh /* note no trailing ";" */ =item EV_CB_DECLARE (type) @@ -2617,18 +3518,20 @@ avoid the C 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 +If you need to re-export the API (e.g. via a DLL) and you need a list of exported symbols, you can use the provided F files which list all public symbols, one per line: - Symbols.ev for libev proper - Symbols.event for the libevent emulation + Symbols.ev for libev proper + Symbols.event for the libevent emulation This can also be used to rename all public symbols to avoid clashes with multiple versions of libev linked together (which is obviously bad in -itself, but sometimes it is inconvinient to avoid this). +itself, but sometimes it is inconvenient to avoid this). A sed command like this will create wrapper C<#define>'s that you need to include before including F: @@ -2655,71 +3558,362 @@ The usage in rxvt-unicode is simpler. It has a F header file that everybody includes and which overrides some configure choices: - #define EV_MINIMAL 1 - #define EV_USE_POLL 0 - #define EV_MULTIPLICITY 0 - #define EV_PERIODIC_ENABLE 0 - #define EV_STAT_ENABLE 0 - #define EV_FORK_ENABLE 0 - #define EV_CONFIG_H - #define EV_MINPRI 0 - #define EV_MAXPRI 0 + #define EV_MINIMAL 1 + #define EV_USE_POLL 0 + #define EV_MULTIPLICITY 0 + #define EV_PERIODIC_ENABLE 0 + #define EV_STAT_ENABLE 0 + #define EV_FORK_ENABLE 0 + #define EV_CONFIG_H + #define EV_MINPRI 0 + #define EV_MAXPRI 0 - #include "ev++.h" + #include "ev++.h" And a F implementation file that contains libev proper and is compiled: - #include "ev_cpp.h" - #include "ev.c" + #include "ev_cpp.h" + #include "ev.c" + +=head1 INTERACTION WITH OTHER PROGRAMS OR LIBRARIES + +=head2 THREADS AND COROUTINES + +=head3 THREADS + +All libev functions are reentrant and thread-safe unless explicitly +documented otherwise, but libev implements no locking itself. This means +that you can use as many loops as you want in parallel, as long as there +are no concurrent calls into any libev function with the same loop +parameter (C calls have an implicit default loop parameter, +of course): libev guarantees that different event loops share no data +structures that need any locking. + +Or to put it differently: calls with different loop parameters can be done +concurrently from multiple threads, calls with the same loop parameter +must be done serially (but can be done from different threads, as long as +only one thread ever is inside a call at any point in time, e.g. by using +a mutex per loop). + +Specifically to support threads (and signal handlers), libev implements +so-called C watchers, which allow some limited form of +concurrency on the same event loop, namely waking it up "from the +outside". + +If you want to know which design (one loop, locking, or multiple loops +without or something else still) is best for your problem, then I cannot +help you, but here is some generic advice: + +=over 4 + +=item * most applications have a main thread: use the default libev loop +in that thread, or create a separate thread running only the default loop. + +This helps integrating other libraries or software modules that use libev +themselves and don't care/know about threading. + +=item * one loop per thread is usually a good model. + +Doing this is almost never wrong, sometimes a better-performance model +exists, but it is always a good start. + +=item * other models exist, such as the leader/follower pattern, where one +loop is handed through multiple threads in a kind of round-robin fashion. + +Choosing a model is hard - look around, learn, know that usually you can do +better than you currently do :-) + +=item * often you need to talk to some other thread which blocks in the +event loop. + +C watchers can be used to wake them up from other threads safely +(or from signal contexts...). + +An example use would be to communicate signals or other events that only +work in the default loop by registering the signal watcher with the +default loop and triggering an C watcher from the default loop +watcher callback into the event loop interested in the signal. + +=back + +=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 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 reschedule callbacks. + +Care has been taken to ensure that libev does not keep local state inside +C, 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 +targeting a specific compiler and compiler-version. + +Another reason is that some compiler warnings require elaborate +workarounds, or other changes to the code that make it less clear and less +maintainable. + +And of course, some compiler warnings are just plain stupid, or simply +wrong (because they don't actually warn about the condition their message +seems to warn about). For example, certain older gcc versions had some +warnings that resulted an extreme number of false positives. These have +been fixed, but some people still insist on making code warn-free with +such buggy versions. +While libev is written to generate as few warnings as possible, +"warn-free" code is not a goal, and it is recommended not to build libev +with any compiler warnings enabled unless you are prepared to cope with +them (e.g. by ignoring them). Remember that warnings are just that: +warnings, not errors, or proof of bugs. -=head1 COMPLEXITIES + +=head2 VALGRIND + +Valgrind has a special section here because it is a popular tool that is +highly useful. Unfortunately, valgrind reports are very hard to interpret. + +If you think you found a bug (memory leak, uninitialised data access etc.) +in libev, then check twice: If valgrind reports something like: + + ==2274== definitely lost: 0 bytes in 0 blocks. + ==2274== possibly lost: 0 bytes in 0 blocks. + ==2274== still reachable: 256 bytes in 1 blocks. + +Then there is no memory leak, just as memory accounted to global variables +is not a memleak - the memory is still being referenced, and didn't leak. + +Similarly, under some circumstances, valgrind might report kernel bugs +as if it were a bug in libev (e.g. in realloc or in the poll backend, +although an acceptable workaround has been found here), or it might be +confused. + +Keep in mind that valgrind is a very good tool, but only a tool. Don't +make it into some kind of religion. + +If you are unsure about something, feel free to contact the mailing list +with the full valgrind report and an explanation on why you think this +is a bug in libev (best check the archives, too :). However, don't be +annoyed when you get a brisk "this is no bug" answer and take the chance +of learning how to interpret valgrind properly. + +If you need, for some reason, empty reports from valgrind for your project +I suggest using suppression lists. + + +=head1 PORTABILITY NOTES + +=head2 WIN32 PLATFORM LIMITATIONS AND WORKAROUNDS + +Win32 doesn't support any of the standards (e.g. POSIX) that libev +requires, and its I/O model is fundamentally incompatible with the POSIX +model. Libev still offers limited functionality on this platform in +the form of the C backend, and only supports socket +descriptors. This only applies when using Win32 natively, not when using +e.g. cygwin. + +Lifting these limitations would basically require the full +re-implementation of the I/O system. If you are into these kinds of +things, then note that glib does exactly that for you in a very portable +way (note also that glib is the slowest event library known to man). + +There is no supported compilation method available on windows except +embedding it into other applications. + +Not a libev limitation but worth mentioning: windows apparently doesn't +accept large writes: instead of resulting in a partial write, windows will +either accept everything or return C if the buffer is too large, +so make sure you only write small amounts into your sockets (less than a +megabyte seems safe, but this apparently depends on the amount of memory +available). + +Due to the many, low, and arbitrary limits on the win32 platform and +the abysmal performance of winsockets, using a large number of sockets +is not recommended (and not reasonable). If your program needs to use +more than a hundred or so sockets, then likely it needs to use a totally +different implementation for windows, as libev offers the POSIX readiness +notification model, which cannot be implemented efficiently on windows +(Microsoft monopoly games). + +A typical way to use libev under windows is to embed it (see the embedding +section for details) and use the following F header file instead +of F: + + #define EV_STANDALONE /* keeps ev from requiring config.h */ + #define EV_SELECT_IS_WINSOCKET 1 /* configure libev for windows select */ + + #include "ev.h" + +And compile the following F file into your project (make sure +you do I compile the F or any other embedded source files!): + + #include "evwrap.h" + #include "ev.c" + +=over 4 + +=item The winsocket select function + +The winsocket C