--- libev/ev.pod 2009/06/30 06:24:38 1.245 +++ libev/ev.pod 2015/10/11 15:46:42 1.436 @@ -1,3 +1,5 @@ +=encoding utf-8 + =head1 NAME libev - a high performance full-featured event loop written in C @@ -28,8 +30,8 @@ // 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); + // this causes all nested ev_run's to stop iterating + ev_break (EV_A_ EVBREAK_ALL); } // another callback, this time for a time-out @@ -37,15 +39,15 @@ 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); + // this causes the innermost ev_run to stop iterating + ev_break (EV_A_ EVBREAK_ONE); } int main (void) { // use the default event loop unless you have special needs - struct ev_loop *loop = ev_default_loop (0); + struct ev_loop *loop = EV_DEFAULT; // initialise an io watcher, then start it // this one will watch for stdin to become readable @@ -58,9 +60,9 @@ ev_timer_start (loop, &timeout_watcher); // now wait for events to arrive - ev_loop (loop, 0); + ev_run (loop, 0); - // unloop was called, so exit + // break was called, so exit return 0; } @@ -77,9 +79,17 @@ on event-based programming, nor will it introduce event-based programming with libev. -Familarity with event based programming techniques in general is assumed +Familiarity with event based programming techniques in general is assumed throughout this document. +=head1 WHAT TO READ WHEN IN A HURRY + +This manual tries to be very detailed, but unfortunately, this also makes +it very long. If you just want to know the basics of libev, I suggest +reading L, then the L above and +look up the missing functions in L and the C and +C sections in L. + =head1 ABOUT LIBEV Libev is an event loop: you register interest in certain events (such as a @@ -100,13 +110,14 @@ Libev supports C (files, many character devices...). + +Epoll is truly the train wreck among event poll mechanisms, a frankenpoll, +cobbled together in a hurry, no thought to design or interaction with +others. Oh, the pain, will it ever stop... While stopping, setting and starting an I/O watcher in the same iteration will result in some caching, there is still a system call per such @@ -464,9 +573,9 @@ 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 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 +two event changes per incident. Support for C is very bad (you +might have to leak fd's on fork, but it's more sane than epoll) and it +drops fds silently in similarly hard-to-detect cases. This backend usually performs well under most conditions. @@ -493,19 +602,25 @@ 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 -notifications, so you need to use non-blocking I/O or other means to avoid -blocking when no data (or space) is available. - While this backend scales well, it requires one system call per active file descriptor per loop iteration. For small and medium numbers of file 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). +On the positive side, 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). + +On the negative side, the interface is I - so bizarre that +even sun itself gets it wrong in their code examples: The event polling +function sometimes returns events to the caller even though an error +occurred, but with no indication whether it has done so or not (yes, it's +even documented that way) - deadly for edge-triggered interfaces where you +absolutely have to know whether an event occurred or not because you have +to re-arm the watcher. + +Fortunately libev seems to be able to work around these idiocies. This backend maps C and C in the same way as C. @@ -516,41 +631,22 @@ with C). Since this is a mask, you can do stuff such as C. -It is definitely not recommended to use this flag. +It is definitely not recommended to use this flag, use whatever +C returns, or simply do not specify a backend +at all. + +=item C + +Not a backend at all, but a mask to select all backend bits from a +C value, in case you want to mask out any backends from a flags +value (e.g. when modifying the C environment variable). =back -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. - -Example: This is the most typical usage. - - if (!ev_default_loop (0)) - fatal ("could not initialise libev, bad $LIBEV_FLAGS in environment?"); - -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); - -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); - -=item struct ev_loop *ev_loop_new (unsigned int flags) - -Similar to C, but always creates a new event loop that is -always distinct from the default loop. Unlike the default loop, it cannot -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. +If one or more of the backend flags 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. Example: Try to create a event loop that uses epoll and nothing else. @@ -558,9 +654,14 @@ if (!epoller) fatal ("no epoll found here, maybe it hides under your chair"); -=item ev_default_destroy () +Example: Use whatever libev has to offer, but make sure that kqueue is +used if available. + + struct ev_loop *loop = ev_loop_new (ev_recommended_backends () | EVBACKEND_KQUEUE); + +=item ev_loop_destroy (loop) -Destroys the default loop again (frees all memory and kernel state +Destroys an event loop object (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 yourself I @@ -572,56 +673,83 @@ 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 -pipe fds. If you need dynamically allocated loops it is better to use -C and C). +This function is normally used on loop objects allocated by +C, but it can also be used on the default loop returned by +C, in which case it is not thread-safe. + +Note that it is not advisable to call this function on the default loop +except in the rare occasion where you really need to free its resources. +If you need dynamically allocated loops it is better to use C +and C. -=item ev_loop_destroy (loop) - -Like C, but destroys an event loop created by an -earlier call to C. - -=item ev_default_fork () +=item ev_loop_fork (loop) -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. +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 you are allowed to start or stop +watchers (except inside an C callback), but it makes most +sense after forking, in the child process. You I call it (or use +C) in the child before resuming or calling C. + +In addition, if you want to reuse a loop (via this function of +C), you I have to ignore C. + +Again, you I to call it on I loop that you want to re-use after +a fork, I. This is +because some kernel interfaces *cough* I *cough* do funny things +during fork. 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. +process if and only if you want to use the event loop in the child. If +you just fork+exec or create a new loop in the child, you don't have to +call it at all (in fact, C is so badly broken that it makes a +difference, but libev will usually detect this case on its own and do a +costly reset of the backend). 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 -quite nicely into a call to C: +it just in case after a fork. - pthread_atfork (0, 0, ev_default_fork); +Example: Automate calling C on the default loop when +using pthreads. -=item ev_loop_fork (loop) + static void + post_fork_child (void) + { + ev_loop_fork (EV_DEFAULT); + } -Like C, but acts on an event loop created by -C. Yes, you have to call this on every allocated event loop -after fork that you want to re-use in the child, and how you do this is -entirely your own problem. + ... + pthread_atfork (0, 0, post_fork_child); =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) +=item unsigned int ev_iteration (loop) -Returns the count of loop iterations for the loop, which is identical to -the number of times libev did poll for new events. It starts at C<0> and -happily wraps around with enough iterations. +Returns the current iteration count for the event loop, which is identical +to the number of times libev did poll for new events. It starts at C<0> +and happily wraps around with enough iterations. This value can sometimes be useful as a generation counter of sorts (it "ticks" the number of loop iterations), as it roughly corresponds with -C and C calls. +C and C calls - and is incremented between the +prepare and check phases. + +=item unsigned int ev_depth (loop) + +Returns the number of times C was entered minus the number of +times C was exited normally, in other words, the recursion depth. + +Outside C, this number is zero. In a callback, this number is +C<1>, unless C was invoked recursively (or from another thread), +in which case it is higher. + +Leaving C abnormally (setjmp/longjmp, cancelling the thread, +throwing an exception etc.), doesn't count as "exit" - consider this +as a hint to avoid such ungentleman-like behaviour unless it's really +convenient, in which case it is fully supported. =item unsigned int ev_backend (loop) @@ -640,20 +768,20 @@ 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. +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 L in the C section. +See also L in the C section. =item ev_suspend (loop) =item ev_resume (loop) -These two functions suspend and resume a loop, for use when the loop is -not used for a while and timeouts should not be processed. +These two functions suspend and resume an event loop, for use when the +loop is not used for a while and timeouts should not be processed. A typical use case would be an interactive program such as a game: When the user presses C<^Z> to suspend the game and resumes it an hour later it @@ -665,7 +793,7 @@ Effectively, all C watchers will be delayed by the time spend between C and C, and all C watchers will be rescheduled (that is, they will lose any events that would have -occured while suspended). +occurred while suspended). After calling C you B call I function on the given loop other than C, and you B call C @@ -674,28 +802,41 @@ Calling C/C has the side effect of updating the event loop time (see C). -=item ev_loop (loop, int flags) +=item bool ev_run (loop, int flags) Finally, this is it, the event handler. This function usually is called -after you initialised all your watchers and you want to start handling -events. +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. -If the flags argument is specified as C<0>, it will not return until -either no event watchers are active anymore or C was called. +If the flags argument is specified as C<0>, it will keep handling events +until either no event watchers are active anymore or C 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 again"). -Please note that an explicit C is usually better than +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, that is truly a thing of beauty. -A flags value of C will look for new events, will handle -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. +This function is I exception-safe - you can break out of a +C call by calling C in a callback, throwing a C++ +exception and so on. This does not decrement the C value, nor +will it clear any outstanding C breaks. + +A flags value of C will look for new events, will handle +those events and any already outstanding ones, but will not wait and +block your process in case there are no events and will return after one +iteration of the loop. This is sometimes useful to poll and handle new +events while doing lengthy calculations, to keep the program responsive. -A flags value of C will look for new events (waiting if +A flags value of C will look for new events (waiting if 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 @@ -704,55 +845,67 @@ 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 +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: +Here are the gory details of what C does (this is for your +understanding, not a guarantee that things will work exactly like this in +future versions): + - Increment loop depth. + - Reset the ev_break status. - Before the first iteration, call any pending watchers. - * If EVFLAG_FORKCHECK was used, check for a fork. + LOOP: + - 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 ev_break was called, goto FINISH. - 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" (ev_now ()). - Calculate for how long to sleep or block, if at all - (active idle watchers, EVLOOP_NONBLOCK or not having + (active idle watchers, EVRUN_NOWAIT or not having any active watchers at all will result in not sleeping). - Sleep if the I/O and timer collect interval say so. + - Increment loop iteration counter. - Block the process, waiting for any events. - Queue all outstanding I/O (fd) events. - 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 idle watchers with priority higher than that of pending events. - 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, or there are no active watchers, return, otherwise - continue with step *. + - If ev_break has been called, or EVRUN_ONCE or EVRUN_NOWAIT + were used, or there are no active watchers, goto FINISH, otherwise + continue with step LOOP. + FINISH: + - Reset the ev_break status iff it was EVBREAK_ONE. + - Decrement the loop depth. + - Return. 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 or somebody called unloop. yeah! + ev_run (my_loop, 0); + ... jobs done or somebody called break. yeah! -=item ev_unloop (loop, how) +=item ev_break (loop, how) -Can be used to make a call to C return early (but only after it +Can be used to make a call to C return early (but only after it has processed all outstanding events). The C argument must be either -C, which will make the innermost C call return, or -C, which will make all nested C calls return. +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. +This "break state" will be cleared on the next call to C. -It is safe to call C from otuside any C calls. +It is safe to call C from outside any C calls, too, in +which case it will have no effect. =item ev_ref (loop) @@ -760,14 +913,15 @@ 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. +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. +This is useful when you have a watcher that you never intend to +unregister, but that nevertheless should not keep C from +returning. In such a case, call C after starting, and C +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 +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 in the callback). -Example: Create a signal watcher, but keep it from keeping C +Example: Create a signal watcher, but keep it from keeping C running when nothing else is active. ev_signal exitsig; ev_signal_init (&exitsig, sig_cb, SIGINT); ev_signal_start (loop, &exitsig); - evf_unref (loop); + ev_unref (loop); Example: For some weird reason, unregister the above signal handler again. @@ -812,10 +966,11 @@ By setting a higher I you allow libev to spend more time collecting I/O events, so you can handle more events per iteration, at the cost of increasing latency. Timeouts (both C and -C) will be not affected. Setting this to a non-null value will +C) will not be affected. Setting this to a non-null value will introduce an additional C call into most loop iterations. The sleep time ensures that libev will not poll for I/O events more often then -once per this interval, on average. +once per this interval, on average (as long as the host time resolution is +good enough). Likewise, by setting a higher I you allow libev to spend more time collecting timeouts, at the expense of increased @@ -831,7 +986,7 @@ you do transactions with the outside world and you can't increase the parallelity, then this setting will limit your transaction rate (if you need to poll once per transaction and the I/O collect interval is 0.01, -then you can't do more than 100 transations per second). +then you can't do more than 100 transactions per second). Setting the I can improve the opportunity for saving power, as the program will "bundle" timer callback invocations that @@ -846,7 +1001,76 @@ ev_set_timeout_collect_interval (EV_DEFAULT_UC_ 0.1); ev_set_io_collect_interval (EV_DEFAULT_UC_ 0.01); -=item ev_loop_verify (loop) +=item ev_invoke_pending (loop) + +This call will simply invoke all pending watchers while resetting their +pending state. Normally, C does this automatically when required, +but when overriding the invoke callback this call comes handy. This +function can be invoked from a watcher - this can be useful for example +when you want to do some lengthy calculation and want to pass further +event handling to another thread (you still have to make sure only one +thread executes within C or C of course). + +=item int ev_pending_count (loop) + +Returns the number of pending watchers - zero indicates that no watchers +are pending. + +=item ev_set_invoke_pending_cb (loop, void (*invoke_pending_cb)(EV_P)) + +This overrides the invoke pending functionality of the loop: Instead of +invoking all pending watchers when there are any, C will call +this callback instead. This is useful, for example, when you want to +invoke the actual watchers inside another context (another thread etc.). + +If you want to reset the callback, use C as new +callback. + +=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 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 and C, another way is to set these +I and I callbacks on the loop. + +When set, then C will be called just before the thread is +suspended waiting for new events, and C is called just +afterwards. + +Ideally, C will just call your mutex_unlock function, and +C will just call the mutex_lock function again. + +While event loop modifications are allowed between invocations of +C and C (that's their only purpose after all), no +modifications done will affect the event loop, i.e. adding watchers will +have no effect on the set of file descriptors being watched, or the time +waited. Use an C watcher to wake up C when you want it +to take note of any changes you made. + +In theory, threads executing C will be async-cancel safe between +invocations of C and C. + +See also the locking example in the C section later in this +document. + +=item ev_set_userdata (loop, void *data) + +=item void *ev_userdata (loop) + +Set and retrieve a single C associated with a loop. When +C has never been called, then C returns +C<0>. + +These two functions can be used to associate arbitrary data with a loop, +and are intended solely for the C, C and +C 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 support has been compiled in, which is the default for non-minimal builds. It tries to go @@ -867,14 +1091,15 @@ watcher type, e.g. C can mean C for timer watchers and C for I/O watchers. -A watcher is a structure that you create and register to record your -interest in some event. For instance, if you want to wait for STDIN to -become readable, you would create an C watcher for that: +A watcher is an opaque structure that you allocate and register to record +your interest in some event. To make a concrete example, imagine you want +to wait for STDIN to become readable, you would create an C watcher +for that: static void my_cb (struct ev_loop *loop, ev_io *w, int revents) { ev_io_stop (w); - ev_unloop (loop, EVUNLOOP_ALL); + ev_break (loop, EVBREAK_ALL); } struct ev_loop *loop = ev_default_loop (0); @@ -885,7 +1110,7 @@ ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ); ev_io_start (loop, &stdin_watcher); - ev_loop (loop, 0); + ev_run (loop, 0); As you can see, you are responsible for allocating the memory for your watcher structures (and it is I a bad idea to do this on the @@ -894,11 +1119,11 @@ Each watcher has an associated watcher structure (called C or simply C, as typedefs are provided for all watcher structs). -Each watcher structure must be initialised by a call to C, which expects a callback to be provided. This -callback gets invoked each time the event occurs (or, in the case of I/O -watchers, each time the event loop detects that the file descriptor given -is readable and/or writable). +Each watcher structure must be initialised by a call to C, which expects a callback to be provided. This callback is +invoked each time the event occurs (or, in the case of I/O watchers, each +time the event loop detects that the file descriptor given is readable +and/or writable). Each watcher type further has its own C<< ev_TYPE_set (watcher *, ...) >> macro to configure it, with arguments specific to the watcher type. There @@ -931,7 +1156,7 @@ The file descriptor in the C watcher has become readable and/or writable. -=item C +=item C The C watcher has timed out. @@ -959,13 +1184,18 @@ =item C -All C watchers are invoked just I C starts -to gather new events, and all C watchers are invoked just after -C has gathered them, but before it invokes any callbacks for any -received events. 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 watcher might start an idle watcher to keep -C from blocking). +All C watchers are invoked just I C starts to +gather new events, and all C watchers are queued (not invoked) +just after C has gathered them, but before it queues any callbacks +for any received events. That means C watchers are the last +watchers invoked before the event loop sleeps or polls for new events, and +C 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 watcher might start an idle watcher to keep C from +blocking). =item C @@ -976,6 +1206,10 @@ The event loop has been resumed in the child process after fork (see C). +=item C + +The event loop is about to be destroyed (see C). + =item C The given async watcher has been asynchronously notified (see C). @@ -1031,7 +1265,7 @@ ev_init (&w, my_cb); ev_io_set (&w, STDIN_FILENO, EV_READ); -=item C (ev_TYPE *, [args]) +=item C (ev_TYPE *watcher, [args]) This macro initialises the type-specific parts of a watcher. You need to call C at least once before you call this macro, but you can @@ -1054,7 +1288,7 @@ ev_io_init (&w, my_cb, STDIN_FILENO, EV_READ); -=item C (loop *, ev_TYPE *watcher) +=item C (loop, ev_TYPE *watcher) Starts (activates) the given watcher. Only active watchers will receive events. If the watcher is already active nothing will happen. @@ -1064,7 +1298,7 @@ ev_io_start (EV_DEFAULT_UC, &w); -=item C (loop *, ev_TYPE *watcher) +=item C (loop, ev_TYPE *watcher) Stops the given watcher if active, and clears the pending status (whether the watcher was active or not). @@ -1094,12 +1328,12 @@ Returns the callback currently set on the watcher. -=item ev_cb_set (ev_TYPE *watcher, callback) +=item ev_set_cb (ev_TYPE *watcher, callback) Change the callback. You can change the callback at virtually any time (modulo threads). -=item ev_set_priority (ev_TYPE *watcher, priority) +=item ev_set_priority (ev_TYPE *watcher, int priority) =item int ev_priority (ev_TYPE *watcher) @@ -1122,7 +1356,7 @@ The default priority used by watchers when no priority has been set is always C<0>, which is supposed to not be too high and not be too low :). -See L, below, for a more thorough treatment of +See L, below, for a more thorough treatment of priorities. =item ev_invoke (loop, ev_TYPE *watcher, int revents) @@ -1141,73 +1375,86 @@ Sometimes it can be useful to "poll" a watcher instead of waiting for its callback to be invoked, which can be accomplished with this function. -=back +=item ev_feed_event (loop, ev_TYPE *watcher, int revents) +Feeds the given event set into the event loop, as if the specified event +had happened for the specified watcher (which must be a pointer to an +initialised but not necessarily started event watcher). Obviously you must +not free the watcher as long as it has pending events. -=head2 ASSOCIATING CUSTOM DATA WITH A WATCHER +Stopping the watcher, letting libev invoke it, or calling +C will clear the pending event, even if the watcher was +not started in the first place. -Each watcher has, by default, a member C that you can change -and read at any time: libev will completely ignore it. This can be used -to associate arbitrary data with your watcher. If you need more data and -don't want to allocate memory and store a pointer to it in that data -member, you can also "subclass" the watcher type and provide your own -data: +See also C and C for related +functions that do not need a watcher. - struct my_io - { - ev_io io; - int otherfd; - void *somedata; - struct whatever *mostinteresting; - }; +=back - ... - struct my_io w; - ev_io_init (&w.io, my_cb, fd, EV_READ); +See also the L and L idioms. -And since your callback will be called with a pointer to the watcher, you -can cast it back to your own type: +=head2 WATCHER STATES - static void my_cb (struct ev_loop *loop, ev_io *w_, int revents) - { - struct my_io *w = (struct my_io *)w_; - ... - } +There are various watcher states mentioned throughout this manual - +active, pending and so on. In this section these states and the rules to +transition between them will be described in more detail - and while these +rules might look complicated, they usually do "the right thing". -More interesting and less C-conformant ways of casting your callback type -instead have been omitted. +=over 4 -Another common scenario is to use some data structure with multiple -embedded watchers: +=item initialised - struct my_biggy - { - int some_data; - ev_timer t1; - ev_timer t2; - } +Before a watcher can be registered with the event loop it has to be +initialised. This can be done with a call to C, or calls to +C followed by the watcher-specific C function. + +In this state it is simply some block of memory that is suitable for +use in an event loop. It can be moved around, freed, reused etc. at +will - as long as you either keep the memory contents intact, or call +C again. + +=item started/running/active + +Once a watcher has been started with a call to C it becomes +property of the event loop, and is actively waiting for events. While in +this state it cannot be accessed (except in a few documented ways), moved, +freed or anything else - the only legal thing is to keep a pointer to it, +and call libev functions on it that are documented to work on active watchers. -In this case getting the pointer to C is a bit more -complicated: Either you store the address of your C struct -in the C member of the watcher (for woozies), or you need to use -some pointer arithmetic using C inside your watchers (for real -programmers): +=item pending - #include +If a watcher is active and libev determines that an event it is interested +in has occurred (such as a timer expiring), it will become pending. It will +stay in this pending state until either it is stopped or its callback is +about to be invoked, so it is not normally pending inside the watcher +callback. - static void - t1_cb (EV_P_ ev_timer *w, int revents) - { - struct my_biggy big = (struct my_biggy *) - (((char *)w) - offsetof (struct my_biggy, t1)); - } +The watcher might or might not be active while it is pending (for example, +an expired non-repeating timer can be pending but no longer active). If it +is stopped, it can be freely accessed (e.g. by calling C), +but it is still property of the event loop at this time, so cannot be +moved, freed or reused. And if it is active the rules described in the +previous item still apply. + +It is also possible to feed an event on a watcher that is not active (e.g. +via C), in which case it becomes pending without being +active. + +=item stopped + +A watcher can be stopped implicitly by libev (in which case it might still +be pending), or explicitly by calling its C function. The +latter will clear any pending state the watcher might be in, regardless +of whether it was active or not, so stopping a watcher explicitly before +freeing it is often a good idea. + +While stopped (and not pending) the watcher is essentially in the +initialised state, that is, it can be reused, moved, modified in any way +you wish (but when you trash the memory block, you need to C +it again). - static void - t2_cb (EV_P_ ev_timer *w, int revents) - { - struct my_biggy big = (struct my_biggy *) - (((char *)w) - offsetof (struct my_biggy, t2)); - } +=back =head2 WATCHER PRIORITY MODELS @@ -1260,7 +1507,7 @@ you can associate an C watcher to each such watcher, and in the normal watcher callback, you just start the idle watcher. The real processing is done in the idle watcher callback. This causes libev to -continously poll and process kernel event data for the watcher, but when +continuously poll and process kernel event data for the watcher, but when the lock-out case is known to be rare (which in turn is rare :), this is workable. @@ -1284,7 +1531,7 @@ // are not yet ready to handle it. ev_io_stop (EV_A_ w); - // start the idle watcher to ahndle the actual event. + // start the idle watcher to handle the actual event. // it will not be executed as long as other watchers // with the default priority are receiving events. ev_idle_start (EV_A_ &idle); @@ -1344,26 +1591,19 @@ descriptors to non-blocking mode is also usually a good idea (but not required if you know what you are doing). -If you cannot use non-blocking mode, then force the use of a -known-to-be-good backend (at the time of this writing, this includes only -C and C). The same applies to file -descriptors for which non-blocking operation makes no sense (such as -files) - libev doesn't guarentee any specific behaviour in that case. - Another thing you have to watch out for is that it is quite easy to -receive "spurious" readiness notifications, that is your callback might +receive "spurious" readiness notifications, that is, your callback might be called with C but a subsequent C(2) will actually block -because there is no data. Not only are some backends known to create a -lot of those (for example Solaris ports), it is very easy to get into -this situation even with a relatively standard program structure. Thus -it is best to always use non-blocking I/O: An extra C(2) returning -C is far preferable to a program hanging until some data arrives. +because there is no data. It is very easy to get into this situation even +with a relatively standard program structure. Thus it is best to always +use non-blocking I/O: An extra C(2) returning C is far +preferable to a program hanging until some data arrives. If you cannot run the fd in non-blocking mode (for example you should not play around with an Xlib connection), then you have to separately re-test whether a file descriptor is really ready with a known-to-be good -interface such as poll (fortunately in our Xlib example, Xlib already -does this on its own, so its quite safe to use). Some people additionally +interface such as poll (fortunately in the case of Xlib, it already does +this on its own, so its quite safe to use). Some people additionally use C and an interval timer, just to be sure you won't block indefinitely. @@ -1401,16 +1641,48 @@ for potentially C'ed file descriptors, or to resort to C or C. +=head3 The special problem of files + +Many people try to use C is buggy + +All that's left is C actively limits the number of file +descriptors you can pass in to 1024 - your program suddenly crashes when +you use more. + +There is an undocumented "workaround" for this - defining +C<_DARWIN_UNLIMITED_SELECT>, which libev tries to use, so select I +work on OS/X. + +=head2 SOLARIS PROBLEMS AND WORKAROUNDS + +=head3 C reentrancy + +The default compile environment on Solaris is unfortunately so +thread-unsafe that you can't even use components/libraries compiled +without C<-D_REENTRANT> in a threaded program, which, of course, isn't +defined by default. A valid, if stupid, implementation choice. + +If you want to use libev in threaded environments you have to make sure +it's compiled with C<_REENTRANT> defined. + +=head3 Event port backend + +The scalable event interface for Solaris is called "event +ports". Unfortunately, this mechanism is very buggy in all major +releases. If you run into high CPU usage, your program freezes or you get +a large number of spurious wakeups, make sure you have all the relevant +and latest kernel patches applied. No, I don't know which ones, but there +are multiple ones to apply, and afterwards, event ports actually work +great. + +If you can't get it to work, you can try running the program by setting +the environment variable C to only allow C and +C works fine +with large bitsets on AIX, and AIX is dead anyway. + =head2 WIN32 PLATFORM LIMITATIONS AND WORKAROUNDS +=head3 General issues + 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. +e.g. cygwin. Actually, it only applies to the microsofts own compilers, +as every compiler comes with a slightly differently broken/incompatible +environment. 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). +re-implementation of the I/O system. If you are into this kind of thing, +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. @@ -3982,9 +5242,7 @@ #include "evwrap.h" #include "ev.c" -=over 4 - -=item The winsocket select function +=head3 The winsocket C function doesn't follow POSIX in that it requires socket I and not socket I (it is @@ -4003,7 +5261,7 @@ Note that winsockets handling of fd sets is O(n), so you can easily get a complexity in the O(n²) range when using win32. -=item Limited number of file descriptors +=head3 Limited number of file descriptors Windows has numerous arbitrary (and low) limits on things. @@ -4028,8 +5286,6 @@ you need to wrap all I/O functions and provide your own fd management, but the cost of calling select (O(n²)) will likely make this unworkable. -=back - =head2 PORTABILITY REQUIREMENTS In addition to a working ISO-C implementation and of course the @@ -4046,6 +5302,11 @@ callback: The watcher callbacks have different type signatures, but libev calls them using an C internally. +=item pointer accesses must be thread-atomic + +Accessing a pointer value must be atomic, it must both be readable and +writable in one piece - this is the case on all current architectures. + =item C must be thread-atomic as well The type C (or whatever is defined as @@ -4063,8 +5324,8 @@ C could complicate things, however. The most portable way to handle signals is to block signals in all threads -except the initial one, and run the default loop in the initial thread as -well. +except the initial one, and run the signal handling loop in the initial +thread as well. =item C must be large enough for common memory allocation sizes @@ -4077,9 +5338,15 @@ =item C must hold a time value in seconds with enough accuracy The type C is used to represent timestamps. It is required to -have at least 51 bits of mantissa (and 9 bits of exponent), which is good -enough for at least into the year 4000. This requirement is fulfilled by -implementations implementing IEEE 754 (basically all existing ones). +have at least 51 bits of mantissa (and 9 bits of exponent), which is +good enough for at least into the year 4000 with millisecond accuracy +(the design goal for libev). This requirement is overfulfilled by +implementations using IEEE 754, which is basically all existing ones. + +With IEEE 754 doubles, you get microsecond accuracy until at least the +year 2255 (and millisecond accuracy till the year 287396 - by then, libev +is either obsolete or somebody patched it to use C or +something like that, just kidding). =back @@ -4151,8 +5418,69 @@ =item Processing signals: O(max_signal_number) Sending involves a system call I there were no other C -calls in the current loop iteration. Checking for async and signal events -involves iterating over all running async watchers or all signal numbers. +calls in the current loop iteration and the loop is currently +blocked. Checking for async and signal events involves iterating over all +running async watchers or all signal numbers. + +=back + + +=head1 PORTING FROM LIBEV 3.X TO 4.X + +The major version 4 introduced some incompatible changes to the API. + +At the moment, the C header file provides compatibility definitions +for all changes, so most programs should still compile. The compatibility +layer might be removed in later versions of libev, so better update to the +new API early than late. + +=over 4 + +=item C backwards compatibility mechanism + +The backward compatibility mechanism can be controlled by +C. See L in the L +section. + +=item C and C have been removed + +These calls can be replaced easily by their C counterparts: + + ev_loop_destroy (EV_DEFAULT_UC); + ev_loop_fork (EV_DEFAULT); + +=item function/symbol renames + +A number of functions and symbols have been renamed: + + ev_loop => ev_run + EVLOOP_NONBLOCK => EVRUN_NOWAIT + EVLOOP_ONESHOT => EVRUN_ONCE + + ev_unloop => ev_break + EVUNLOOP_CANCEL => EVBREAK_CANCEL + EVUNLOOP_ONE => EVBREAK_ONE + EVUNLOOP_ALL => EVBREAK_ALL + + EV_TIMEOUT => EV_TIMER + + ev_loop_count => ev_iteration + ev_loop_depth => ev_depth + ev_loop_verify => ev_verify + +Most functions working on C objects don't have an +C prefix, so it was removed; C, C and +associated constants have been renamed to not collide with the C anymore and C now follows the same naming scheme +as all other watcher types. Note that C is still called +C because it would otherwise clash with the C +typedef. + +=item C mechanism replaced by C + +The preprocessor symbol C has been replaced by a different +mechanism, C. Programs using C usually compile +and work, but the library code will of course be larger. =back @@ -4163,20 +5491,24 @@ =item active -A watcher is active as long as it has been started (has been attached to -an event loop) but not yet stopped (disassociated from the event loop). +A watcher is active as long as it has been started and not yet stopped. +See L for details. =item application In this document, an application is whatever is using libev. +=item backend + +The part of the code dealing with the operating system interfaces. + =item callback The address of a function that is called when some event has been detected. Callbacks are being passed the event loop, the watcher that received the event, and the actual event bitset. -=item callback invocation +=item callback/watcher invocation The act of calling the callback associated with a watcher. @@ -4187,7 +5519,7 @@ any other events happening anymore. In libev, events are represented as single bits (such as C or -C). +C). =item event library @@ -4205,12 +5537,8 @@ =item pending -A watcher is pending as soon as the corresponding event has been detected, -and stops being pending as soon as the watcher will be invoked or its -pending status is explicitly cleared by the application. - -A watcher can be pending, but not active. Stopping a watcher also clears -its pending status. +A watcher is pending as soon as the corresponding event has been +detected. See L for details. =item real time @@ -4219,7 +5547,7 @@ =item wall-clock time The time and date as shown on clocks. Unlike real time, it can actually -be wrong and jump forwards and backwards, e.g. when the you adjust your +be wrong and jump forwards and backwards, e.g. when you adjust your clock. =item watcher @@ -4227,13 +5555,10 @@ A data structure that describes interest in certain events. Watchers need to be started (attached to an event loop) before they can receive events. -=item watcher invocation - -The act of calling the callback associated with a watcher. - =back =head1 AUTHOR -Marc Lehmann , with repeated corrections by Mikael Magnusson. +Marc Lehmann , with repeated corrections by Mikael +Magnusson and Emanuele Giaquinta, and minor corrections by many others.