ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/libev/ev.pod
(Generate patch)

Comparing libev/ev.pod (file contents):
Revision 1.185 by root, Tue Sep 23 09:13:59 2008 UTC vs.
Revision 1.206 by root, Tue Oct 28 12:31:38 2008 UTC

10 10
11 // a single header file is required 11 // a single header file is required
12 #include <ev.h> 12 #include <ev.h>
13 13
14 // every watcher type has its own typedef'd struct 14 // every watcher type has its own typedef'd struct
15 // with the name ev_<type> 15 // with the name ev_TYPE
16 ev_io stdin_watcher; 16 ev_io stdin_watcher;
17 ev_timer timeout_watcher; 17 ev_timer timeout_watcher;
18 18
19 // all watcher callbacks have a similar signature 19 // all watcher callbacks have a similar signature
20 // this callback is called when data is readable on stdin 20 // this callback is called when data is readable on stdin
21 static void 21 static void
22 stdin_cb (EV_P_ struct ev_io *w, int revents) 22 stdin_cb (EV_P_ ev_io *w, int revents)
23 { 23 {
24 puts ("stdin ready"); 24 puts ("stdin ready");
25 // for one-shot events, one must manually stop the watcher 25 // for one-shot events, one must manually stop the watcher
26 // with its corresponding stop function. 26 // with its corresponding stop function.
27 ev_io_stop (EV_A_ w); 27 ev_io_stop (EV_A_ w);
30 ev_unloop (EV_A_ EVUNLOOP_ALL); 30 ev_unloop (EV_A_ EVUNLOOP_ALL);
31 } 31 }
32 32
33 // another callback, this time for a time-out 33 // another callback, this time for a time-out
34 static void 34 static void
35 timeout_cb (EV_P_ struct ev_timer *w, int revents) 35 timeout_cb (EV_P_ ev_timer *w, int revents)
36 { 36 {
37 puts ("timeout"); 37 puts ("timeout");
38 // this causes the innermost ev_loop to stop iterating 38 // this causes the innermost ev_loop to stop iterating
39 ev_unloop (EV_A_ EVUNLOOP_ONE); 39 ev_unloop (EV_A_ EVUNLOOP_ONE);
40 } 40 }
41 41
42 int 42 int
43 main (void) 43 main (void)
44 { 44 {
45 // use the default event loop unless you have special needs 45 // use the default event loop unless you have special needs
46 struct ev_loop *loop = ev_default_loop (0); 46 ev_loop *loop = ev_default_loop (0);
47 47
48 // initialise an io watcher, then start it 48 // initialise an io watcher, then start it
49 // this one will watch for stdin to become readable 49 // this one will watch for stdin to become readable
50 ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ); 50 ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ);
51 ev_io_start (loop, &stdin_watcher); 51 ev_io_start (loop, &stdin_watcher);
103Libev is very configurable. In this manual the default (and most common) 103Libev is very configurable. In this manual the default (and most common)
104configuration will be described, which supports multiple event loops. For 104configuration will be described, which supports multiple event loops. For
105more info about various configuration options please have a look at 105more info about various configuration options please have a look at
106B<EMBED> section in this manual. If libev was configured without support 106B<EMBED> section in this manual. If libev was configured without support
107for multiple event loops, then all functions taking an initial argument of 107for multiple event loops, then all functions taking an initial argument of
108name C<loop> (which is always of type C<struct ev_loop *>) will not have 108name C<loop> (which is always of type C<ev_loop *>) will not have
109this argument. 109this argument.
110 110
111=head2 TIME REPRESENTATION 111=head2 TIME REPRESENTATION
112 112
113Libev represents time as a single floating point number, representing the 113Libev represents time as a single floating point number, representing the
214C<ev_embeddable_backends () & ev_supported_backends ()>, likewise for 214C<ev_embeddable_backends () & ev_supported_backends ()>, likewise for
215recommended ones. 215recommended ones.
216 216
217See the description of C<ev_embed> watchers for more info. 217See the description of C<ev_embed> watchers for more info.
218 218
219=item ev_set_allocator (void *(*cb)(void *ptr, long size)) 219=item ev_set_allocator (void *(*cb)(void *ptr, long size)) [NOT REENTRANT]
220 220
221Sets the allocation function to use (the prototype is similar - the 221Sets the allocation function to use (the prototype is similar - the
222semantics are identical to the C<realloc> C89/SuS/POSIX function). It is 222semantics are identical to the C<realloc> C89/SuS/POSIX function). It is
223used to allocate and free memory (no surprises here). If it returns zero 223used to allocate and free memory (no surprises here). If it returns zero
224when memory needs to be allocated (C<size != 0>), the library might abort 224when memory needs to be allocated (C<size != 0>), the library might abort
250 } 250 }
251 251
252 ... 252 ...
253 ev_set_allocator (persistent_realloc); 253 ev_set_allocator (persistent_realloc);
254 254
255=item ev_set_syserr_cb (void (*cb)(const char *msg)); 255=item ev_set_syserr_cb (void (*cb)(const char *msg)); [NOT REENTRANT]
256 256
257Set the callback function to call on a retryable system call error (such 257Set the callback function to call on a retryable system call error (such
258as failed select, poll, epoll_wait). The message is a printable string 258as failed select, poll, epoll_wait). The message is a printable string
259indicating the system call or subsystem causing the problem. If this 259indicating the system call or subsystem causing the problem. If this
260callback is set, then libev will expect it to remedy the situation, no 260callback is set, then libev will expect it to remedy the situation, no
276 276
277=back 277=back
278 278
279=head1 FUNCTIONS CONTROLLING THE EVENT LOOP 279=head1 FUNCTIONS CONTROLLING THE EVENT LOOP
280 280
281An event loop is described by a C<struct ev_loop *>. The library knows two 281An event loop is described by a C<struct ev_loop *> (the C<struct>
282types of such loops, the I<default> loop, which supports signals and child 282is I<not> optional in this case, as there is also an C<ev_loop>
283events, and dynamically created loops which do not. 283I<function>).
284
285The library knows two types of such loops, the I<default> loop, which
286supports signals and child events, and dynamically created loops which do
287not.
284 288
285=over 4 289=over 4
286 290
287=item struct ev_loop *ev_default_loop (unsigned int flags) 291=item struct ev_loop *ev_default_loop (unsigned int flags)
288 292
380=item C<EVBACKEND_EPOLL> (value 4, Linux) 384=item C<EVBACKEND_EPOLL> (value 4, Linux)
381 385
382For few fds, this backend is a bit little slower than poll and select, 386For few fds, this backend is a bit little slower than poll and select,
383but it scales phenomenally better. While poll and select usually scale 387but it scales phenomenally better. While poll and select usually scale
384like O(total_fds) where n is the total number of fds (or the highest fd), 388like O(total_fds) where n is the total number of fds (or the highest fd),
385epoll scales either O(1) or O(active_fds). The epoll design has a number 389epoll scales either O(1) or O(active_fds).
386of shortcomings, such as silently dropping events in some hard-to-detect 390
387cases and requiring a system call per fd change, no fork support and bad 391The epoll syscalls are the most misdesigned of the more advanced event
388support for dup. 392mechanisms: problems include silently dropping fds, requiring a system
393call per change per fd (and unnecessary guessing of parameters), problems
394with dup and so on. The biggest issue is fork races, however - if a
395program forks then I<both> parent and child process have to recreate the
396epoll set, which can take considerable time (one syscall per fd) and is of
397course hard to detect.
398
399Epoll is also notoriously buggy - embedding epoll fds should work, but
400of course doesn't, and epoll just loves to report events for totally
401I<different> file descriptors (even already closed ones, so one cannot
402even remove them from the set) than registered in the set (especially
403on SMP systems). Libev tries to counter these spurious notifications by
404employing an additional generation counter and comparing that against the
405events to filter out spurious ones.
389 406
390While stopping, setting and starting an I/O watcher in the same iteration 407While stopping, setting and starting an I/O watcher in the same iteration
391will result in some caching, there is still a system call per such incident 408will result in some caching, there is still a system call per such incident
392(because the fd could point to a different file description now), so its 409(because the fd could point to a different file description now), so its
393best to avoid that. Also, C<dup ()>'ed file descriptors might not work 410best to avoid that. Also, C<dup ()>'ed file descriptors might not work
394very well if you register events for both fds. 411very well if you register events for both fds.
395 412
396Please note that epoll sometimes generates spurious notifications, so you
397need to use non-blocking I/O or other means to avoid blocking when no data
398(or space) is available.
399
400Best performance from this backend is achieved by not unregistering all 413Best performance from this backend is achieved by not unregistering all
401watchers for a file descriptor until it has been closed, if possible, 414watchers for a file descriptor until it has been closed, if possible,
402i.e. keep at least one watcher active per fd at all times. Stopping and 415i.e. keep at least one watcher active per fd at all times. Stopping and
403starting a watcher (without re-setting it) also usually doesn't cause 416starting a watcher (without re-setting it) also usually doesn't cause
404extra overhead. 417extra overhead. A fork can both result in spurious notifications as well
418as in libev having to destroy and recreate the epoll object, which can
419take considerable time and thus should be avoided.
405 420
406While nominally embeddable in other event loops, this feature is broken in 421While nominally embeddable in other event loops, this feature is broken in
407all kernel versions tested so far. 422all kernel versions tested so far.
408 423
409This backend maps C<EV_READ> and C<EV_WRITE> in the same way as 424This backend maps C<EV_READ> and C<EV_WRITE> in the same way as
424 439
425It scales in the same way as the epoll backend, but the interface to the 440It scales in the same way as the epoll backend, but the interface to the
426kernel is more efficient (which says nothing about its actual speed, of 441kernel is more efficient (which says nothing about its actual speed, of
427course). While stopping, setting and starting an I/O watcher does never 442course). While stopping, setting and starting an I/O watcher does never
428cause an extra system call as with C<EVBACKEND_EPOLL>, it still adds up to 443cause an extra system call as with C<EVBACKEND_EPOLL>, it still adds up to
429two event changes per incident. Support for C<fork ()> is very bad and it 444two event changes per incident. Support for C<fork ()> is very bad (but
430drops fds silently in similarly hard-to-detect cases. 445sane, unlike epoll) and it drops fds silently in similarly hard-to-detect
446cases
431 447
432This backend usually performs well under most conditions. 448This backend usually performs well under most conditions.
433 449
434While nominally embeddable in other event loops, this doesn't work 450While nominally embeddable in other event loops, this doesn't work
435everywhere, so you might need to test for this. And since it is broken 451everywhere, so you might need to test for this. And since it is broken
464might perform better. 480might perform better.
465 481
466On the positive side, with the exception of the spurious readiness 482On the positive side, with the exception of the spurious readiness
467notifications, this backend actually performed fully to specification 483notifications, this backend actually performed fully to specification
468in all tests and is fully embeddable, which is a rare feat among the 484in all tests and is fully embeddable, which is a rare feat among the
469OS-specific backends. 485OS-specific backends (I vastly prefer correctness over speed hacks).
470 486
471This backend maps C<EV_READ> and C<EV_WRITE> in the same way as 487This backend maps C<EV_READ> and C<EV_WRITE> in the same way as
472C<EVBACKEND_POLL>. 488C<EVBACKEND_POLL>.
473 489
474=item C<EVBACKEND_ALL> 490=item C<EVBACKEND_ALL>
527responsibility to either stop all watchers cleanly yourself I<before> 543responsibility to either stop all watchers cleanly yourself I<before>
528calling this function, or cope with the fact afterwards (which is usually 544calling this function, or cope with the fact afterwards (which is usually
529the easiest thing, you can just ignore the watchers and/or C<free ()> them 545the easiest thing, you can just ignore the watchers and/or C<free ()> them
530for example). 546for example).
531 547
532Note that certain global state, such as signal state, will not be freed by 548Note that certain global state, such as signal state (and installed signal
533this function, and related watchers (such as signal and child watchers) 549handlers), will not be freed by this function, and related watchers (such
534would need to be stopped manually. 550as signal and child watchers) would need to be stopped manually.
535 551
536In general it is not advisable to call this function except in the 552In general it is not advisable to call this function except in the
537rare occasion where you really need to free e.g. the signal handling 553rare occasion where you really need to free e.g. the signal handling
538pipe fds. If you need dynamically allocated loops it is better to use 554pipe fds. If you need dynamically allocated loops it is better to use
539C<ev_loop_new> and C<ev_loop_destroy>). 555C<ev_loop_new> and C<ev_loop_destroy>).
685C<EVUNLOOP_ONE>, which will make the innermost C<ev_loop> call return, or 701C<EVUNLOOP_ONE>, which will make the innermost C<ev_loop> call return, or
686C<EVUNLOOP_ALL>, which will make all nested C<ev_loop> calls return. 702C<EVUNLOOP_ALL>, which will make all nested C<ev_loop> calls return.
687 703
688This "unloop state" will be cleared when entering C<ev_loop> again. 704This "unloop state" will be cleared when entering C<ev_loop> again.
689 705
706It is safe to call C<ev_unloop> from otuside any C<ev_loop> calls.
707
690=item ev_ref (loop) 708=item ev_ref (loop)
691 709
692=item ev_unref (loop) 710=item ev_unref (loop)
693 711
694Ref/unref can be used to add or remove a reference count on the event 712Ref/unref can be used to add or remove a reference count on the event
708respectively). 726respectively).
709 727
710Example: Create a signal watcher, but keep it from keeping C<ev_loop> 728Example: Create a signal watcher, but keep it from keeping C<ev_loop>
711running when nothing else is active. 729running when nothing else is active.
712 730
713 struct ev_signal exitsig; 731 ev_signal exitsig;
714 ev_signal_init (&exitsig, sig_cb, SIGINT); 732 ev_signal_init (&exitsig, sig_cb, SIGINT);
715 ev_signal_start (loop, &exitsig); 733 ev_signal_start (loop, &exitsig);
716 evf_unref (loop); 734 evf_unref (loop);
717 735
718Example: For some weird reason, unregister the above signal handler again. 736Example: For some weird reason, unregister the above signal handler again.
766they fire on, say, one-second boundaries only. 784they fire on, say, one-second boundaries only.
767 785
768=item ev_loop_verify (loop) 786=item ev_loop_verify (loop)
769 787
770This function only does something when C<EV_VERIFY> support has been 788This function only does something when C<EV_VERIFY> support has been
771compiled in. which is the default for non-minimal builds. It tries to go 789compiled in, which is the default for non-minimal builds. It tries to go
772through all internal structures and checks them for validity. If anything 790through all internal structures and checks them for validity. If anything
773is found to be inconsistent, it will print an error message to standard 791is found to be inconsistent, it will print an error message to standard
774error and call C<abort ()>. 792error and call C<abort ()>.
775 793
776This can be used to catch bugs inside libev itself: under normal 794This can be used to catch bugs inside libev itself: under normal
780=back 798=back
781 799
782 800
783=head1 ANATOMY OF A WATCHER 801=head1 ANATOMY OF A WATCHER
784 802
803In the following description, uppercase C<TYPE> in names stands for the
804watcher type, e.g. C<ev_TYPE_start> can mean C<ev_timer_start> for timer
805watchers and C<ev_io_start> for I/O watchers.
806
785A watcher is a structure that you create and register to record your 807A watcher is a structure that you create and register to record your
786interest in some event. For instance, if you want to wait for STDIN to 808interest in some event. For instance, if you want to wait for STDIN to
787become readable, you would create an C<ev_io> watcher for that: 809become readable, you would create an C<ev_io> watcher for that:
788 810
789 static void my_cb (struct ev_loop *loop, struct ev_io *w, int revents) 811 static void my_cb (struct ev_loop *loop, ev_io *w, int revents)
790 { 812 {
791 ev_io_stop (w); 813 ev_io_stop (w);
792 ev_unloop (loop, EVUNLOOP_ALL); 814 ev_unloop (loop, EVUNLOOP_ALL);
793 } 815 }
794 816
795 struct ev_loop *loop = ev_default_loop (0); 817 struct ev_loop *loop = ev_default_loop (0);
818
796 struct ev_io stdin_watcher; 819 ev_io stdin_watcher;
820
797 ev_init (&stdin_watcher, my_cb); 821 ev_init (&stdin_watcher, my_cb);
798 ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ); 822 ev_io_set (&stdin_watcher, STDIN_FILENO, EV_READ);
799 ev_io_start (loop, &stdin_watcher); 823 ev_io_start (loop, &stdin_watcher);
824
800 ev_loop (loop, 0); 825 ev_loop (loop, 0);
801 826
802As you can see, you are responsible for allocating the memory for your 827As you can see, you are responsible for allocating the memory for your
803watcher structures (and it is usually a bad idea to do this on the stack, 828watcher structures (and it is I<usually> a bad idea to do this on the
804although this can sometimes be quite valid). 829stack).
830
831Each watcher has an associated watcher structure (called C<struct ev_TYPE>
832or simply C<ev_TYPE>, as typedefs are provided for all watcher structs).
805 833
806Each watcher structure must be initialised by a call to C<ev_init 834Each watcher structure must be initialised by a call to C<ev_init
807(watcher *, callback)>, which expects a callback to be provided. This 835(watcher *, callback)>, which expects a callback to be provided. This
808callback gets invoked each time the event occurs (or, in the case of I/O 836callback gets invoked each time the event occurs (or, in the case of I/O
809watchers, each time the event loop detects that the file descriptor given 837watchers, each time the event loop detects that the file descriptor given
810is readable and/or writable). 838is readable and/or writable).
811 839
812Each watcher type has its own C<< ev_<type>_set (watcher *, ...) >> macro 840Each watcher type further has its own C<< ev_TYPE_set (watcher *, ...) >>
813with arguments specific to this watcher type. There is also a macro 841macro to configure it, with arguments specific to the watcher type. There
814to combine initialisation and setting in one call: C<< ev_<type>_init 842is also a macro to combine initialisation and setting in one call: C<<
815(watcher *, callback, ...) >>. 843ev_TYPE_init (watcher *, callback, ...) >>.
816 844
817To make the watcher actually watch out for events, you have to start it 845To make the watcher actually watch out for events, you have to start it
818with a watcher-specific start function (C<< ev_<type>_start (loop, watcher 846with a watcher-specific start function (C<< ev_TYPE_start (loop, watcher
819*) >>), and you can stop watching for events at any time by calling the 847*) >>), and you can stop watching for events at any time by calling the
820corresponding stop function (C<< ev_<type>_stop (loop, watcher *) >>. 848corresponding stop function (C<< ev_TYPE_stop (loop, watcher *) >>.
821 849
822As long as your watcher is active (has been started but not stopped) you 850As long as your watcher is active (has been started but not stopped) you
823must not touch the values stored in it. Most specifically you must never 851must not touch the values stored in it. Most specifically you must never
824reinitialise it or call its C<set> macro. 852reinitialise it or call its C<ev_TYPE_set> macro.
825 853
826Each and every callback receives the event loop pointer as first, the 854Each and every callback receives the event loop pointer as first, the
827registered watcher structure as second, and a bitset of received events as 855registered watcher structure as second, and a bitset of received events as
828third argument. 856third argument.
829 857
892=item C<EV_ERROR> 920=item C<EV_ERROR>
893 921
894An unspecified error has occurred, the watcher has been stopped. This might 922An unspecified error has occurred, the watcher has been stopped. This might
895happen because the watcher could not be properly started because libev 923happen because the watcher could not be properly started because libev
896ran out of memory, a file descriptor was found to be closed or any other 924ran out of memory, a file descriptor was found to be closed or any other
925problem. Libev considers these application bugs.
926
897problem. You best act on it by reporting the problem and somehow coping 927You best act on it by reporting the problem and somehow coping with the
898with the watcher being stopped. 928watcher being stopped. Note that well-written programs should not receive
929an error ever, so when your watcher receives it, this usually indicates a
930bug in your program.
899 931
900Libev will usually signal a few "dummy" events together with an error, for 932Libev will usually signal a few "dummy" events together with an error, for
901example it might indicate that a fd is readable or writable, and if your 933example it might indicate that a fd is readable or writable, and if your
902callbacks is well-written it can just attempt the operation and cope with 934callbacks is well-written it can just attempt the operation and cope with
903the error from read() or write(). This will not work in multi-threaded 935the error from read() or write(). This will not work in multi-threaded
906 938
907=back 939=back
908 940
909=head2 GENERIC WATCHER FUNCTIONS 941=head2 GENERIC WATCHER FUNCTIONS
910 942
911In the following description, C<TYPE> stands for the watcher type,
912e.g. C<timer> for C<ev_timer> watchers and C<io> for C<ev_io> watchers.
913
914=over 4 943=over 4
915 944
916=item C<ev_init> (ev_TYPE *watcher, callback) 945=item C<ev_init> (ev_TYPE *watcher, callback)
917 946
918This macro initialises the generic portion of a watcher. The contents 947This macro initialises the generic portion of a watcher. The contents
923which rolls both calls into one. 952which rolls both calls into one.
924 953
925You can reinitialise a watcher at any time as long as it has been stopped 954You can reinitialise a watcher at any time as long as it has been stopped
926(or never started) and there are no pending events outstanding. 955(or never started) and there are no pending events outstanding.
927 956
928The callback is always of type C<void (*)(ev_loop *loop, ev_TYPE *watcher, 957The callback is always of type C<void (*)(struct ev_loop *loop, ev_TYPE *watcher,
929int revents)>. 958int revents)>.
930 959
931Example: Initialise an C<ev_io> watcher in two steps. 960Example: Initialise an C<ev_io> watcher in two steps.
932 961
933 ev_io w; 962 ev_io w;
967 996
968 ev_io_start (EV_DEFAULT_UC, &w); 997 ev_io_start (EV_DEFAULT_UC, &w);
969 998
970=item C<ev_TYPE_stop> (loop *, ev_TYPE *watcher) 999=item C<ev_TYPE_stop> (loop *, ev_TYPE *watcher)
971 1000
972Stops the given watcher again (if active) and clears the pending 1001Stops the given watcher if active, and clears the pending status (whether
1002the watcher was active or not).
1003
973status. It is possible that stopped watchers are pending (for example, 1004It is possible that stopped watchers are pending - for example,
974non-repeating timers are being stopped when they become pending), but 1005non-repeating timers are being stopped when they become pending - but
975C<ev_TYPE_stop> ensures that the watcher is neither active nor pending. If 1006calling C<ev_TYPE_stop> ensures that the watcher is neither active nor
976you want to free or reuse the memory used by the watcher it is therefore a 1007pending. If you want to free or reuse the memory used by the watcher it is
977good idea to always call its C<ev_TYPE_stop> function. 1008therefore a good idea to always call its C<ev_TYPE_stop> function.
978 1009
979=item bool ev_is_active (ev_TYPE *watcher) 1010=item bool ev_is_active (ev_TYPE *watcher)
980 1011
981Returns a true value iff the watcher is active (i.e. it has been started 1012Returns a true value iff the watcher is active (i.e. it has been started
982and not yet been stopped). As long as a watcher is active you must not modify 1013and not yet been stopped). As long as a watcher is active you must not modify
1024The default priority used by watchers when no priority has been set is 1055The default priority used by watchers when no priority has been set is
1025always C<0>, which is supposed to not be too high and not be too low :). 1056always C<0>, which is supposed to not be too high and not be too low :).
1026 1057
1027Setting a priority outside the range of C<EV_MINPRI> to C<EV_MAXPRI> is 1058Setting a priority outside the range of C<EV_MINPRI> to C<EV_MAXPRI> is
1028fine, as long as you do not mind that the priority value you query might 1059fine, as long as you do not mind that the priority value you query might
1029or might not have been adjusted to be within valid range. 1060or might not have been clamped to the valid range.
1030 1061
1031=item ev_invoke (loop, ev_TYPE *watcher, int revents) 1062=item ev_invoke (loop, ev_TYPE *watcher, int revents)
1032 1063
1033Invoke the C<watcher> with the given C<loop> and C<revents>. Neither 1064Invoke the C<watcher> with the given C<loop> and C<revents>. Neither
1034C<loop> nor C<revents> need to be valid as long as the watcher callback 1065C<loop> nor C<revents> need to be valid as long as the watcher callback
1056member, you can also "subclass" the watcher type and provide your own 1087member, you can also "subclass" the watcher type and provide your own
1057data: 1088data:
1058 1089
1059 struct my_io 1090 struct my_io
1060 { 1091 {
1061 struct ev_io io; 1092 ev_io io;
1062 int otherfd; 1093 int otherfd;
1063 void *somedata; 1094 void *somedata;
1064 struct whatever *mostinteresting; 1095 struct whatever *mostinteresting;
1065 }; 1096 };
1066 1097
1069 ev_io_init (&w.io, my_cb, fd, EV_READ); 1100 ev_io_init (&w.io, my_cb, fd, EV_READ);
1070 1101
1071And since your callback will be called with a pointer to the watcher, you 1102And since your callback will be called with a pointer to the watcher, you
1072can cast it back to your own type: 1103can cast it back to your own type:
1073 1104
1074 static void my_cb (struct ev_loop *loop, struct ev_io *w_, int revents) 1105 static void my_cb (struct ev_loop *loop, ev_io *w_, int revents)
1075 { 1106 {
1076 struct my_io *w = (struct my_io *)w_; 1107 struct my_io *w = (struct my_io *)w_;
1077 ... 1108 ...
1078 } 1109 }
1079 1110
1097programmers): 1128programmers):
1098 1129
1099 #include <stddef.h> 1130 #include <stddef.h>
1100 1131
1101 static void 1132 static void
1102 t1_cb (EV_P_ struct ev_timer *w, int revents) 1133 t1_cb (EV_P_ ev_timer *w, int revents)
1103 { 1134 {
1104 struct my_biggy big = (struct my_biggy * 1135 struct my_biggy big = (struct my_biggy *
1105 (((char *)w) - offsetof (struct my_biggy, t1)); 1136 (((char *)w) - offsetof (struct my_biggy, t1));
1106 } 1137 }
1107 1138
1108 static void 1139 static void
1109 t2_cb (EV_P_ struct ev_timer *w, int revents) 1140 t2_cb (EV_P_ ev_timer *w, int revents)
1110 { 1141 {
1111 struct my_biggy big = (struct my_biggy * 1142 struct my_biggy big = (struct my_biggy *
1112 (((char *)w) - offsetof (struct my_biggy, t2)); 1143 (((char *)w) - offsetof (struct my_biggy, t2));
1113 } 1144 }
1114 1145
1249Example: Call C<stdin_readable_cb> when STDIN_FILENO has become, well 1280Example: Call C<stdin_readable_cb> when STDIN_FILENO has become, well
1250readable, but only once. Since it is likely line-buffered, you could 1281readable, but only once. Since it is likely line-buffered, you could
1251attempt to read a whole line in the callback. 1282attempt to read a whole line in the callback.
1252 1283
1253 static void 1284 static void
1254 stdin_readable_cb (struct ev_loop *loop, struct ev_io *w, int revents) 1285 stdin_readable_cb (struct ev_loop *loop, ev_io *w, int revents)
1255 { 1286 {
1256 ev_io_stop (loop, w); 1287 ev_io_stop (loop, w);
1257 .. read from stdin here (or from w->fd) and handle any I/O errors 1288 .. read from stdin here (or from w->fd) and handle any I/O errors
1258 } 1289 }
1259 1290
1260 ... 1291 ...
1261 struct ev_loop *loop = ev_default_init (0); 1292 struct ev_loop *loop = ev_default_init (0);
1262 struct ev_io stdin_readable; 1293 ev_io stdin_readable;
1263 ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ); 1294 ev_io_init (&stdin_readable, stdin_readable_cb, STDIN_FILENO, EV_READ);
1264 ev_io_start (loop, &stdin_readable); 1295 ev_io_start (loop, &stdin_readable);
1265 ev_loop (loop, 0); 1296 ev_loop (loop, 0);
1266 1297
1267 1298
1278 1309
1279The callback is guaranteed to be invoked only I<after> its timeout has 1310The callback is guaranteed to be invoked only I<after> its timeout has
1280passed, but if multiple timers become ready during the same loop iteration 1311passed, but if multiple timers become ready during the same loop iteration
1281then order of execution is undefined. 1312then order of execution is undefined.
1282 1313
1314=head3 Be smart about timeouts
1315
1316Many real-world problems involve some kind of timeout, usually for error
1317recovery. A typical example is an HTTP request - if the other side hangs,
1318you want to raise some error after a while.
1319
1320What follows are some ways to handle this problem, from obvious and
1321inefficient to smart and efficient.
1322
1323In the following, a 60 second activity timeout is assumed - a timeout that
1324gets reset to 60 seconds each time there is activity (e.g. each time some
1325data or other life sign was received).
1326
1327=over 4
1328
1329=item 1. Use a timer and stop, reinitialise and start it on activity.
1330
1331This is the most obvious, but not the most simple way: In the beginning,
1332start the watcher:
1333
1334 ev_timer_init (timer, callback, 60., 0.);
1335 ev_timer_start (loop, timer);
1336
1337Then, each time there is some activity, C<ev_timer_stop> it, initialise it
1338and start it again:
1339
1340 ev_timer_stop (loop, timer);
1341 ev_timer_set (timer, 60., 0.);
1342 ev_timer_start (loop, timer);
1343
1344This is relatively simple to implement, but means that each time there is
1345some activity, libev will first have to remove the timer from its internal
1346data structure and then add it again. Libev tries to be fast, but it's
1347still not a constant-time operation.
1348
1349=item 2. Use a timer and re-start it with C<ev_timer_again> inactivity.
1350
1351This is the easiest way, and involves using C<ev_timer_again> instead of
1352C<ev_timer_start>.
1353
1354To implement this, configure an C<ev_timer> with a C<repeat> value
1355of C<60> and then call C<ev_timer_again> at start and each time you
1356successfully read or write some data. If you go into an idle state where
1357you do not expect data to travel on the socket, you can C<ev_timer_stop>
1358the timer, and C<ev_timer_again> will automatically restart it if need be.
1359
1360That means you can ignore both the C<ev_timer_start> function and the
1361C<after> argument to C<ev_timer_set>, and only ever use the C<repeat>
1362member and C<ev_timer_again>.
1363
1364At start:
1365
1366 ev_timer_init (timer, callback);
1367 timer->repeat = 60.;
1368 ev_timer_again (loop, timer);
1369
1370Each time there is some activity:
1371
1372 ev_timer_again (loop, timer);
1373
1374It is even possible to change the time-out on the fly, regardless of
1375whether the watcher is active or not:
1376
1377 timer->repeat = 30.;
1378 ev_timer_again (loop, timer);
1379
1380This is slightly more efficient then stopping/starting the timer each time
1381you want to modify its timeout value, as libev does not have to completely
1382remove and re-insert the timer from/into its internal data structure.
1383
1384It is, however, even simpler than the "obvious" way to do it.
1385
1386=item 3. Let the timer time out, but then re-arm it as required.
1387
1388This method is more tricky, but usually most efficient: Most timeouts are
1389relatively long compared to the intervals between other activity - in
1390our example, within 60 seconds, there are usually many I/O events with
1391associated activity resets.
1392
1393In this case, it would be more efficient to leave the C<ev_timer> alone,
1394but remember the time of last activity, and check for a real timeout only
1395within the callback:
1396
1397 ev_tstamp last_activity; // time of last activity
1398
1399 static void
1400 callback (EV_P_ ev_timer *w, int revents)
1401 {
1402 ev_tstamp now = ev_now (EV_A);
1403 ev_tstamp timeout = last_activity + 60.;
1404
1405 // if last_activity + 60. is older than now, we did time out
1406 if (timeout < now)
1407 {
1408 // timeout occured, take action
1409 }
1410 else
1411 {
1412 // callback was invoked, but there was some activity, re-arm
1413 // the watcher to fire in last_activity + 60, which is
1414 // guaranteed to be in the future, so "again" is positive:
1415 w->again = timeout - now;
1416 ev_timer_again (EV_A_ w);
1417 }
1418 }
1419
1420To summarise the callback: first calculate the real timeout (defined
1421as "60 seconds after the last activity"), then check if that time has
1422been reached, which means something I<did>, in fact, time out. Otherwise
1423the callback was invoked too early (C<timeout> is in the future), so
1424re-schedule the timer to fire at that future time, to see if maybe we have
1425a timeout then.
1426
1427Note how C<ev_timer_again> is used, taking advantage of the
1428C<ev_timer_again> optimisation when the timer is already running.
1429
1430This scheme causes more callback invocations (about one every 60 seconds
1431minus half the average time between activity), but virtually no calls to
1432libev to change the timeout.
1433
1434To start the timer, simply initialise the watcher and set C<last_activity>
1435to the current time (meaning we just have some activity :), then call the
1436callback, which will "do the right thing" and start the timer:
1437
1438 ev_timer_init (timer, callback);
1439 last_activity = ev_now (loop);
1440 callback (loop, timer, EV_TIMEOUT);
1441
1442And when there is some activity, simply store the current time in
1443C<last_activity>, no libev calls at all:
1444
1445 last_actiivty = ev_now (loop);
1446
1447This technique is slightly more complex, but in most cases where the
1448time-out is unlikely to be triggered, much more efficient.
1449
1450Changing the timeout is trivial as well (if it isn't hard-coded in the
1451callback :) - just change the timeout and invoke the callback, which will
1452fix things for you.
1453
1454=item 4. Wee, just use a double-linked list for your timeouts.
1455
1456If there is not one request, but many thousands (millions...), all
1457employing some kind of timeout with the same timeout value, then one can
1458do even better:
1459
1460When starting the timeout, calculate the timeout value and put the timeout
1461at the I<end> of the list.
1462
1463Then use an C<ev_timer> to fire when the timeout at the I<beginning> of
1464the list is expected to fire (for example, using the technique #3).
1465
1466When there is some activity, remove the timer from the list, recalculate
1467the timeout, append it to the end of the list again, and make sure to
1468update the C<ev_timer> if it was taken from the beginning of the list.
1469
1470This way, one can manage an unlimited number of timeouts in O(1) time for
1471starting, stopping and updating the timers, at the expense of a major
1472complication, and having to use a constant timeout. The constant timeout
1473ensures that the list stays sorted.
1474
1475=back
1476
1477So which method the best?
1478
1479Method #2 is a simple no-brain-required solution that is adequate in most
1480situations. Method #3 requires a bit more thinking, but handles many cases
1481better, and isn't very complicated either. In most case, choosing either
1482one is fine, with #3 being better in typical situations.
1483
1484Method #1 is almost always a bad idea, and buys you nothing. Method #4 is
1485rather complicated, but extremely efficient, something that really pays
1486off after the first million or so of active timers, i.e. it's usually
1487overkill :)
1488
1283=head3 The special problem of time updates 1489=head3 The special problem of time updates
1284 1490
1285Establishing the current time is a costly operation (it usually takes at 1491Establishing the current time is a costly operation (it usually takes at
1286least two system calls): EV therefore updates its idea of the current 1492least two system calls): EV therefore updates its idea of the current
1287time only before and after C<ev_loop> collects new events, which causes a 1493time only before and after C<ev_loop> collects new events, which causes a
1330If the timer is started but non-repeating, stop it (as if it timed out). 1536If the timer is started but non-repeating, stop it (as if it timed out).
1331 1537
1332If the timer is repeating, either start it if necessary (with the 1538If the timer is repeating, either start it if necessary (with the
1333C<repeat> value), or reset the running timer to the C<repeat> value. 1539C<repeat> value), or reset the running timer to the C<repeat> value.
1334 1540
1335This sounds a bit complicated, but here is a useful and typical 1541This sounds a bit complicated, see "Be smart about timeouts", above, for a
1336example: Imagine you have a TCP connection and you want a so-called idle 1542usage example.
1337timeout, that is, you want to be called when there have been, say, 60
1338seconds of inactivity on the socket. The easiest way to do this is to
1339configure an C<ev_timer> with a C<repeat> value of C<60> and then call
1340C<ev_timer_again> each time you successfully read or write some data. If
1341you go into an idle state where you do not expect data to travel on the
1342socket, you can C<ev_timer_stop> the timer, and C<ev_timer_again> will
1343automatically restart it if need be.
1344
1345That means you can ignore the C<after> value and C<ev_timer_start>
1346altogether and only ever use the C<repeat> value and C<ev_timer_again>:
1347
1348 ev_timer_init (timer, callback, 0., 5.);
1349 ev_timer_again (loop, timer);
1350 ...
1351 timer->again = 17.;
1352 ev_timer_again (loop, timer);
1353 ...
1354 timer->again = 10.;
1355 ev_timer_again (loop, timer);
1356
1357This is more slightly efficient then stopping/starting the timer each time
1358you want to modify its timeout value.
1359
1360Note, however, that it is often even more efficient to remember the
1361time of the last activity and let the timer time-out naturally. In the
1362callback, you then check whether the time-out is real, or, if there was
1363some activity, you reschedule the watcher to time-out in "last_activity +
1364timeout - ev_now ()" seconds.
1365 1543
1366=item ev_tstamp repeat [read-write] 1544=item ev_tstamp repeat [read-write]
1367 1545
1368The current C<repeat> value. Will be used each time the watcher times out 1546The current C<repeat> value. Will be used each time the watcher times out
1369or C<ev_timer_again> is called, and determines the next timeout (if any), 1547or C<ev_timer_again> is called, and determines the next timeout (if any),
1374=head3 Examples 1552=head3 Examples
1375 1553
1376Example: Create a timer that fires after 60 seconds. 1554Example: Create a timer that fires after 60 seconds.
1377 1555
1378 static void 1556 static void
1379 one_minute_cb (struct ev_loop *loop, struct ev_timer *w, int revents) 1557 one_minute_cb (struct ev_loop *loop, ev_timer *w, int revents)
1380 { 1558 {
1381 .. one minute over, w is actually stopped right here 1559 .. one minute over, w is actually stopped right here
1382 } 1560 }
1383 1561
1384 struct ev_timer mytimer; 1562 ev_timer mytimer;
1385 ev_timer_init (&mytimer, one_minute_cb, 60., 0.); 1563 ev_timer_init (&mytimer, one_minute_cb, 60., 0.);
1386 ev_timer_start (loop, &mytimer); 1564 ev_timer_start (loop, &mytimer);
1387 1565
1388Example: Create a timeout timer that times out after 10 seconds of 1566Example: Create a timeout timer that times out after 10 seconds of
1389inactivity. 1567inactivity.
1390 1568
1391 static void 1569 static void
1392 timeout_cb (struct ev_loop *loop, struct ev_timer *w, int revents) 1570 timeout_cb (struct ev_loop *loop, ev_timer *w, int revents)
1393 { 1571 {
1394 .. ten seconds without any activity 1572 .. ten seconds without any activity
1395 } 1573 }
1396 1574
1397 struct ev_timer mytimer; 1575 ev_timer mytimer;
1398 ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */ 1576 ev_timer_init (&mytimer, timeout_cb, 0., 10.); /* note, only repeat used */
1399 ev_timer_again (&mytimer); /* start timer */ 1577 ev_timer_again (&mytimer); /* start timer */
1400 ev_loop (loop, 0); 1578 ev_loop (loop, 0);
1401 1579
1402 // and in some piece of code that gets executed on any "activity": 1580 // and in some piece of code that gets executed on any "activity":
1488 1666
1489If you need to stop it, return C<now + 1e30> (or so, fudge fudge) and stop 1667If you need to stop it, return C<now + 1e30> (or so, fudge fudge) and stop
1490it afterwards (e.g. by starting an C<ev_prepare> watcher, which is the 1668it afterwards (e.g. by starting an C<ev_prepare> watcher, which is the
1491only event loop modification you are allowed to do). 1669only event loop modification you are allowed to do).
1492 1670
1493The callback prototype is C<ev_tstamp (*reschedule_cb)(struct ev_periodic 1671The callback prototype is C<ev_tstamp (*reschedule_cb)(ev_periodic
1494*w, ev_tstamp now)>, e.g.: 1672*w, ev_tstamp now)>, e.g.:
1495 1673
1674 static ev_tstamp
1496 static ev_tstamp my_rescheduler (struct ev_periodic *w, ev_tstamp now) 1675 my_rescheduler (ev_periodic *w, ev_tstamp now)
1497 { 1676 {
1498 return now + 60.; 1677 return now + 60.;
1499 } 1678 }
1500 1679
1501It must return the next time to trigger, based on the passed time value 1680It must return the next time to trigger, based on the passed time value
1538 1717
1539The current interval value. Can be modified any time, but changes only 1718The current interval value. Can be modified any time, but changes only
1540take effect when the periodic timer fires or C<ev_periodic_again> is being 1719take effect when the periodic timer fires or C<ev_periodic_again> is being
1541called. 1720called.
1542 1721
1543=item ev_tstamp (*reschedule_cb)(struct ev_periodic *w, ev_tstamp now) [read-write] 1722=item ev_tstamp (*reschedule_cb)(ev_periodic *w, ev_tstamp now) [read-write]
1544 1723
1545The current reschedule callback, or C<0>, if this functionality is 1724The current reschedule callback, or C<0>, if this functionality is
1546switched off. Can be changed any time, but changes only take effect when 1725switched off. Can be changed any time, but changes only take effect when
1547the periodic timer fires or C<ev_periodic_again> is being called. 1726the periodic timer fires or C<ev_periodic_again> is being called.
1548 1727
1553Example: Call a callback every hour, or, more precisely, whenever the 1732Example: Call a callback every hour, or, more precisely, whenever the
1554system time is divisible by 3600. The callback invocation times have 1733system time is divisible by 3600. The callback invocation times have
1555potentially a lot of jitter, but good long-term stability. 1734potentially a lot of jitter, but good long-term stability.
1556 1735
1557 static void 1736 static void
1558 clock_cb (struct ev_loop *loop, struct ev_io *w, int revents) 1737 clock_cb (struct ev_loop *loop, ev_io *w, int revents)
1559 { 1738 {
1560 ... its now a full hour (UTC, or TAI or whatever your clock follows) 1739 ... its now a full hour (UTC, or TAI or whatever your clock follows)
1561 } 1740 }
1562 1741
1563 struct ev_periodic hourly_tick; 1742 ev_periodic hourly_tick;
1564 ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0); 1743 ev_periodic_init (&hourly_tick, clock_cb, 0., 3600., 0);
1565 ev_periodic_start (loop, &hourly_tick); 1744 ev_periodic_start (loop, &hourly_tick);
1566 1745
1567Example: The same as above, but use a reschedule callback to do it: 1746Example: The same as above, but use a reschedule callback to do it:
1568 1747
1569 #include <math.h> 1748 #include <math.h>
1570 1749
1571 static ev_tstamp 1750 static ev_tstamp
1572 my_scheduler_cb (struct ev_periodic *w, ev_tstamp now) 1751 my_scheduler_cb (ev_periodic *w, ev_tstamp now)
1573 { 1752 {
1574 return now + (3600. - fmod (now, 3600.)); 1753 return now + (3600. - fmod (now, 3600.));
1575 } 1754 }
1576 1755
1577 ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb); 1756 ev_periodic_init (&hourly_tick, clock_cb, 0., 0., my_scheduler_cb);
1578 1757
1579Example: Call a callback every hour, starting now: 1758Example: Call a callback every hour, starting now:
1580 1759
1581 struct ev_periodic hourly_tick; 1760 ev_periodic hourly_tick;
1582 ev_periodic_init (&hourly_tick, clock_cb, 1761 ev_periodic_init (&hourly_tick, clock_cb,
1583 fmod (ev_now (loop), 3600.), 3600., 0); 1762 fmod (ev_now (loop), 3600.), 3600., 0);
1584 ev_periodic_start (loop, &hourly_tick); 1763 ev_periodic_start (loop, &hourly_tick);
1585 1764
1586 1765
1625 1804
1626=back 1805=back
1627 1806
1628=head3 Examples 1807=head3 Examples
1629 1808
1630Example: Try to exit cleanly on SIGINT and SIGTERM. 1809Example: Try to exit cleanly on SIGINT.
1631 1810
1632 static void 1811 static void
1633 sigint_cb (struct ev_loop *loop, struct ev_signal *w, int revents) 1812 sigint_cb (struct ev_loop *loop, ev_signal *w, int revents)
1634 { 1813 {
1635 ev_unloop (loop, EVUNLOOP_ALL); 1814 ev_unloop (loop, EVUNLOOP_ALL);
1636 } 1815 }
1637 1816
1638 struct ev_signal signal_watcher; 1817 ev_signal signal_watcher;
1639 ev_signal_init (&signal_watcher, sigint_cb, SIGINT); 1818 ev_signal_init (&signal_watcher, sigint_cb, SIGINT);
1640 ev_signal_start (loop, &sigint_cb); 1819 ev_signal_start (loop, &signal_watcher);
1641 1820
1642 1821
1643=head2 C<ev_child> - watch out for process status changes 1822=head2 C<ev_child> - watch out for process status changes
1644 1823
1645Child watchers trigger when your process receives a SIGCHLD in response to 1824Child watchers trigger when your process receives a SIGCHLD in response to
1718its completion. 1897its completion.
1719 1898
1720 ev_child cw; 1899 ev_child cw;
1721 1900
1722 static void 1901 static void
1723 child_cb (EV_P_ struct ev_child *w, int revents) 1902 child_cb (EV_P_ ev_child *w, int revents)
1724 { 1903 {
1725 ev_child_stop (EV_A_ w); 1904 ev_child_stop (EV_A_ w);
1726 printf ("process %d exited with status %x\n", w->rpid, w->rstatus); 1905 printf ("process %d exited with status %x\n", w->rpid, w->rstatus);
1727 } 1906 }
1728 1907
1792to exchange stat structures with application programs compiled using the 1971to exchange stat structures with application programs compiled using the
1793default compilation environment. 1972default compilation environment.
1794 1973
1795=head3 Inotify and Kqueue 1974=head3 Inotify and Kqueue
1796 1975
1797When C<inotify (7)> support has been compiled into libev (generally only 1976When C<inotify (7)> support has been compiled into libev (generally
1977only available with Linux 2.6.25 or above due to bugs in earlier
1798available with Linux) and present at runtime, it will be used to speed up 1978implementations) and present at runtime, it will be used to speed up
1799change detection where possible. The inotify descriptor will be created lazily 1979change detection where possible. The inotify descriptor will be created
1800when the first C<ev_stat> watcher is being started. 1980lazily when the first C<ev_stat> watcher is being started.
1801 1981
1802Inotify presence does not change the semantics of C<ev_stat> watchers 1982Inotify presence does not change the semantics of C<ev_stat> watchers
1803except that changes might be detected earlier, and in some cases, to avoid 1983except that changes might be detected earlier, and in some cases, to avoid
1804making regular C<stat> calls. Even in the presence of inotify support 1984making regular C<stat> calls. Even in the presence of inotify support
1805there are many cases where libev has to resort to regular C<stat> polling, 1985there are many cases where libev has to resort to regular C<stat> polling,
1979 2159
1980Example: Dynamically allocate an C<ev_idle> watcher, start it, and in the 2160Example: Dynamically allocate an C<ev_idle> watcher, start it, and in the
1981callback, free it. Also, use no error checking, as usual. 2161callback, free it. Also, use no error checking, as usual.
1982 2162
1983 static void 2163 static void
1984 idle_cb (struct ev_loop *loop, struct ev_idle *w, int revents) 2164 idle_cb (struct ev_loop *loop, ev_idle *w, int revents)
1985 { 2165 {
1986 free (w); 2166 free (w);
1987 // now do something you wanted to do when the program has 2167 // now do something you wanted to do when the program has
1988 // no longer anything immediate to do. 2168 // no longer anything immediate to do.
1989 } 2169 }
1990 2170
1991 struct ev_idle *idle_watcher = malloc (sizeof (struct ev_idle)); 2171 ev_idle *idle_watcher = malloc (sizeof (ev_idle));
1992 ev_idle_init (idle_watcher, idle_cb); 2172 ev_idle_init (idle_watcher, idle_cb);
1993 ev_idle_start (loop, idle_cb); 2173 ev_idle_start (loop, idle_cb);
1994 2174
1995 2175
1996=head2 C<ev_prepare> and C<ev_check> - customise your event loop! 2176=head2 C<ev_prepare> and C<ev_check> - customise your event loop!
2077 2257
2078 static ev_io iow [nfd]; 2258 static ev_io iow [nfd];
2079 static ev_timer tw; 2259 static ev_timer tw;
2080 2260
2081 static void 2261 static void
2082 io_cb (ev_loop *loop, ev_io *w, int revents) 2262 io_cb (struct ev_loop *loop, ev_io *w, int revents)
2083 { 2263 {
2084 } 2264 }
2085 2265
2086 // create io watchers for each fd and a timer before blocking 2266 // create io watchers for each fd and a timer before blocking
2087 static void 2267 static void
2088 adns_prepare_cb (ev_loop *loop, ev_prepare *w, int revents) 2268 adns_prepare_cb (struct ev_loop *loop, ev_prepare *w, int revents)
2089 { 2269 {
2090 int timeout = 3600000; 2270 int timeout = 3600000;
2091 struct pollfd fds [nfd]; 2271 struct pollfd fds [nfd];
2092 // actual code will need to loop here and realloc etc. 2272 // actual code will need to loop here and realloc etc.
2093 adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ())); 2273 adns_beforepoll (ads, fds, &nfd, &timeout, timeval_from (ev_time ()));
2108 } 2288 }
2109 } 2289 }
2110 2290
2111 // stop all watchers after blocking 2291 // stop all watchers after blocking
2112 static void 2292 static void
2113 adns_check_cb (ev_loop *loop, ev_check *w, int revents) 2293 adns_check_cb (struct ev_loop *loop, ev_check *w, int revents)
2114 { 2294 {
2115 ev_timer_stop (loop, &tw); 2295 ev_timer_stop (loop, &tw);
2116 2296
2117 for (int i = 0; i < nfd; ++i) 2297 for (int i = 0; i < nfd; ++i)
2118 { 2298 {
2242So when you want to use this feature you will always have to be prepared 2422So when you want to use this feature you will always have to be prepared
2243that you cannot get an embeddable loop. The recommended way to get around 2423that you cannot get an embeddable loop. The recommended way to get around
2244this is to have a separate variables for your embeddable loop, try to 2424this is to have a separate variables for your embeddable loop, try to
2245create it, and if that fails, use the normal loop for everything. 2425create it, and if that fails, use the normal loop for everything.
2246 2426
2427=head3 C<ev_embed> and fork
2428
2429While the C<ev_embed> watcher is running, forks in the embedding loop will
2430automatically be applied to the embedded loop as well, so no special
2431fork handling is required in that case. When the watcher is not running,
2432however, it is still the task of the libev user to call C<ev_loop_fork ()>
2433as applicable.
2434
2247=head3 Watcher-Specific Functions and Data Members 2435=head3 Watcher-Specific Functions and Data Members
2248 2436
2249=over 4 2437=over 4
2250 2438
2251=item ev_embed_init (ev_embed *, callback, struct ev_loop *embedded_loop) 2439=item ev_embed_init (ev_embed *, callback, struct ev_loop *embedded_loop)
2278C<loop_lo> (which is C<loop_hi> in the case no embeddable loop can be 2466C<loop_lo> (which is C<loop_hi> in the case no embeddable loop can be
2279used). 2467used).
2280 2468
2281 struct ev_loop *loop_hi = ev_default_init (0); 2469 struct ev_loop *loop_hi = ev_default_init (0);
2282 struct ev_loop *loop_lo = 0; 2470 struct ev_loop *loop_lo = 0;
2283 struct ev_embed embed; 2471 ev_embed embed;
2284 2472
2285 // see if there is a chance of getting one that works 2473 // see if there is a chance of getting one that works
2286 // (remember that a flags value of 0 means autodetection) 2474 // (remember that a flags value of 0 means autodetection)
2287 loop_lo = ev_embeddable_backends () & ev_recommended_backends () 2475 loop_lo = ev_embeddable_backends () & ev_recommended_backends ()
2288 ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ()) 2476 ? ev_loop_new (ev_embeddable_backends () & ev_recommended_backends ())
2302kqueue implementation). Store the kqueue/socket-only event loop in 2490kqueue implementation). Store the kqueue/socket-only event loop in
2303C<loop_socket>. (One might optionally use C<EVFLAG_NOENV>, too). 2491C<loop_socket>. (One might optionally use C<EVFLAG_NOENV>, too).
2304 2492
2305 struct ev_loop *loop = ev_default_init (0); 2493 struct ev_loop *loop = ev_default_init (0);
2306 struct ev_loop *loop_socket = 0; 2494 struct ev_loop *loop_socket = 0;
2307 struct ev_embed embed; 2495 ev_embed embed;
2308 2496
2309 if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE) 2497 if (ev_supported_backends () & ~ev_recommended_backends () & EVBACKEND_KQUEUE)
2310 if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE)) 2498 if ((loop_socket = ev_loop_new (EVBACKEND_KQUEUE))
2311 { 2499 {
2312 ev_embed_init (&embed, 0, loop_socket); 2500 ev_embed_init (&embed, 0, loop_socket);
2376=over 4 2564=over 4
2377 2565
2378=item queueing from a signal handler context 2566=item queueing from a signal handler context
2379 2567
2380To implement race-free queueing, you simply add to the queue in the signal 2568To implement race-free queueing, you simply add to the queue in the signal
2381handler but you block the signal handler in the watcher callback. Here is an example that does that for 2569handler but you block the signal handler in the watcher callback. Here is
2382some fictitious SIGUSR1 handler: 2570an example that does that for some fictitious SIGUSR1 handler:
2383 2571
2384 static ev_async mysig; 2572 static ev_async mysig;
2385 2573
2386 static void 2574 static void
2387 sigusr1_handler (void) 2575 sigusr1_handler (void)
2494=over 4 2682=over 4
2495 2683
2496=item ev_once (loop, int fd, int events, ev_tstamp timeout, callback) 2684=item ev_once (loop, int fd, int events, ev_tstamp timeout, callback)
2497 2685
2498This function combines a simple timer and an I/O watcher, calls your 2686This function combines a simple timer and an I/O watcher, calls your
2499callback on whichever event happens first and automatically stop both 2687callback on whichever event happens first and automatically stops both
2500watchers. This is useful if you want to wait for a single event on an fd 2688watchers. This is useful if you want to wait for a single event on an fd
2501or timeout without having to allocate/configure/start/stop/free one or 2689or timeout without having to allocate/configure/start/stop/free one or
2502more watchers yourself. 2690more watchers yourself.
2503 2691
2504If C<fd> is less than 0, then no I/O watcher will be started and events 2692If C<fd> is less than 0, then no I/O watcher will be started and the
2505is being ignored. Otherwise, an C<ev_io> watcher for the given C<fd> and 2693C<events> argument is being ignored. Otherwise, an C<ev_io> watcher for
2506C<events> set will be created and started. 2694the given C<fd> and C<events> set will be created and started.
2507 2695
2508If C<timeout> is less than 0, then no timeout watcher will be 2696If C<timeout> is less than 0, then no timeout watcher will be
2509started. Otherwise an C<ev_timer> watcher with after = C<timeout> (and 2697started. Otherwise an C<ev_timer> watcher with after = C<timeout> (and
2510repeat = 0) will be started. While C<0> is a valid timeout, it is of 2698repeat = 0) will be started. C<0> is a valid timeout.
2511dubious value.
2512 2699
2513The callback has the type C<void (*cb)(int revents, void *arg)> and gets 2700The callback has the type C<void (*cb)(int revents, void *arg)> and gets
2514passed an C<revents> set like normal event callbacks (a combination of 2701passed an C<revents> set like normal event callbacks (a combination of
2515C<EV_ERROR>, C<EV_READ>, C<EV_WRITE> or C<EV_TIMEOUT>) and the C<arg> 2702C<EV_ERROR>, C<EV_READ>, C<EV_WRITE> or C<EV_TIMEOUT>) and the C<arg>
2516value passed to C<ev_once>: 2703value passed to C<ev_once>. Note that it is possible to receive I<both>
2704a timeout and an io event at the same time - you probably should give io
2705events precedence.
2706
2707Example: wait up to ten seconds for data to appear on STDIN_FILENO.
2517 2708
2518 static void stdin_ready (int revents, void *arg) 2709 static void stdin_ready (int revents, void *arg)
2519 { 2710 {
2711 if (revents & EV_READ)
2712 /* stdin might have data for us, joy! */;
2520 if (revents & EV_TIMEOUT) 2713 else if (revents & EV_TIMEOUT)
2521 /* doh, nothing entered */; 2714 /* doh, nothing entered */;
2522 else if (revents & EV_READ)
2523 /* stdin might have data for us, joy! */;
2524 } 2715 }
2525 2716
2526 ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0); 2717 ev_once (STDIN_FILENO, EV_READ, 10., stdin_ready, 0);
2527 2718
2528=item ev_feed_event (ev_loop *, watcher *, int revents) 2719=item ev_feed_event (struct ev_loop *, watcher *, int revents)
2529 2720
2530Feeds the given event set into the event loop, as if the specified event 2721Feeds the given event set into the event loop, as if the specified event
2531had happened for the specified watcher (which must be a pointer to an 2722had happened for the specified watcher (which must be a pointer to an
2532initialised but not necessarily started event watcher). 2723initialised but not necessarily started event watcher).
2533 2724
2534=item ev_feed_fd_event (ev_loop *, int fd, int revents) 2725=item ev_feed_fd_event (struct ev_loop *, int fd, int revents)
2535 2726
2536Feed an event on the given fd, as if a file descriptor backend detected 2727Feed an event on the given fd, as if a file descriptor backend detected
2537the given events it. 2728the given events it.
2538 2729
2539=item ev_feed_signal_event (ev_loop *loop, int signum) 2730=item ev_feed_signal_event (struct ev_loop *loop, int signum)
2540 2731
2541Feed an event as if the given signal occurred (C<loop> must be the default 2732Feed an event as if the given signal occurred (C<loop> must be the default
2542loop!). 2733loop!).
2543 2734
2544=back 2735=back
2778 2969
2779=item D 2970=item D
2780 2971
2781Leandro Lucarella has written a D language binding (F<ev.d>) for libev, to 2972Leandro Lucarella has written a D language binding (F<ev.d>) for libev, to
2782be found at L<http://proj.llucax.com.ar/wiki/evd>. 2973be found at L<http://proj.llucax.com.ar/wiki/evd>.
2974
2975=item Ocaml
2976
2977Erkki Seppala has written Ocaml bindings for libev, to be found at
2978L<http://modeemi.cs.tut.fi/~flux/software/ocaml-ev/>.
2783 2979
2784=back 2980=back
2785 2981
2786 2982
2787=head1 MACRO MAGIC 2983=head1 MACRO MAGIC
3298And a F<ev_cpp.C> implementation file that contains libev proper and is compiled: 3494And a F<ev_cpp.C> implementation file that contains libev proper and is compiled:
3299 3495
3300 #include "ev_cpp.h" 3496 #include "ev_cpp.h"
3301 #include "ev.c" 3497 #include "ev.c"
3302 3498
3499=head1 INTERACTION WITH OTHER PROGRAMS OR LIBRARIES
3303 3500
3304=head1 THREADS AND COROUTINES 3501=head2 THREADS AND COROUTINES
3305 3502
3306=head2 THREADS 3503=head3 THREADS
3307 3504
3308Libev itself is thread-safe (unless the opposite is specifically 3505All libev functions are reentrant and thread-safe unless explicitly
3309documented for a function), but it uses no locking itself. This means that 3506documented otherwise, but libev implements no locking itself. This means
3310you can use as many loops as you want in parallel, as long as only one 3507that you can use as many loops as you want in parallel, as long as there
3311thread ever calls into one libev function with the same loop parameter: 3508are no concurrent calls into any libev function with the same loop
3509parameter (C<ev_default_*> calls have an implicit default loop parameter,
3312libev guarantees that different event loops share no data structures that 3510of course): libev guarantees that different event loops share no data
3313need locking. 3511structures that need any locking.
3314 3512
3315Or to put it differently: calls with different loop parameters can be done 3513Or to put it differently: calls with different loop parameters can be done
3316concurrently from multiple threads, calls with the same loop parameter 3514concurrently from multiple threads, calls with the same loop parameter
3317must be done serially (but can be done from different threads, as long as 3515must be done serially (but can be done from different threads, as long as
3318only one thread ever is inside a call at any point in time, e.g. by using 3516only one thread ever is inside a call at any point in time, e.g. by using
3319a mutex per loop). 3517a mutex per loop).
3320 3518
3321Specifically to support threads (and signal handlers), libev implements 3519Specifically to support threads (and signal handlers), libev implements
3322so-called C<ev_async> watchers, which allow some limited form of 3520so-called C<ev_async> watchers, which allow some limited form of
3323concurrency on the same event loop. 3521concurrency on the same event loop, namely waking it up "from the
3522outside".
3324 3523
3325If you want to know which design (one loop, locking, or multiple loops 3524If you want to know which design (one loop, locking, or multiple loops
3326without or something else still) is best for your problem, then I cannot 3525without or something else still) is best for your problem, then I cannot
3327help you. I can give some generic advice however: 3526help you, but here is some generic advice:
3328 3527
3329=over 4 3528=over 4
3330 3529
3331=item * most applications have a main thread: use the default libev loop 3530=item * most applications have a main thread: use the default libev loop
3332in that thread, or create a separate thread running only the default loop. 3531in that thread, or create a separate thread running only the default loop.
3356default loop and triggering an C<ev_async> watcher from the default loop 3555default loop and triggering an C<ev_async> watcher from the default loop
3357watcher callback into the event loop interested in the signal. 3556watcher callback into the event loop interested in the signal.
3358 3557
3359=back 3558=back
3360 3559
3361=head2 COROUTINES 3560=head3 COROUTINES
3362 3561
3363Libev is much more accommodating to coroutines ("cooperative threads"): 3562Libev is very accommodating to coroutines ("cooperative threads"):
3364libev fully supports nesting calls to it's functions from different 3563libev fully supports nesting calls to its functions from different
3365coroutines (e.g. you can call C<ev_loop> on the same loop from two 3564coroutines (e.g. you can call C<ev_loop> on the same loop from two
3366different coroutines and switch freely between both coroutines running the 3565different coroutines, and switch freely between both coroutines running the
3367loop, as long as you don't confuse yourself). The only exception is that 3566loop, as long as you don't confuse yourself). The only exception is that
3368you must not do this from C<ev_periodic> reschedule callbacks. 3567you must not do this from C<ev_periodic> reschedule callbacks.
3369 3568
3370Care has been taken to ensure that libev does not keep local state inside 3569Care has been taken to ensure that libev does not keep local state inside
3371C<ev_loop>, and other calls do not usually allow coroutine switches. 3570C<ev_loop>, and other calls do not usually allow for coroutine switches as
3571they do not clal any callbacks.
3372 3572
3573=head2 COMPILER WARNINGS
3373 3574
3374=head1 COMPLEXITIES 3575Depending on your compiler and compiler settings, you might get no or a
3576lot of warnings when compiling libev code. Some people are apparently
3577scared by this.
3375 3578
3376In this section the complexities of (many of) the algorithms used inside 3579However, these are unavoidable for many reasons. For one, each compiler
3377libev will be explained. For complexity discussions about backends see the 3580has different warnings, and each user has different tastes regarding
3378documentation for C<ev_default_init>. 3581warning options. "Warn-free" code therefore cannot be a goal except when
3582targeting a specific compiler and compiler-version.
3379 3583
3380All of the following are about amortised time: If an array needs to be 3584Another reason is that some compiler warnings require elaborate
3381extended, libev needs to realloc and move the whole array, but this 3585workarounds, or other changes to the code that make it less clear and less
3382happens asymptotically never with higher number of elements, so O(1) might 3586maintainable.
3383mean it might do a lengthy realloc operation in rare cases, but on average
3384it is much faster and asymptotically approaches constant time.
3385 3587
3386=over 4 3588And of course, some compiler warnings are just plain stupid, or simply
3589wrong (because they don't actually warn about the condition their message
3590seems to warn about). For example, certain older gcc versions had some
3591warnings that resulted an extreme number of false positives. These have
3592been fixed, but some people still insist on making code warn-free with
3593such buggy versions.
3387 3594
3388=item Starting and stopping timer/periodic watchers: O(log skipped_other_timers) 3595While libev is written to generate as few warnings as possible,
3596"warn-free" code is not a goal, and it is recommended not to build libev
3597with any compiler warnings enabled unless you are prepared to cope with
3598them (e.g. by ignoring them). Remember that warnings are just that:
3599warnings, not errors, or proof of bugs.
3389 3600
3390This means that, when you have a watcher that triggers in one hour and
3391there are 100 watchers that would trigger before that then inserting will
3392have to skip roughly seven (C<ld 100>) of these watchers.
3393 3601
3394=item Changing timer/periodic watchers (by autorepeat or calling again): O(log skipped_other_timers) 3602=head2 VALGRIND
3395 3603
3396That means that changing a timer costs less than removing/adding them 3604Valgrind has a special section here because it is a popular tool that is
3397as only the relative motion in the event queue has to be paid for. 3605highly useful. Unfortunately, valgrind reports are very hard to interpret.
3398 3606
3399=item Starting io/check/prepare/idle/signal/child/fork/async watchers: O(1) 3607If you think you found a bug (memory leak, uninitialised data access etc.)
3608in libev, then check twice: If valgrind reports something like:
3400 3609
3401These just add the watcher into an array or at the head of a list. 3610 ==2274== definitely lost: 0 bytes in 0 blocks.
3611 ==2274== possibly lost: 0 bytes in 0 blocks.
3612 ==2274== still reachable: 256 bytes in 1 blocks.
3402 3613
3403=item Stopping check/prepare/idle/fork/async watchers: O(1) 3614Then there is no memory leak, just as memory accounted to global variables
3615is not a memleak - the memory is still being refernced, and didn't leak.
3404 3616
3405=item Stopping an io/signal/child watcher: O(number_of_watchers_for_this_(fd/signal/pid % EV_PID_HASHSIZE)) 3617Similarly, under some circumstances, valgrind might report kernel bugs
3618as if it were a bug in libev (e.g. in realloc or in the poll backend,
3619although an acceptable workaround has been found here), or it might be
3620confused.
3406 3621
3407These watchers are stored in lists then need to be walked to find the 3622Keep in mind that valgrind is a very good tool, but only a tool. Don't
3408correct watcher to remove. The lists are usually short (you don't usually 3623make it into some kind of religion.
3409have many watchers waiting for the same fd or signal).
3410 3624
3411=item Finding the next timer in each loop iteration: O(1) 3625If you are unsure about something, feel free to contact the mailing list
3626with the full valgrind report and an explanation on why you think this
3627is a bug in libev (best check the archives, too :). However, don't be
3628annoyed when you get a brisk "this is no bug" answer and take the chance
3629of learning how to interpret valgrind properly.
3412 3630
3413By virtue of using a binary or 4-heap, the next timer is always found at a 3631If you need, for some reason, empty reports from valgrind for your project
3414fixed position in the storage array. 3632I suggest using suppression lists.
3415 3633
3416=item Each change on a file descriptor per loop iteration: O(number_of_watchers_for_this_fd)
3417 3634
3418A change means an I/O watcher gets started or stopped, which requires 3635=head1 PORTABILITY NOTES
3419libev to recalculate its status (and possibly tell the kernel, depending
3420on backend and whether C<ev_io_set> was used).
3421 3636
3422=item Activating one watcher (putting it into the pending state): O(1)
3423
3424=item Priority handling: O(number_of_priorities)
3425
3426Priorities are implemented by allocating some space for each
3427priority. When doing priority-based operations, libev usually has to
3428linearly search all the priorities, but starting/stopping and activating
3429watchers becomes O(1) with respect to priority handling.
3430
3431=item Sending an ev_async: O(1)
3432
3433=item Processing ev_async_send: O(number_of_async_watchers)
3434
3435=item Processing signals: O(max_signal_number)
3436
3437Sending involves a system call I<iff> there were no other C<ev_async_send>
3438calls in the current loop iteration. Checking for async and signal events
3439involves iterating over all running async watchers or all signal numbers.
3440
3441=back
3442
3443
3444=head1 WIN32 PLATFORM LIMITATIONS AND WORKAROUNDS 3637=head2 WIN32 PLATFORM LIMITATIONS AND WORKAROUNDS
3445 3638
3446Win32 doesn't support any of the standards (e.g. POSIX) that libev 3639Win32 doesn't support any of the standards (e.g. POSIX) that libev
3447requires, and its I/O model is fundamentally incompatible with the POSIX 3640requires, and its I/O model is fundamentally incompatible with the POSIX
3448model. Libev still offers limited functionality on this platform in 3641model. Libev still offers limited functionality on this platform in
3449the form of the C<EVBACKEND_SELECT> backend, and only supports socket 3642the form of the C<EVBACKEND_SELECT> backend, and only supports socket
3536wrap all I/O functions and provide your own fd management, but the cost of 3729wrap all I/O functions and provide your own fd management, but the cost of
3537calling select (O(n²)) will likely make this unworkable. 3730calling select (O(n²)) will likely make this unworkable.
3538 3731
3539=back 3732=back
3540 3733
3541
3542=head1 PORTABILITY REQUIREMENTS 3734=head2 PORTABILITY REQUIREMENTS
3543 3735
3544In addition to a working ISO-C implementation, libev relies on a few 3736In addition to a working ISO-C implementation and of course the
3545additional extensions: 3737backend-specific APIs, libev relies on a few additional extensions:
3546 3738
3547=over 4 3739=over 4
3548 3740
3549=item C<void (*)(ev_watcher_type *, int revents)> must have compatible 3741=item C<void (*)(ev_watcher_type *, int revents)> must have compatible
3550calling conventions regardless of C<ev_watcher_type *>. 3742calling conventions regardless of C<ev_watcher_type *>.
3575except the initial one, and run the default loop in the initial thread as 3767except the initial one, and run the default loop in the initial thread as
3576well. 3768well.
3577 3769
3578=item C<long> must be large enough for common memory allocation sizes 3770=item C<long> must be large enough for common memory allocation sizes
3579 3771
3580To improve portability and simplify using libev, libev uses C<long> 3772To improve portability and simplify its API, libev uses C<long> internally
3581internally instead of C<size_t> when allocating its data structures. On 3773instead of C<size_t> when allocating its data structures. On non-POSIX
3582non-POSIX systems (Microsoft...) this might be unexpectedly low, but 3774systems (Microsoft...) this might be unexpectedly low, but is still at
3583is still at least 31 bits everywhere, which is enough for hundreds of 3775least 31 bits everywhere, which is enough for hundreds of millions of
3584millions of watchers. 3776watchers.
3585 3777
3586=item C<double> must hold a time value in seconds with enough accuracy 3778=item C<double> must hold a time value in seconds with enough accuracy
3587 3779
3588The type C<double> is used to represent timestamps. It is required to 3780The type C<double> is used to represent timestamps. It is required to
3589have at least 51 bits of mantissa (and 9 bits of exponent), which is good 3781have at least 51 bits of mantissa (and 9 bits of exponent), which is good
3593=back 3785=back
3594 3786
3595If you know of other additional requirements drop me a note. 3787If you know of other additional requirements drop me a note.
3596 3788
3597 3789
3598=head1 COMPILER WARNINGS 3790=head1 ALGORITHMIC COMPLEXITIES
3599 3791
3600Depending on your compiler and compiler settings, you might get no or a 3792In this section the complexities of (many of) the algorithms used inside
3601lot of warnings when compiling libev code. Some people are apparently 3793libev will be documented. For complexity discussions about backends see
3602scared by this. 3794the documentation for C<ev_default_init>.
3603 3795
3604However, these are unavoidable for many reasons. For one, each compiler 3796All of the following are about amortised time: If an array needs to be
3605has different warnings, and each user has different tastes regarding 3797extended, libev needs to realloc and move the whole array, but this
3606warning options. "Warn-free" code therefore cannot be a goal except when 3798happens asymptotically rarer with higher number of elements, so O(1) might
3607targeting a specific compiler and compiler-version. 3799mean that libev does a lengthy realloc operation in rare cases, but on
3800average it is much faster and asymptotically approaches constant time.
3608 3801
3609Another reason is that some compiler warnings require elaborate 3802=over 4
3610workarounds, or other changes to the code that make it less clear and less
3611maintainable.
3612 3803
3613And of course, some compiler warnings are just plain stupid, or simply 3804=item Starting and stopping timer/periodic watchers: O(log skipped_other_timers)
3614wrong (because they don't actually warn about the condition their message
3615seems to warn about).
3616 3805
3617While libev is written to generate as few warnings as possible, 3806This means that, when you have a watcher that triggers in one hour and
3618"warn-free" code is not a goal, and it is recommended not to build libev 3807there are 100 watchers that would trigger before that, then inserting will
3619with any compiler warnings enabled unless you are prepared to cope with 3808have to skip roughly seven (C<ld 100>) of these watchers.
3620them (e.g. by ignoring them). Remember that warnings are just that:
3621warnings, not errors, or proof of bugs.
3622 3809
3810=item Changing timer/periodic watchers (by autorepeat or calling again): O(log skipped_other_timers)
3623 3811
3624=head1 VALGRIND 3812That means that changing a timer costs less than removing/adding them,
3813as only the relative motion in the event queue has to be paid for.
3625 3814
3626Valgrind has a special section here because it is a popular tool that is 3815=item Starting io/check/prepare/idle/signal/child/fork/async watchers: O(1)
3627highly useful, but valgrind reports are very hard to interpret.
3628 3816
3629If you think you found a bug (memory leak, uninitialised data access etc.) 3817These just add the watcher into an array or at the head of a list.
3630in libev, then check twice: If valgrind reports something like:
3631 3818
3632 ==2274== definitely lost: 0 bytes in 0 blocks. 3819=item Stopping check/prepare/idle/fork/async watchers: O(1)
3633 ==2274== possibly lost: 0 bytes in 0 blocks.
3634 ==2274== still reachable: 256 bytes in 1 blocks.
3635 3820
3636Then there is no memory leak. Similarly, under some circumstances, 3821=item Stopping an io/signal/child watcher: O(number_of_watchers_for_this_(fd/signal/pid % EV_PID_HASHSIZE))
3637valgrind might report kernel bugs as if it were a bug in libev, or it
3638might be confused (it is a very good tool, but only a tool).
3639 3822
3640If you are unsure about something, feel free to contact the mailing list 3823These watchers are stored in lists, so they need to be walked to find the
3641with the full valgrind report and an explanation on why you think this is 3824correct watcher to remove. The lists are usually short (you don't usually
3642a bug in libev. However, don't be annoyed when you get a brisk "this is 3825have many watchers waiting for the same fd or signal: one is typical, two
3643no bug" answer and take the chance of learning how to interpret valgrind 3826is rare).
3644properly.
3645 3827
3646If you need, for some reason, empty reports from valgrind for your project 3828=item Finding the next timer in each loop iteration: O(1)
3647I suggest using suppression lists. 3829
3830By virtue of using a binary or 4-heap, the next timer is always found at a
3831fixed position in the storage array.
3832
3833=item Each change on a file descriptor per loop iteration: O(number_of_watchers_for_this_fd)
3834
3835A change means an I/O watcher gets started or stopped, which requires
3836libev to recalculate its status (and possibly tell the kernel, depending
3837on backend and whether C<ev_io_set> was used).
3838
3839=item Activating one watcher (putting it into the pending state): O(1)
3840
3841=item Priority handling: O(number_of_priorities)
3842
3843Priorities are implemented by allocating some space for each
3844priority. When doing priority-based operations, libev usually has to
3845linearly search all the priorities, but starting/stopping and activating
3846watchers becomes O(1) with respect to priority handling.
3847
3848=item Sending an ev_async: O(1)
3849
3850=item Processing ev_async_send: O(number_of_async_watchers)
3851
3852=item Processing signals: O(max_signal_number)
3853
3854Sending involves a system call I<iff> there were no other C<ev_async_send>
3855calls in the current loop iteration. Checking for async and signal events
3856involves iterating over all running async watchers or all signal numbers.
3857
3858=back
3648 3859
3649 3860
3650=head1 AUTHOR 3861=head1 AUTHOR
3651 3862
3652Marc Lehmann <libev@schmorp.de>. 3863Marc Lehmann <libev@schmorp.de>.

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines