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

Comparing libev/ev.3 (file contents):
Revision 1.83 by root, Mon Oct 25 11:30:45 2010 UTC vs.
Revision 1.87 by root, Wed Feb 16 08:09:06 2011 UTC

122.\} 122.\}
123.rm #[ #] #H #V #F C 123.rm #[ #] #H #V #F C
124.\" ======================================================================== 124.\" ========================================================================
125.\" 125.\"
126.IX Title "LIBEV 3" 126.IX Title "LIBEV 3"
127.TH LIBEV 3 "2010-10-25" "libev-4.00" "libev - high performance full featured event loop" 127.TH LIBEV 3 "2011-02-16" "libev-4.04" "libev - high performance full featured event loop"
128.\" For nroff, turn off justification. Always turn off hyphenation; it makes 128.\" For nroff, turn off justification. Always turn off hyphenation; it makes
129.\" way too many mistakes in technical documents. 129.\" way too many mistakes in technical documents.
130.if n .ad l 130.if n .ad l
131.nh 131.nh
132.SH "NAME" 132.SH "NAME"
189\& ev_timer_start (loop, &timeout_watcher); 189\& ev_timer_start (loop, &timeout_watcher);
190\& 190\&
191\& // now wait for events to arrive 191\& // now wait for events to arrive
192\& ev_run (loop, 0); 192\& ev_run (loop, 0);
193\& 193\&
194\& // unloop was called, so exit 194\& // break was called, so exit
195\& return 0; 195\& return 0;
196\& } 196\& }
197.Ve 197.Ve
198.SH "ABOUT THIS DOCUMENT" 198.SH "ABOUT THIS DOCUMENT"
199.IX Header "ABOUT THIS DOCUMENT" 199.IX Header "ABOUT THIS DOCUMENT"
361current system. To find which embeddable backends might be supported on 361current system. To find which embeddable backends might be supported on
362the current system, you would need to look at \f(CW\*(C`ev_embeddable_backends () 362the current system, you would need to look at \f(CW\*(C`ev_embeddable_backends ()
363& ev_supported_backends ()\*(C'\fR, likewise for recommended ones. 363& ev_supported_backends ()\*(C'\fR, likewise for recommended ones.
364.Sp 364.Sp
365See the description of \f(CW\*(C`ev_embed\*(C'\fR watchers for more info. 365See the description of \f(CW\*(C`ev_embed\*(C'\fR watchers for more info.
366.IP "ev_set_allocator (void *(*cb)(void *ptr, long size)) [\s-1NOT\s0 \s-1REENTRANT\s0]" 4 366.IP "ev_set_allocator (void *(*cb)(void *ptr, long size))" 4
367.IX Item "ev_set_allocator (void *(*cb)(void *ptr, long size)) [NOT REENTRANT]" 367.IX Item "ev_set_allocator (void *(*cb)(void *ptr, long size))"
368Sets the allocation function to use (the prototype is similar \- the 368Sets the allocation function to use (the prototype is similar \- the
369semantics are identical to the \f(CW\*(C`realloc\*(C'\fR C89/SuS/POSIX function). It is 369semantics are identical to the \f(CW\*(C`realloc\*(C'\fR C89/SuS/POSIX function). It is
370used to allocate and free memory (no surprises here). If it returns zero 370used to allocate and free memory (no surprises here). If it returns zero
371when memory needs to be allocated (\f(CW\*(C`size != 0\*(C'\fR), the library might abort 371when memory needs to be allocated (\f(CW\*(C`size != 0\*(C'\fR), the library might abort
372or take some potentially destructive action. 372or take some potentially destructive action.
398\& } 398\& }
399\& 399\&
400\& ... 400\& ...
401\& ev_set_allocator (persistent_realloc); 401\& ev_set_allocator (persistent_realloc);
402.Ve 402.Ve
403.IP "ev_set_syserr_cb (void (*cb)(const char *msg)); [\s-1NOT\s0 \s-1REENTRANT\s0]" 4 403.IP "ev_set_syserr_cb (void (*cb)(const char *msg))" 4
404.IX Item "ev_set_syserr_cb (void (*cb)(const char *msg)); [NOT REENTRANT]" 404.IX Item "ev_set_syserr_cb (void (*cb)(const char *msg))"
405Set the callback function to call on a retryable system call error (such 405Set the callback function to call on a retryable system call error (such
406as failed select, poll, epoll_wait). The message is a printable string 406as failed select, poll, epoll_wait). The message is a printable string
407indicating the system call or subsystem causing the problem. If this 407indicating the system call or subsystem causing the problem. If this
408callback is set, then libev will expect it to remedy the situation, no 408callback is set, then libev will expect it to remedy the situation, no
409matter what, when it returns. That is, libev will generally retry the 409matter what, when it returns. That is, libev will generally retry the
421\& } 421\& }
422\& 422\&
423\& ... 423\& ...
424\& ev_set_syserr_cb (fatal_error); 424\& ev_set_syserr_cb (fatal_error);
425.Ve 425.Ve
426.IP "ev_feed_signal (int signum)" 4
427.IX Item "ev_feed_signal (int signum)"
428This function can be used to \*(L"simulate\*(R" a signal receive. It is completely
429safe to call this function at any time, from any context, including signal
430handlers or random threads.
431.Sp
432Its main use is to customise signal handling in your process, especially
433in the presence of threads. For example, you could block signals
434by default in all threads (and specifying \f(CW\*(C`EVFLAG_NOSIGMASK\*(C'\fR when
435creating any loops), and in one thread, use \f(CW\*(C`sigwait\*(C'\fR or any other
436mechanism to wait for signals, then \*(L"deliver\*(R" them to libev by calling
437\&\f(CW\*(C`ev_feed_signal\*(C'\fR.
426.SH "FUNCTIONS CONTROLLING EVENT LOOPS" 438.SH "FUNCTIONS CONTROLLING EVENT LOOPS"
427.IX Header "FUNCTIONS CONTROLLING EVENT LOOPS" 439.IX Header "FUNCTIONS CONTROLLING EVENT LOOPS"
428An event loop is described by a \f(CW\*(C`struct ev_loop *\*(C'\fR (the \f(CW\*(C`struct\*(C'\fR is 440An event loop is described by a \f(CW\*(C`struct ev_loop *\*(C'\fR (the \f(CW\*(C`struct\*(C'\fR is
429\&\fInot\fR optional in this case unless libev 3 compatibility is disabled, as 441\&\fInot\fR optional in this case unless libev 3 compatibility is disabled, as
430libev 3 had an \f(CW\*(C`ev_loop\*(C'\fR function colliding with the struct name). 442libev 3 had an \f(CW\*(C`ev_loop\*(C'\fR function colliding with the struct name).
475.IP "struct ev_loop *ev_loop_new (unsigned int flags)" 4 487.IP "struct ev_loop *ev_loop_new (unsigned int flags)" 4
476.IX Item "struct ev_loop *ev_loop_new (unsigned int flags)" 488.IX Item "struct ev_loop *ev_loop_new (unsigned int flags)"
477This will create and initialise a new event loop object. If the loop 489This will create and initialise a new event loop object. If the loop
478could not be initialised, returns false. 490could not be initialised, returns false.
479.Sp 491.Sp
480Note that this function \fIis\fR thread-safe, and one common way to use 492This function is thread-safe, and one common way to use libev with
481libev with threads is indeed to create one loop per thread, and using the 493threads is indeed to create one loop per thread, and using the default
482default loop in the \*(L"main\*(R" or \*(L"initial\*(R" thread. 494loop in the \*(L"main\*(R" or \*(L"initial\*(R" thread.
483.Sp 495.Sp
484The flags argument can be used to specify special behaviour or specific 496The flags argument can be used to specify special behaviour or specific
485backends to use, and is usually specified as \f(CW0\fR (or \f(CW\*(C`EVFLAG_AUTO\*(C'\fR). 497backends to use, and is usually specified as \f(CW0\fR (or \f(CW\*(C`EVFLAG_AUTO\*(C'\fR).
486.Sp 498.Sp
487The following flags are supported: 499The following flags are supported:
521environment variable. 533environment variable.
522.ie n .IP """EVFLAG_NOINOTIFY""" 4 534.ie n .IP """EVFLAG_NOINOTIFY""" 4
523.el .IP "\f(CWEVFLAG_NOINOTIFY\fR" 4 535.el .IP "\f(CWEVFLAG_NOINOTIFY\fR" 4
524.IX Item "EVFLAG_NOINOTIFY" 536.IX Item "EVFLAG_NOINOTIFY"
525When this flag is specified, then libev will not attempt to use the 537When this flag is specified, then libev will not attempt to use the
526\&\fIinotify\fR \s-1API\s0 for it's \f(CW\*(C`ev_stat\*(C'\fR watchers. Apart from debugging and 538\&\fIinotify\fR \s-1API\s0 for its \f(CW\*(C`ev_stat\*(C'\fR watchers. Apart from debugging and
527testing, this flag can be useful to conserve inotify file descriptors, as 539testing, this flag can be useful to conserve inotify file descriptors, as
528otherwise each loop using \f(CW\*(C`ev_stat\*(C'\fR watchers consumes one inotify handle. 540otherwise each loop using \f(CW\*(C`ev_stat\*(C'\fR watchers consumes one inotify handle.
529.ie n .IP """EVFLAG_SIGNALFD""" 4 541.ie n .IP """EVFLAG_SIGNALFD""" 4
530.el .IP "\f(CWEVFLAG_SIGNALFD\fR" 4 542.el .IP "\f(CWEVFLAG_SIGNALFD\fR" 4
531.IX Item "EVFLAG_SIGNALFD" 543.IX Item "EVFLAG_SIGNALFD"
532When this flag is specified, then libev will attempt to use the 544When this flag is specified, then libev will attempt to use the
533\&\fIsignalfd\fR \s-1API\s0 for it's \f(CW\*(C`ev_signal\*(C'\fR (and \f(CW\*(C`ev_child\*(C'\fR) watchers. This \s-1API\s0 545\&\fIsignalfd\fR \s-1API\s0 for its \f(CW\*(C`ev_signal\*(C'\fR (and \f(CW\*(C`ev_child\*(C'\fR) watchers. This \s-1API\s0
534delivers signals synchronously, which makes it both faster and might make 546delivers signals synchronously, which makes it both faster and might make
535it possible to get the queued signal data. It can also simplify signal 547it possible to get the queued signal data. It can also simplify signal
536handling with threads, as long as you properly block signals in your 548handling with threads, as long as you properly block signals in your
537threads that are not interested in handling them. 549threads that are not interested in handling them.
538.Sp 550.Sp
539Signalfd will not be used by default as this changes your signal mask, and 551Signalfd will not be used by default as this changes your signal mask, and
540there are a lot of shoddy libraries and programs (glib's threadpool for 552there are a lot of shoddy libraries and programs (glib's threadpool for
541example) that can't properly initialise their signal masks. 553example) that can't properly initialise their signal masks.
554.ie n .IP """EVFLAG_NOSIGMASK""" 4
555.el .IP "\f(CWEVFLAG_NOSIGMASK\fR" 4
556.IX Item "EVFLAG_NOSIGMASK"
557When this flag is specified, then libev will avoid to modify the signal
558mask. Specifically, this means you ahve to make sure signals are unblocked
559when you want to receive them.
560.Sp
561This behaviour is useful when you want to do your own signal handling, or
562want to handle signals only in specific threads and want to avoid libev
563unblocking the signals.
564.Sp
565It's also required by \s-1POSIX\s0 in a threaded program, as libev calls
566\&\f(CW\*(C`sigprocmask\*(C'\fR, whose behaviour is officially unspecified.
567.Sp
568This flag's behaviour will become the default in future versions of libev.
542.ie n .IP """EVBACKEND_SELECT"" (value 1, portable select backend)" 4 569.ie n .IP """EVBACKEND_SELECT"" (value 1, portable select backend)" 4
543.el .IP "\f(CWEVBACKEND_SELECT\fR (value 1, portable select backend)" 4 570.el .IP "\f(CWEVBACKEND_SELECT\fR (value 1, portable select backend)" 4
544.IX Item "EVBACKEND_SELECT (value 1, portable select backend)" 571.IX Item "EVBACKEND_SELECT (value 1, portable select backend)"
545This is your standard \fIselect\fR\|(2) backend. Not \fIcompletely\fR standard, as 572This is your standard \fIselect\fR\|(2) backend. Not \fIcompletely\fR standard, as
546libev tries to roll its own fd_set with no limits on the number of fds, 573libev tries to roll its own fd_set with no limits on the number of fds,
582epoll scales either O(1) or O(active_fds). 609epoll scales either O(1) or O(active_fds).
583.Sp 610.Sp
584The epoll mechanism deserves honorable mention as the most misdesigned 611The epoll mechanism deserves honorable mention as the most misdesigned
585of the more advanced event mechanisms: mere annoyances include silently 612of the more advanced event mechanisms: mere annoyances include silently
586dropping file descriptors, requiring a system call per change per file 613dropping file descriptors, requiring a system call per change per file
587descriptor (and unnecessary guessing of parameters), problems with dup and 614descriptor (and unnecessary guessing of parameters), problems with dup,
615returning before the timeout value, resulting in additional iterations
616(and only giving 5ms accuracy while select on the same platform gives
588so on. The biggest issue is fork races, however \- if a program forks then 6170.1ms) and so on. The biggest issue is fork races, however \- if a program
589\&\fIboth\fR parent and child process have to recreate the epoll set, which can 618forks then \fIboth\fR parent and child process have to recreate the epoll
590take considerable time (one syscall per file descriptor) and is of course 619set, which can take considerable time (one syscall per file descriptor)
591hard to detect. 620and is of course hard to detect.
592.Sp 621.Sp
593Epoll is also notoriously buggy \- embedding epoll fds \fIshould\fR work, but 622Epoll is also notoriously buggy \- embedding epoll fds \fIshould\fR work, but
594of course \fIdoesn't\fR, and epoll just loves to report events for totally 623of course \fIdoesn't\fR, and epoll just loves to report events for totally
595\&\fIdifferent\fR file descriptors (even already closed ones, so one cannot 624\&\fIdifferent\fR file descriptors (even already closed ones, so one cannot
596even remove them from the set) than registered in the set (especially 625even remove them from the set) than registered in the set (especially
597on \s-1SMP\s0 systems). Libev tries to counter these spurious notifications by 626on \s-1SMP\s0 systems). Libev tries to counter these spurious notifications by
598employing an additional generation counter and comparing that against the 627employing an additional generation counter and comparing that against the
599events to filter out spurious ones, recreating the set when required. Last 628events to filter out spurious ones, recreating the set when required. Last
600not least, it also refuses to work with some file descriptors which work 629not least, it also refuses to work with some file descriptors which work
601perfectly fine with \f(CW\*(C`select\*(C'\fR (files, many character devices...). 630perfectly fine with \f(CW\*(C`select\*(C'\fR (files, many character devices...).
631.Sp
632Epoll is truly the train wreck analog among event poll mechanisms,
633a frankenpoll, cobbled together in a hurry, no thought to design or
634interaction with others.
602.Sp 635.Sp
603While stopping, setting and starting an I/O watcher in the same iteration 636While stopping, setting and starting an I/O watcher in the same iteration
604will result in some caching, there is still a system call per such 637will result in some caching, there is still a system call per such
605incident (because the same \fIfile descriptor\fR could point to a different 638incident (because the same \fIfile descriptor\fR could point to a different
606\&\fIfile description\fR now), so its best to avoid that. Also, \f(CW\*(C`dup ()\*(C'\fR'ed 639\&\fIfile description\fR now), so its best to avoid that. Also, \f(CW\*(C`dup ()\*(C'\fR'ed
672.el .IP "\f(CWEVBACKEND_PORT\fR (value 32, Solaris 10)" 4 705.el .IP "\f(CWEVBACKEND_PORT\fR (value 32, Solaris 10)" 4
673.IX Item "EVBACKEND_PORT (value 32, Solaris 10)" 706.IX Item "EVBACKEND_PORT (value 32, Solaris 10)"
674This uses the Solaris 10 event port mechanism. As with everything on Solaris, 707This uses the Solaris 10 event port mechanism. As with everything on Solaris,
675it's really slow, but it still scales very well (O(active_fds)). 708it's really slow, but it still scales very well (O(active_fds)).
676.Sp 709.Sp
677Please note that Solaris event ports can deliver a lot of spurious
678notifications, so you need to use non-blocking I/O or other means to avoid
679blocking when no data (or space) is available.
680.Sp
681While this backend scales well, it requires one system call per active 710While this backend scales well, it requires one system call per active
682file descriptor per loop iteration. For small and medium numbers of file 711file descriptor per loop iteration. For small and medium numbers of file
683descriptors a \*(L"slow\*(R" \f(CW\*(C`EVBACKEND_SELECT\*(C'\fR or \f(CW\*(C`EVBACKEND_POLL\*(C'\fR backend 712descriptors a \*(L"slow\*(R" \f(CW\*(C`EVBACKEND_SELECT\*(C'\fR or \f(CW\*(C`EVBACKEND_POLL\*(C'\fR backend
684might perform better. 713might perform better.
685.Sp 714.Sp
686On the positive side, with the exception of the spurious readiness 715On the positive side, this backend actually performed fully to
687notifications, this backend actually performed fully to specification
688in all tests and is fully embeddable, which is a rare feat among the 716specification in all tests and is fully embeddable, which is a rare feat
689OS-specific backends (I vastly prefer correctness over speed hacks). 717among the OS-specific backends (I vastly prefer correctness over speed
718hacks).
719.Sp
720On the negative side, the interface is \fIbizarre\fR \- so bizarre that
721even sun itself gets it wrong in their code examples: The event polling
722function sometimes returning events to the caller even though an error
723occurred, but with no indication whether it has done so or not (yes, it's
724even documented that way) \- deadly for edge-triggered interfaces where
725you absolutely have to know whether an event occurred or not because you
726have to re-arm the watcher.
727.Sp
728Fortunately libev seems to be able to work around these idiocies.
690.Sp 729.Sp
691This backend maps \f(CW\*(C`EV_READ\*(C'\fR and \f(CW\*(C`EV_WRITE\*(C'\fR in the same way as 730This backend maps \f(CW\*(C`EV_READ\*(C'\fR and \f(CW\*(C`EV_WRITE\*(C'\fR in the same way as
692\&\f(CW\*(C`EVBACKEND_POLL\*(C'\fR. 731\&\f(CW\*(C`EVBACKEND_POLL\*(C'\fR.
693.ie n .IP """EVBACKEND_ALL""" 4 732.ie n .IP """EVBACKEND_ALL""" 4
694.el .IP "\f(CWEVBACKEND_ALL\fR" 4 733.el .IP "\f(CWEVBACKEND_ALL\fR" 4
695.IX Item "EVBACKEND_ALL" 734.IX Item "EVBACKEND_ALL"
696Try all backends (even potentially broken ones that wouldn't be tried 735Try all backends (even potentially broken ones that wouldn't be tried
697with \f(CW\*(C`EVFLAG_AUTO\*(C'\fR). Since this is a mask, you can do stuff such as 736with \f(CW\*(C`EVFLAG_AUTO\*(C'\fR). Since this is a mask, you can do stuff such as
698\&\f(CW\*(C`EVBACKEND_ALL & ~EVBACKEND_KQUEUE\*(C'\fR. 737\&\f(CW\*(C`EVBACKEND_ALL & ~EVBACKEND_KQUEUE\*(C'\fR.
699.Sp 738.Sp
700It is definitely not recommended to use this flag. 739It is definitely not recommended to use this flag, use whatever
740\&\f(CW\*(C`ev_recommended_backends ()\*(C'\fR returns, or simply do not specify a backend
741at all.
742.ie n .IP """EVBACKEND_MASK""" 4
743.el .IP "\f(CWEVBACKEND_MASK\fR" 4
744.IX Item "EVBACKEND_MASK"
745Not a backend at all, but a mask to select all backend bits from a
746\&\f(CW\*(C`flags\*(C'\fR value, in case you want to mask out any backends from a flags
747value (e.g. when modifying the \f(CW\*(C`LIBEV_FLAGS\*(C'\fR environment variable).
701.RE 748.RE
702.RS 4 749.RS 4
703.Sp 750.Sp
704If one or more of the backend flags are or'ed into the flags value, 751If one or more of the backend flags are or'ed into the flags value,
705then only these backends will be tried (in the reverse order as listed 752then only these backends will be tried (in the reverse order as listed
738This function is normally used on loop objects allocated by 785This function is normally used on loop objects allocated by
739\&\f(CW\*(C`ev_loop_new\*(C'\fR, but it can also be used on the default loop returned by 786\&\f(CW\*(C`ev_loop_new\*(C'\fR, but it can also be used on the default loop returned by
740\&\f(CW\*(C`ev_default_loop\*(C'\fR, in which case it is not thread-safe. 787\&\f(CW\*(C`ev_default_loop\*(C'\fR, in which case it is not thread-safe.
741.Sp 788.Sp
742Note that it is not advisable to call this function on the default loop 789Note that it is not advisable to call this function on the default loop
743except in the rare occasion where you really need to free it's resources. 790except in the rare occasion where you really need to free its resources.
744If you need dynamically allocated loops it is better to use \f(CW\*(C`ev_loop_new\*(C'\fR 791If you need dynamically allocated loops it is better to use \f(CW\*(C`ev_loop_new\*(C'\fR
745and \f(CW\*(C`ev_loop_destroy\*(C'\fR. 792and \f(CW\*(C`ev_loop_destroy\*(C'\fR.
746.IP "ev_loop_fork (loop)" 4 793.IP "ev_loop_fork (loop)" 4
747.IX Item "ev_loop_fork (loop)" 794.IX Item "ev_loop_fork (loop)"
748This function sets a flag that causes subsequent \f(CW\*(C`ev_run\*(C'\fR iterations to 795This function sets a flag that causes subsequent \f(CW\*(C`ev_run\*(C'\fR iterations to
794\&\f(CW\*(C`ev_prepare\*(C'\fR and \f(CW\*(C`ev_check\*(C'\fR calls \- and is incremented between the 841\&\f(CW\*(C`ev_prepare\*(C'\fR and \f(CW\*(C`ev_check\*(C'\fR calls \- and is incremented between the
795prepare and check phases. 842prepare and check phases.
796.IP "unsigned int ev_depth (loop)" 4 843.IP "unsigned int ev_depth (loop)" 4
797.IX Item "unsigned int ev_depth (loop)" 844.IX Item "unsigned int ev_depth (loop)"
798Returns the number of times \f(CW\*(C`ev_run\*(C'\fR was entered minus the number of 845Returns the number of times \f(CW\*(C`ev_run\*(C'\fR was entered minus the number of
799times \f(CW\*(C`ev_run\*(C'\fR was exited, in other words, the recursion depth. 846times \f(CW\*(C`ev_run\*(C'\fR was exited normally, in other words, the recursion depth.
800.Sp 847.Sp
801Outside \f(CW\*(C`ev_run\*(C'\fR, this number is zero. In a callback, this number is 848Outside \f(CW\*(C`ev_run\*(C'\fR, this number is zero. In a callback, this number is
802\&\f(CW1\fR, unless \f(CW\*(C`ev_run\*(C'\fR was invoked recursively (or from another thread), 849\&\f(CW1\fR, unless \f(CW\*(C`ev_run\*(C'\fR was invoked recursively (or from another thread),
803in which case it is higher. 850in which case it is higher.
804.Sp 851.Sp
805Leaving \f(CW\*(C`ev_run\*(C'\fR abnormally (setjmp/longjmp, cancelling the thread 852Leaving \f(CW\*(C`ev_run\*(C'\fR abnormally (setjmp/longjmp, cancelling the thread,
806etc.), doesn't count as \*(L"exit\*(R" \- consider this as a hint to avoid such 853throwing an exception etc.), doesn't count as \*(L"exit\*(R" \- consider this
807ungentleman-like behaviour unless it's really convenient. 854as a hint to avoid such ungentleman-like behaviour unless it's really
855convenient, in which case it is fully supported.
808.IP "unsigned int ev_backend (loop)" 4 856.IP "unsigned int ev_backend (loop)" 4
809.IX Item "unsigned int ev_backend (loop)" 857.IX Item "unsigned int ev_backend (loop)"
810Returns one of the \f(CW\*(C`EVBACKEND_*\*(C'\fR flags indicating the event backend in 858Returns one of the \f(CW\*(C`EVBACKEND_*\*(C'\fR flags indicating the event backend in
811use. 859use.
812.IP "ev_tstamp ev_now (loop)" 4 860.IP "ev_tstamp ev_now (loop)" 4
870relying on all watchers to be stopped when deciding when a program has 918relying on all watchers to be stopped when deciding when a program has
871finished (especially in interactive programs), but having a program 919finished (especially in interactive programs), but having a program
872that automatically loops as long as it has to and no longer by virtue 920that automatically loops as long as it has to and no longer by virtue
873of relying on its watchers stopping correctly, that is truly a thing of 921of relying on its watchers stopping correctly, that is truly a thing of
874beauty. 922beauty.
923.Sp
924This function is also \fImostly\fR exception-safe \- you can break out of
925a \f(CW\*(C`ev_run\*(C'\fR call by calling \f(CW\*(C`longjmp\*(C'\fR in a callback, throwing a \*(C+
926exception and so on. This does not decrement the \f(CW\*(C`ev_depth\*(C'\fR value, nor
927will it clear any outstanding \f(CW\*(C`EVBREAK_ONE\*(C'\fR breaks.
875.Sp 928.Sp
876A flags value of \f(CW\*(C`EVRUN_NOWAIT\*(C'\fR will look for new events, will handle 929A flags value of \f(CW\*(C`EVRUN_NOWAIT\*(C'\fR will look for new events, will handle
877those events and any already outstanding ones, but will not wait and 930those events and any already outstanding ones, but will not wait and
878block your process in case there are no events and will return after one 931block your process in case there are no events and will return after one
879iteration of the loop. This is sometimes useful to poll and handle new 932iteration of the loop. This is sometimes useful to poll and handle new
935.Sp 988.Sp
936.Vb 4 989.Vb 4
937\& ... queue jobs here, make sure they register event watchers as long 990\& ... queue jobs here, make sure they register event watchers as long
938\& ... as they still have work to do (even an idle watcher will do..) 991\& ... as they still have work to do (even an idle watcher will do..)
939\& ev_run (my_loop, 0); 992\& ev_run (my_loop, 0);
940\& ... jobs done or somebody called unloop. yeah! 993\& ... jobs done or somebody called break. yeah!
941.Ve 994.Ve
942.IP "ev_break (loop, how)" 4 995.IP "ev_break (loop, how)" 4
943.IX Item "ev_break (loop, how)" 996.IX Item "ev_break (loop, how)"
944Can be used to make a call to \f(CW\*(C`ev_run\*(C'\fR return early (but only after it 997Can be used to make a call to \f(CW\*(C`ev_run\*(C'\fR return early (but only after it
945has processed all outstanding events). The \f(CW\*(C`how\*(C'\fR argument must be either 998has processed all outstanding events). The \f(CW\*(C`how\*(C'\fR argument must be either
946\&\f(CW\*(C`EVBREAK_ONE\*(C'\fR, which will make the innermost \f(CW\*(C`ev_run\*(C'\fR call return, or 999\&\f(CW\*(C`EVBREAK_ONE\*(C'\fR, which will make the innermost \f(CW\*(C`ev_run\*(C'\fR call return, or
947\&\f(CW\*(C`EVBREAK_ALL\*(C'\fR, which will make all nested \f(CW\*(C`ev_run\*(C'\fR calls return. 1000\&\f(CW\*(C`EVBREAK_ALL\*(C'\fR, which will make all nested \f(CW\*(C`ev_run\*(C'\fR calls return.
948.Sp 1001.Sp
949This \*(L"break state\*(R" will be cleared when entering \f(CW\*(C`ev_run\*(C'\fR again. 1002This \*(L"break state\*(R" will be cleared on the next call to \f(CW\*(C`ev_run\*(C'\fR.
950.Sp 1003.Sp
951It is safe to call \f(CW\*(C`ev_break\*(C'\fR from outside any \f(CW\*(C`ev_run\*(C'\fR calls, too. 1004It is safe to call \f(CW\*(C`ev_break\*(C'\fR from outside any \f(CW\*(C`ev_run\*(C'\fR calls, too, in
1005which case it will have no effect.
952.IP "ev_ref (loop)" 4 1006.IP "ev_ref (loop)" 4
953.IX Item "ev_ref (loop)" 1007.IX Item "ev_ref (loop)"
954.PD 0 1008.PD 0
955.IP "ev_unref (loop)" 4 1009.IP "ev_unref (loop)" 4
956.IX Item "ev_unref (loop)" 1010.IX Item "ev_unref (loop)"
979.Sp 1033.Sp
980.Vb 4 1034.Vb 4
981\& ev_signal exitsig; 1035\& ev_signal exitsig;
982\& ev_signal_init (&exitsig, sig_cb, SIGINT); 1036\& ev_signal_init (&exitsig, sig_cb, SIGINT);
983\& ev_signal_start (loop, &exitsig); 1037\& ev_signal_start (loop, &exitsig);
984\& evf_unref (loop); 1038\& ev_unref (loop);
985.Ve 1039.Ve
986.Sp 1040.Sp
987Example: For some weird reason, unregister the above signal handler again. 1041Example: For some weird reason, unregister the above signal handler again.
988.Sp 1042.Sp
989.Vb 2 1043.Vb 2
1103See also the locking example in the \f(CW\*(C`THREADS\*(C'\fR section later in this 1157See also the locking example in the \f(CW\*(C`THREADS\*(C'\fR section later in this
1104document. 1158document.
1105.IP "ev_set_userdata (loop, void *data)" 4 1159.IP "ev_set_userdata (loop, void *data)" 4
1106.IX Item "ev_set_userdata (loop, void *data)" 1160.IX Item "ev_set_userdata (loop, void *data)"
1107.PD 0 1161.PD 0
1108.IP "ev_userdata (loop)" 4 1162.IP "void *ev_userdata (loop)" 4
1109.IX Item "ev_userdata (loop)" 1163.IX Item "void *ev_userdata (loop)"
1110.PD 1164.PD
1111Set and retrieve a single \f(CW\*(C`void *\*(C'\fR associated with a loop. When 1165Set and retrieve a single \f(CW\*(C`void *\*(C'\fR associated with a loop. When
1112\&\f(CW\*(C`ev_set_userdata\*(C'\fR has never been called, then \f(CW\*(C`ev_userdata\*(C'\fR returns 1166\&\f(CW\*(C`ev_set_userdata\*(C'\fR has never been called, then \f(CW\*(C`ev_userdata\*(C'\fR returns
1113\&\f(CW0.\fR 1167\&\f(CW0\fR.
1114.Sp 1168.Sp
1115These two functions can be used to associate arbitrary data with a loop, 1169These two functions can be used to associate arbitrary data with a loop,
1116and are intended solely for the \f(CW\*(C`invoke_pending_cb\*(C'\fR, \f(CW\*(C`release\*(C'\fR and 1170and are intended solely for the \f(CW\*(C`invoke_pending_cb\*(C'\fR, \f(CW\*(C`release\*(C'\fR and
1117\&\f(CW\*(C`acquire\*(C'\fR callbacks described above, but of course can be (ab\-)used for 1171\&\f(CW\*(C`acquire\*(C'\fR callbacks described above, but of course can be (ab\-)used for
1118any other purpose as well. 1172any other purpose as well.
1424\&\f(CW\*(C`ev_clear_pending\*(C'\fR will clear the pending event, even if the watcher was 1478\&\f(CW\*(C`ev_clear_pending\*(C'\fR will clear the pending event, even if the watcher was
1425not started in the first place. 1479not started in the first place.
1426.Sp 1480.Sp
1427See also \f(CW\*(C`ev_feed_fd_event\*(C'\fR and \f(CW\*(C`ev_feed_signal_event\*(C'\fR for related 1481See also \f(CW\*(C`ev_feed_fd_event\*(C'\fR and \f(CW\*(C`ev_feed_signal_event\*(C'\fR for related
1428functions that do not need a watcher. 1482functions that do not need a watcher.
1429.SS "\s-1ASSOCIATING\s0 \s-1CUSTOM\s0 \s-1DATA\s0 \s-1WITH\s0 A \s-1WATCHER\s0"
1430.IX Subsection "ASSOCIATING CUSTOM DATA WITH A WATCHER"
1431Each watcher has, by default, a member \f(CW\*(C`void *data\*(C'\fR that you can change
1432and read at any time: libev will completely ignore it. This can be used
1433to associate arbitrary data with your watcher. If you need more data and
1434don't want to allocate memory and store a pointer to it in that data
1435member, you can also \*(L"subclass\*(R" the watcher type and provide your own
1436data:
1437.PP 1483.PP
1438.Vb 7 1484See also the \*(L"\s-1ASSOCIATING\s0 \s-1CUSTOM\s0 \s-1DATA\s0 \s-1WITH\s0 A \s-1WATCHER\s0\*(R" and \*(L"\s-1BUILDING\s0 \s-1YOUR\s0
1439\& struct my_io 1485\&\s-1OWN\s0 \s-1COMPOSITE\s0 \s-1WATCHERS\s0\*(R" idioms.
1440\& {
1441\& ev_io io;
1442\& int otherfd;
1443\& void *somedata;
1444\& struct whatever *mostinteresting;
1445\& };
1446\&
1447\& ...
1448\& struct my_io w;
1449\& ev_io_init (&w.io, my_cb, fd, EV_READ);
1450.Ve
1451.PP
1452And since your callback will be called with a pointer to the watcher, you
1453can cast it back to your own type:
1454.PP
1455.Vb 5
1456\& static void my_cb (struct ev_loop *loop, ev_io *w_, int revents)
1457\& {
1458\& struct my_io *w = (struct my_io *)w_;
1459\& ...
1460\& }
1461.Ve
1462.PP
1463More interesting and less C\-conformant ways of casting your callback type
1464instead have been omitted.
1465.PP
1466Another common scenario is to use some data structure with multiple
1467embedded watchers:
1468.PP
1469.Vb 6
1470\& struct my_biggy
1471\& {
1472\& int some_data;
1473\& ev_timer t1;
1474\& ev_timer t2;
1475\& }
1476.Ve
1477.PP
1478In this case getting the pointer to \f(CW\*(C`my_biggy\*(C'\fR is a bit more
1479complicated: Either you store the address of your \f(CW\*(C`my_biggy\*(C'\fR struct
1480in the \f(CW\*(C`data\*(C'\fR member of the watcher (for woozies), or you need to use
1481some pointer arithmetic using \f(CW\*(C`offsetof\*(C'\fR inside your watchers (for real
1482programmers):
1483.PP
1484.Vb 1
1485\& #include <stddef.h>
1486\&
1487\& static void
1488\& t1_cb (EV_P_ ev_timer *w, int revents)
1489\& {
1490\& struct my_biggy big = (struct my_biggy *)
1491\& (((char *)w) \- offsetof (struct my_biggy, t1));
1492\& }
1493\&
1494\& static void
1495\& t2_cb (EV_P_ ev_timer *w, int revents)
1496\& {
1497\& struct my_biggy big = (struct my_biggy *)
1498\& (((char *)w) \- offsetof (struct my_biggy, t2));
1499\& }
1500.Ve
1501.SS "\s-1WATCHER\s0 \s-1STATES\s0" 1486.SS "\s-1WATCHER\s0 \s-1STATES\s0"
1502.IX Subsection "WATCHER STATES" 1487.IX Subsection "WATCHER STATES"
1503There are various watcher states mentioned throughout this manual \- 1488There are various watcher states mentioned throughout this manual \-
1504active, pending and so on. In this section these states and the rules to 1489active, pending and so on. In this section these states and the rules to
1505transition between them will be described in more detail \- and while these 1490transition between them will be described in more detail \- and while these
1508.IX Item "initialiased" 1493.IX Item "initialiased"
1509Before a watcher can be registered with the event looop it has to be 1494Before a watcher can be registered with the event looop it has to be
1510initialised. This can be done with a call to \f(CW\*(C`ev_TYPE_init\*(C'\fR, or calls to 1495initialised. This can be done with a call to \f(CW\*(C`ev_TYPE_init\*(C'\fR, or calls to
1511\&\f(CW\*(C`ev_init\*(C'\fR followed by the watcher-specific \f(CW\*(C`ev_TYPE_set\*(C'\fR function. 1496\&\f(CW\*(C`ev_init\*(C'\fR followed by the watcher-specific \f(CW\*(C`ev_TYPE_set\*(C'\fR function.
1512.Sp 1497.Sp
1513In this state it is simply some block of memory that is suitable for use 1498In this state it is simply some block of memory that is suitable for
1514in an event loop. It can be moved around, freed, reused etc. at will. 1499use in an event loop. It can be moved around, freed, reused etc. at
1500will \- as long as you either keep the memory contents intact, or call
1501\&\f(CW\*(C`ev_TYPE_init\*(C'\fR again.
1515.IP "started/running/active" 4 1502.IP "started/running/active" 4
1516.IX Item "started/running/active" 1503.IX Item "started/running/active"
1517Once a watcher has been started with a call to \f(CW\*(C`ev_TYPE_start\*(C'\fR it becomes 1504Once a watcher has been started with a call to \f(CW\*(C`ev_TYPE_start\*(C'\fR it becomes
1518property of the event loop, and is actively waiting for events. While in 1505property of the event loop, and is actively waiting for events. While in
1519this state it cannot be accessed (except in a few documented ways), moved, 1506this state it cannot be accessed (except in a few documented ways), moved,
1544latter will clear any pending state the watcher might be in, regardless 1531latter will clear any pending state the watcher might be in, regardless
1545of whether it was active or not, so stopping a watcher explicitly before 1532of whether it was active or not, so stopping a watcher explicitly before
1546freeing it is often a good idea. 1533freeing it is often a good idea.
1547.Sp 1534.Sp
1548While stopped (and not pending) the watcher is essentially in the 1535While stopped (and not pending) the watcher is essentially in the
1549initialised state, that is it can be reused, moved, modified in any way 1536initialised state, that is, it can be reused, moved, modified in any way
1550you wish. 1537you wish (but when you trash the memory block, you need to \f(CW\*(C`ev_TYPE_init\*(C'\fR
1538it again).
1551.SS "\s-1WATCHER\s0 \s-1PRIORITY\s0 \s-1MODELS\s0" 1539.SS "\s-1WATCHER\s0 \s-1PRIORITY\s0 \s-1MODELS\s0"
1552.IX Subsection "WATCHER PRIORITY MODELS" 1540.IX Subsection "WATCHER PRIORITY MODELS"
1553Many event loops support \fIwatcher priorities\fR, which are usually small 1541Many event loops support \fIwatcher priorities\fR, which are usually small
1554integers that influence the ordering of event callback invocation 1542integers that influence the ordering of event callback invocation
1555between watchers in some way, all else being equal. 1543between watchers in some way, all else being equal.
1680In general you can register as many read and/or write event watchers per 1668In general you can register as many read and/or write event watchers per
1681fd as you want (as long as you don't confuse yourself). Setting all file 1669fd as you want (as long as you don't confuse yourself). Setting all file
1682descriptors to non-blocking mode is also usually a good idea (but not 1670descriptors to non-blocking mode is also usually a good idea (but not
1683required if you know what you are doing). 1671required if you know what you are doing).
1684.PP 1672.PP
1685If you cannot use non-blocking mode, then force the use of a
1686known-to-be-good backend (at the time of this writing, this includes only
1687\&\f(CW\*(C`EVBACKEND_SELECT\*(C'\fR and \f(CW\*(C`EVBACKEND_POLL\*(C'\fR). The same applies to file
1688descriptors for which non-blocking operation makes no sense (such as
1689files) \- libev doesn't guarantee any specific behaviour in that case.
1690.PP
1691Another thing you have to watch out for is that it is quite easy to 1673Another thing you have to watch out for is that it is quite easy to
1692receive \*(L"spurious\*(R" readiness notifications, that is your callback might 1674receive \*(L"spurious\*(R" readiness notifications, that is, your callback might
1693be called with \f(CW\*(C`EV_READ\*(C'\fR but a subsequent \f(CW\*(C`read\*(C'\fR(2) will actually block 1675be called with \f(CW\*(C`EV_READ\*(C'\fR but a subsequent \f(CW\*(C`read\*(C'\fR(2) will actually block
1694because there is no data. Not only are some backends known to create a 1676because there is no data. It is very easy to get into this situation even
1695lot of those (for example Solaris ports), it is very easy to get into 1677with a relatively standard program structure. Thus it is best to always
1696this situation even with a relatively standard program structure. Thus 1678use non-blocking I/O: An extra \f(CW\*(C`read\*(C'\fR(2) returning \f(CW\*(C`EAGAIN\*(C'\fR is far
1697it is best to always use non-blocking I/O: An extra \f(CW\*(C`read\*(C'\fR(2) returning
1698\&\f(CW\*(C`EAGAIN\*(C'\fR is far preferable to a program hanging until some data arrives. 1679preferable to a program hanging until some data arrives.
1699.PP 1680.PP
1700If you cannot run the fd in non-blocking mode (for example you should 1681If you cannot run the fd in non-blocking mode (for example you should
1701not play around with an Xlib connection), then you have to separately 1682not play around with an Xlib connection), then you have to separately
1702re-test whether a file descriptor is really ready with a known-to-be good 1683re-test whether a file descriptor is really ready with a known-to-be good
1703interface such as poll (fortunately in our Xlib example, Xlib already 1684interface such as poll (fortunately in the case of Xlib, it already does
1704does this on its own, so its quite safe to use). Some people additionally 1685this on its own, so its quite safe to use). Some people additionally
1705use \f(CW\*(C`SIGALRM\*(C'\fR and an interval timer, just to be sure you won't block 1686use \f(CW\*(C`SIGALRM\*(C'\fR and an interval timer, just to be sure you won't block
1706indefinitely. 1687indefinitely.
1707.PP 1688.PP
1708But really, best use non-blocking mode. 1689But really, best use non-blocking mode.
1709.PP 1690.PP
1739.PP 1720.PP
1740There is no workaround possible except not registering events 1721There is no workaround possible except not registering events
1741for potentially \f(CW\*(C`dup ()\*(C'\fR'ed file descriptors, or to resort to 1722for potentially \f(CW\*(C`dup ()\*(C'\fR'ed file descriptors, or to resort to
1742\&\f(CW\*(C`EVBACKEND_SELECT\*(C'\fR or \f(CW\*(C`EVBACKEND_POLL\*(C'\fR. 1723\&\f(CW\*(C`EVBACKEND_SELECT\*(C'\fR or \f(CW\*(C`EVBACKEND_POLL\*(C'\fR.
1743.PP 1724.PP
1725\fIThe special problem of files\fR
1726.IX Subsection "The special problem of files"
1727.PP
1728Many people try to use \f(CW\*(C`select\*(C'\fR (or libev) on file descriptors
1729representing files, and expect it to become ready when their program
1730doesn't block on disk accesses (which can take a long time on their own).
1731.PP
1732However, this cannot ever work in the \*(L"expected\*(R" way \- you get a readiness
1733notification as soon as the kernel knows whether and how much data is
1734there, and in the case of open files, that's always the case, so you
1735always get a readiness notification instantly, and your read (or possibly
1736write) will still block on the disk I/O.
1737.PP
1738Another way to view it is that in the case of sockets, pipes, character
1739devices and so on, there is another party (the sender) that delivers data
1740on its own, but in the case of files, there is no such thing: the disk
1741will not send data on its own, simply because it doesn't know what you
1742wish to read \- you would first have to request some data.
1743.PP
1744Since files are typically not-so-well supported by advanced notification
1745mechanism, libev tries hard to emulate \s-1POSIX\s0 behaviour with respect
1746to files, even though you should not use it. The reason for this is
1747convenience: sometimes you want to watch \s-1STDIN\s0 or \s-1STDOUT\s0, which is
1748usually a tty, often a pipe, but also sometimes files or special devices
1749(for example, \f(CW\*(C`epoll\*(C'\fR on Linux works with \fI/dev/random\fR but not with
1750\&\fI/dev/urandom\fR), and even though the file might better be served with
1751asynchronous I/O instead of with non-blocking I/O, it is still useful when
1752it \*(L"just works\*(R" instead of freezing.
1753.PP
1754So avoid file descriptors pointing to files when you know it (e.g. use
1755libeio), but use them when it is convenient, e.g. for \s-1STDIN/STDOUT\s0, or
1756when you rarely read from a file instead of from a socket, and want to
1757reuse the same code path.
1758.PP
1744\fIThe special problem of fork\fR 1759\fIThe special problem of fork\fR
1745.IX Subsection "The special problem of fork" 1760.IX Subsection "The special problem of fork"
1746.PP 1761.PP
1747Some backends (epoll, kqueue) do not support \f(CW\*(C`fork ()\*(C'\fR at all or exhibit 1762Some backends (epoll, kqueue) do not support \f(CW\*(C`fork ()\*(C'\fR at all or exhibit
1748useless behaviour. Libev fully supports fork, but needs to be told about 1763useless behaviour. Libev fully supports fork, but needs to be told about
1749it in the child. 1764it in the child if you want to continue to use it in the child.
1750.PP 1765.PP
1751To support fork in your programs, you either have to call 1766To support fork in your child processes, you have to call \f(CW\*(C`ev_loop_fork
1752\&\f(CW\*(C`ev_default_fork ()\*(C'\fR or \f(CW\*(C`ev_loop_fork ()\*(C'\fR after a fork in the child, 1767()\*(C'\fR after a fork in the child, enable \f(CW\*(C`EVFLAG_FORKCHECK\*(C'\fR, or resort to
1753enable \f(CW\*(C`EVFLAG_FORKCHECK\*(C'\fR, or resort to \f(CW\*(C`EVBACKEND_SELECT\*(C'\fR or 1768\&\f(CW\*(C`EVBACKEND_SELECT\*(C'\fR or \f(CW\*(C`EVBACKEND_POLL\*(C'\fR.
1754\&\f(CW\*(C`EVBACKEND_POLL\*(C'\fR.
1755.PP 1769.PP
1756\fIThe special problem of \s-1SIGPIPE\s0\fR 1770\fIThe special problem of \s-1SIGPIPE\s0\fR
1757.IX Subsection "The special problem of SIGPIPE" 1771.IX Subsection "The special problem of SIGPIPE"
1758.PP 1772.PP
1759While not really specific to libev, it is easy to forget about \f(CW\*(C`SIGPIPE\*(C'\fR: 1773While not really specific to libev, it is easy to forget about \f(CW\*(C`SIGPIPE\*(C'\fR:
2391.ie n .SS """ev_signal"" \- signal me when a signal gets signalled!" 2405.ie n .SS """ev_signal"" \- signal me when a signal gets signalled!"
2392.el .SS "\f(CWev_signal\fP \- signal me when a signal gets signalled!" 2406.el .SS "\f(CWev_signal\fP \- signal me when a signal gets signalled!"
2393.IX Subsection "ev_signal - signal me when a signal gets signalled!" 2407.IX Subsection "ev_signal - signal me when a signal gets signalled!"
2394Signal watchers will trigger an event when the process receives a specific 2408Signal watchers will trigger an event when the process receives a specific
2395signal one or more times. Even though signals are very asynchronous, libev 2409signal one or more times. Even though signals are very asynchronous, libev
2396will try it's best to deliver signals synchronously, i.e. as part of the 2410will try its best to deliver signals synchronously, i.e. as part of the
2397normal event processing, like any other event. 2411normal event processing, like any other event.
2398.PP 2412.PP
2399If you want signals to be delivered truly asynchronously, just use 2413If you want signals to be delivered truly asynchronously, just use
2400\&\f(CW\*(C`sigaction\*(C'\fR as you would do without libev and forget about sharing 2414\&\f(CW\*(C`sigaction\*(C'\fR as you would do without libev and forget about sharing
2401the signal. You can even use \f(CW\*(C`ev_async\*(C'\fR from a signal handler to 2415the signal. You can even use \f(CW\*(C`ev_async\*(C'\fR from a signal handler to
2421.IX Subsection "The special problem of inheritance over fork/execve/pthread_create" 2435.IX Subsection "The special problem of inheritance over fork/execve/pthread_create"
2422.PP 2436.PP
2423Both the signal mask (\f(CW\*(C`sigprocmask\*(C'\fR) and the signal disposition 2437Both the signal mask (\f(CW\*(C`sigprocmask\*(C'\fR) and the signal disposition
2424(\f(CW\*(C`sigaction\*(C'\fR) are unspecified after starting a signal watcher (and after 2438(\f(CW\*(C`sigaction\*(C'\fR) are unspecified after starting a signal watcher (and after
2425stopping it again), that is, libev might or might not block the signal, 2439stopping it again), that is, libev might or might not block the signal,
2426and might or might not set or restore the installed signal handler. 2440and might or might not set or restore the installed signal handler (but
2441see \f(CW\*(C`EVFLAG_NOSIGMASK\*(C'\fR).
2427.PP 2442.PP
2428While this does not matter for the signal disposition (libev never 2443While this does not matter for the signal disposition (libev never
2429sets signals to \f(CW\*(C`SIG_IGN\*(C'\fR, so handlers will be reset to \f(CW\*(C`SIG_DFL\*(C'\fR on 2444sets signals to \f(CW\*(C`SIG_IGN\*(C'\fR, so handlers will be reset to \f(CW\*(C`SIG_DFL\*(C'\fR on
2430\&\f(CW\*(C`execve\*(C'\fR), this matters for the signal mask: many programs do not expect 2445\&\f(CW\*(C`execve\*(C'\fR), this matters for the signal mask: many programs do not expect
2431certain signals to be blocked. 2446certain signals to be blocked.
2444\&\fIhas\fR to modify the signal mask, at least temporarily. 2459\&\fIhas\fR to modify the signal mask, at least temporarily.
2445.PP 2460.PP
2446So I can't stress this enough: \fIIf you do not reset your signal mask when 2461So I can't stress this enough: \fIIf you do not reset your signal mask when
2447you expect it to be empty, you have a race condition in your code\fR. This 2462you expect it to be empty, you have a race condition in your code\fR. This
2448is not a libev-specific thing, this is true for most event libraries. 2463is not a libev-specific thing, this is true for most event libraries.
2464.PP
2465\fIThe special problem of threads signal handling\fR
2466.IX Subsection "The special problem of threads signal handling"
2467.PP
2468\&\s-1POSIX\s0 threads has problematic signal handling semantics, specifically,
2469a lot of functionality (sigfd, sigwait etc.) only really works if all
2470threads in a process block signals, which is hard to achieve.
2471.PP
2472When you want to use sigwait (or mix libev signal handling with your own
2473for the same signals), you can tackle this problem by globally blocking
2474all signals before creating any threads (or creating them with a fully set
2475sigprocmask) and also specifying the \f(CW\*(C`EVFLAG_NOSIGMASK\*(C'\fR when creating
2476loops. Then designate one thread as \*(L"signal receiver thread\*(R" which handles
2477these signals. You can pass on any signals that libev might be interested
2478in by calling \f(CW\*(C`ev_feed_signal\*(C'\fR.
2449.PP 2479.PP
2450\fIWatcher-Specific Functions and Data Members\fR 2480\fIWatcher-Specific Functions and Data Members\fR
2451.IX Subsection "Watcher-Specific Functions and Data Members" 2481.IX Subsection "Watcher-Specific Functions and Data Members"
2452.IP "ev_signal_init (ev_signal *, callback, int signum)" 4 2482.IP "ev_signal_init (ev_signal *, callback, int signum)" 4
2453.IX Item "ev_signal_init (ev_signal *, callback, int signum)" 2483.IX Item "ev_signal_init (ev_signal *, callback, int signum)"
3284\& atexit (program_exits); 3314\& atexit (program_exits);
3285.Ve 3315.Ve
3286.ie n .SS """ev_async"" \- how to wake up an event loop" 3316.ie n .SS """ev_async"" \- how to wake up an event loop"
3287.el .SS "\f(CWev_async\fP \- how to wake up an event loop" 3317.el .SS "\f(CWev_async\fP \- how to wake up an event loop"
3288.IX Subsection "ev_async - how to wake up an event loop" 3318.IX Subsection "ev_async - how to wake up an event loop"
3289In general, you cannot use an \f(CW\*(C`ev_run\*(C'\fR from multiple threads or other 3319In general, you cannot use an \f(CW\*(C`ev_loop\*(C'\fR from multiple threads or other
3290asynchronous sources such as signal handlers (as opposed to multiple event 3320asynchronous sources such as signal handlers (as opposed to multiple event
3291loops \- those are of course safe to use in different threads). 3321loops \- those are of course safe to use in different threads).
3292.PP 3322.PP
3293Sometimes, however, you need to wake up an event loop you do not control, 3323Sometimes, however, you need to wake up an event loop you do not control,
3294for example because it belongs to another thread. This is what \f(CW\*(C`ev_async\*(C'\fR 3324for example because it belongs to another thread. This is what \f(CW\*(C`ev_async\*(C'\fR
3296it by calling \f(CW\*(C`ev_async_send\*(C'\fR, which is thread\- and signal safe. 3326it by calling \f(CW\*(C`ev_async_send\*(C'\fR, which is thread\- and signal safe.
3297.PP 3327.PP
3298This functionality is very similar to \f(CW\*(C`ev_signal\*(C'\fR watchers, as signals, 3328This functionality is very similar to \f(CW\*(C`ev_signal\*(C'\fR watchers, as signals,
3299too, are asynchronous in nature, and signals, too, will be compressed 3329too, are asynchronous in nature, and signals, too, will be compressed
3300(i.e. the number of callback invocations may be less than the number of 3330(i.e. the number of callback invocations may be less than the number of
3301\&\f(CW\*(C`ev_async_sent\*(C'\fR calls). 3331\&\f(CW\*(C`ev_async_sent\*(C'\fR calls). In fact, you could use signal watchers as a kind
3332of \*(L"global async watchers\*(R" by using a watcher on an otherwise unused
3333signal, and \f(CW\*(C`ev_feed_signal\*(C'\fR to signal this watcher from another thread,
3334even without knowing which loop owns the signal.
3302.PP 3335.PP
3303Unlike \f(CW\*(C`ev_signal\*(C'\fR watchers, \f(CW\*(C`ev_async\*(C'\fR works with any event loop, not 3336Unlike \f(CW\*(C`ev_signal\*(C'\fR watchers, \f(CW\*(C`ev_async\*(C'\fR works with any event loop, not
3304just the default loop. 3337just the default loop.
3305.PP 3338.PP
3306\fIQueueing\fR 3339\fIQueueing\fR
3396kind. There is a \f(CW\*(C`ev_async_set\*(C'\fR macro, but using it is utterly pointless, 3429kind. There is a \f(CW\*(C`ev_async_set\*(C'\fR macro, but using it is utterly pointless,
3397trust me. 3430trust me.
3398.IP "ev_async_send (loop, ev_async *)" 4 3431.IP "ev_async_send (loop, ev_async *)" 4
3399.IX Item "ev_async_send (loop, ev_async *)" 3432.IX Item "ev_async_send (loop, ev_async *)"
3400Sends/signals/activates the given \f(CW\*(C`ev_async\*(C'\fR watcher, that is, feeds 3433Sends/signals/activates the given \f(CW\*(C`ev_async\*(C'\fR watcher, that is, feeds
3401an \f(CW\*(C`EV_ASYNC\*(C'\fR event on the watcher into the event loop. Unlike 3434an \f(CW\*(C`EV_ASYNC\*(C'\fR event on the watcher into the event loop, and instantly
3435returns.
3436.Sp
3402\&\f(CW\*(C`ev_feed_event\*(C'\fR, this call is safe to do from other threads, signal or 3437Unlike \f(CW\*(C`ev_feed_event\*(C'\fR, this call is safe to do from other threads,
3403similar contexts (see the discussion of \f(CW\*(C`EV_ATOMIC_T\*(C'\fR in the embedding 3438signal or similar contexts (see the discussion of \f(CW\*(C`EV_ATOMIC_T\*(C'\fR in the
3404section below on what exactly this means). 3439embedding section below on what exactly this means).
3405.Sp 3440.Sp
3406Note that, as with other watchers in libev, multiple events might get 3441Note that, as with other watchers in libev, multiple events might get
3407compressed into a single callback invocation (another way to look at this 3442compressed into a single callback invocation (another way to look at this
3408is that \f(CW\*(C`ev_async\*(C'\fR watchers are level-triggered, set on \f(CW\*(C`ev_async_send\*(C'\fR, 3443is that \f(CW\*(C`ev_async\*(C'\fR watchers are level-triggered, set on \f(CW\*(C`ev_async_send\*(C'\fR,
3409reset when the event loop detects that). 3444reset when the event loop detects that).
3469.IX Item "ev_feed_fd_event (loop, int fd, int revents)" 3504.IX Item "ev_feed_fd_event (loop, int fd, int revents)"
3470Feed an event on the given fd, as if a file descriptor backend detected 3505Feed an event on the given fd, as if a file descriptor backend detected
3471the given events it. 3506the given events it.
3472.IP "ev_feed_signal_event (loop, int signum)" 4 3507.IP "ev_feed_signal_event (loop, int signum)" 4
3473.IX Item "ev_feed_signal_event (loop, int signum)" 3508.IX Item "ev_feed_signal_event (loop, int signum)"
3474Feed an event as if the given signal occurred (\f(CW\*(C`loop\*(C'\fR must be the default 3509Feed an event as if the given signal occurred. See also \f(CW\*(C`ev_feed_signal\*(C'\fR,
3475loop!). 3510which is async-safe.
3511.SH "COMMON OR USEFUL IDIOMS (OR BOTH)"
3512.IX Header "COMMON OR USEFUL IDIOMS (OR BOTH)"
3513This section explains some common idioms that are not immediately
3514obvious. Note that examples are sprinkled over the whole manual, and this
3515section only contains stuff that wouldn't fit anywhere else.
3516.SS "\s-1ASSOCIATING\s0 \s-1CUSTOM\s0 \s-1DATA\s0 \s-1WITH\s0 A \s-1WATCHER\s0"
3517.IX Subsection "ASSOCIATING CUSTOM DATA WITH A WATCHER"
3518Each watcher has, by default, a \f(CW\*(C`void *data\*(C'\fR member that you can read
3519or modify at any time: libev will completely ignore it. This can be used
3520to associate arbitrary data with your watcher. If you need more data and
3521don't want to allocate memory separately and store a pointer to it in that
3522data member, you can also \*(L"subclass\*(R" the watcher type and provide your own
3523data:
3524.PP
3525.Vb 7
3526\& struct my_io
3527\& {
3528\& ev_io io;
3529\& int otherfd;
3530\& void *somedata;
3531\& struct whatever *mostinteresting;
3532\& };
3533\&
3534\& ...
3535\& struct my_io w;
3536\& ev_io_init (&w.io, my_cb, fd, EV_READ);
3537.Ve
3538.PP
3539And since your callback will be called with a pointer to the watcher, you
3540can cast it back to your own type:
3541.PP
3542.Vb 5
3543\& static void my_cb (struct ev_loop *loop, ev_io *w_, int revents)
3544\& {
3545\& struct my_io *w = (struct my_io *)w_;
3546\& ...
3547\& }
3548.Ve
3549.PP
3550More interesting and less C\-conformant ways of casting your callback
3551function type instead have been omitted.
3552.SS "\s-1BUILDING\s0 \s-1YOUR\s0 \s-1OWN\s0 \s-1COMPOSITE\s0 \s-1WATCHERS\s0"
3553.IX Subsection "BUILDING YOUR OWN COMPOSITE WATCHERS"
3554Another common scenario is to use some data structure with multiple
3555embedded watchers, in effect creating your own watcher that combines
3556multiple libev event sources into one \*(L"super-watcher\*(R":
3557.PP
3558.Vb 6
3559\& struct my_biggy
3560\& {
3561\& int some_data;
3562\& ev_timer t1;
3563\& ev_timer t2;
3564\& }
3565.Ve
3566.PP
3567In this case getting the pointer to \f(CW\*(C`my_biggy\*(C'\fR is a bit more
3568complicated: Either you store the address of your \f(CW\*(C`my_biggy\*(C'\fR struct in
3569the \f(CW\*(C`data\*(C'\fR member of the watcher (for woozies or \*(C+ coders), or you need
3570to use some pointer arithmetic using \f(CW\*(C`offsetof\*(C'\fR inside your watchers (for
3571real programmers):
3572.PP
3573.Vb 1
3574\& #include <stddef.h>
3575\&
3576\& static void
3577\& t1_cb (EV_P_ ev_timer *w, int revents)
3578\& {
3579\& struct my_biggy big = (struct my_biggy *)
3580\& (((char *)w) \- offsetof (struct my_biggy, t1));
3581\& }
3582\&
3583\& static void
3584\& t2_cb (EV_P_ ev_timer *w, int revents)
3585\& {
3586\& struct my_biggy big = (struct my_biggy *)
3587\& (((char *)w) \- offsetof (struct my_biggy, t2));
3588\& }
3589.Ve
3590.SS "\s-1MODEL/NESTED\s0 \s-1EVENT\s0 \s-1LOOP\s0 \s-1INVOCATIONS\s0 \s-1AND\s0 \s-1EXIT\s0 \s-1CONDITIONS\s0"
3591.IX Subsection "MODEL/NESTED EVENT LOOP INVOCATIONS AND EXIT CONDITIONS"
3592Often (especially in \s-1GUI\s0 toolkits) there are places where you have
3593\&\fImodal\fR interaction, which is most easily implemented by recursively
3594invoking \f(CW\*(C`ev_run\*(C'\fR.
3595.PP
3596This brings the problem of exiting \- a callback might want to finish the
3597main \f(CW\*(C`ev_run\*(C'\fR call, but not the nested one (e.g. user clicked \*(L"Quit\*(R", but
3598a modal \*(L"Are you sure?\*(R" dialog is still waiting), or just the nested one
3599and not the main one (e.g. user clocked \*(L"Ok\*(R" in a modal dialog), or some
3600other combination: In these cases, \f(CW\*(C`ev_break\*(C'\fR will not work alone.
3601.PP
3602The solution is to maintain \*(L"break this loop\*(R" variable for each \f(CW\*(C`ev_run\*(C'\fR
3603invocation, and use a loop around \f(CW\*(C`ev_run\*(C'\fR until the condition is
3604triggered, using \f(CW\*(C`EVRUN_ONCE\*(C'\fR:
3605.PP
3606.Vb 2
3607\& // main loop
3608\& int exit_main_loop = 0;
3609\&
3610\& while (!exit_main_loop)
3611\& ev_run (EV_DEFAULT_ EVRUN_ONCE);
3612\&
3613\& // in a model watcher
3614\& int exit_nested_loop = 0;
3615\&
3616\& while (!exit_nested_loop)
3617\& ev_run (EV_A_ EVRUN_ONCE);
3618.Ve
3619.PP
3620To exit from any of these loops, just set the corresponding exit variable:
3621.PP
3622.Vb 2
3623\& // exit modal loop
3624\& exit_nested_loop = 1;
3625\&
3626\& // exit main program, after modal loop is finished
3627\& exit_main_loop = 1;
3628\&
3629\& // exit both
3630\& exit_main_loop = exit_nested_loop = 1;
3631.Ve
3632.SS "\s-1THREAD\s0 \s-1LOCKING\s0 \s-1EXAMPLE\s0"
3633.IX Subsection "THREAD LOCKING EXAMPLE"
3634Here is a fictitious example of how to run an event loop in a different
3635thread from where callbacks are being invoked and watchers are
3636created/added/removed.
3637.PP
3638For a real-world example, see the \f(CW\*(C`EV::Loop::Async\*(C'\fR perl module,
3639which uses exactly this technique (which is suited for many high-level
3640languages).
3641.PP
3642The example uses a pthread mutex to protect the loop data, a condition
3643variable to wait for callback invocations, an async watcher to notify the
3644event loop thread and an unspecified mechanism to wake up the main thread.
3645.PP
3646First, you need to associate some data with the event loop:
3647.PP
3648.Vb 6
3649\& typedef struct {
3650\& mutex_t lock; /* global loop lock */
3651\& ev_async async_w;
3652\& thread_t tid;
3653\& cond_t invoke_cv;
3654\& } userdata;
3655\&
3656\& void prepare_loop (EV_P)
3657\& {
3658\& // for simplicity, we use a static userdata struct.
3659\& static userdata u;
3660\&
3661\& ev_async_init (&u\->async_w, async_cb);
3662\& ev_async_start (EV_A_ &u\->async_w);
3663\&
3664\& pthread_mutex_init (&u\->lock, 0);
3665\& pthread_cond_init (&u\->invoke_cv, 0);
3666\&
3667\& // now associate this with the loop
3668\& ev_set_userdata (EV_A_ u);
3669\& ev_set_invoke_pending_cb (EV_A_ l_invoke);
3670\& ev_set_loop_release_cb (EV_A_ l_release, l_acquire);
3671\&
3672\& // then create the thread running ev_run
3673\& pthread_create (&u\->tid, 0, l_run, EV_A);
3674\& }
3675.Ve
3676.PP
3677The callback for the \f(CW\*(C`ev_async\*(C'\fR watcher does nothing: the watcher is used
3678solely to wake up the event loop so it takes notice of any new watchers
3679that might have been added:
3680.PP
3681.Vb 5
3682\& static void
3683\& async_cb (EV_P_ ev_async *w, int revents)
3684\& {
3685\& // just used for the side effects
3686\& }
3687.Ve
3688.PP
3689The \f(CW\*(C`l_release\*(C'\fR and \f(CW\*(C`l_acquire\*(C'\fR callbacks simply unlock/lock the mutex
3690protecting the loop data, respectively.
3691.PP
3692.Vb 6
3693\& static void
3694\& l_release (EV_P)
3695\& {
3696\& userdata *u = ev_userdata (EV_A);
3697\& pthread_mutex_unlock (&u\->lock);
3698\& }
3699\&
3700\& static void
3701\& l_acquire (EV_P)
3702\& {
3703\& userdata *u = ev_userdata (EV_A);
3704\& pthread_mutex_lock (&u\->lock);
3705\& }
3706.Ve
3707.PP
3708The event loop thread first acquires the mutex, and then jumps straight
3709into \f(CW\*(C`ev_run\*(C'\fR:
3710.PP
3711.Vb 4
3712\& void *
3713\& l_run (void *thr_arg)
3714\& {
3715\& struct ev_loop *loop = (struct ev_loop *)thr_arg;
3716\&
3717\& l_acquire (EV_A);
3718\& pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, 0);
3719\& ev_run (EV_A_ 0);
3720\& l_release (EV_A);
3721\&
3722\& return 0;
3723\& }
3724.Ve
3725.PP
3726Instead of invoking all pending watchers, the \f(CW\*(C`l_invoke\*(C'\fR callback will
3727signal the main thread via some unspecified mechanism (signals? pipe
3728writes? \f(CW\*(C`Async::Interrupt\*(C'\fR?) and then waits until all pending watchers
3729have been called (in a while loop because a) spurious wakeups are possible
3730and b) skipping inter-thread-communication when there are no pending
3731watchers is very beneficial):
3732.PP
3733.Vb 4
3734\& static void
3735\& l_invoke (EV_P)
3736\& {
3737\& userdata *u = ev_userdata (EV_A);
3738\&
3739\& while (ev_pending_count (EV_A))
3740\& {
3741\& wake_up_other_thread_in_some_magic_or_not_so_magic_way ();
3742\& pthread_cond_wait (&u\->invoke_cv, &u\->lock);
3743\& }
3744\& }
3745.Ve
3746.PP
3747Now, whenever the main thread gets told to invoke pending watchers, it
3748will grab the lock, call \f(CW\*(C`ev_invoke_pending\*(C'\fR and then signal the loop
3749thread to continue:
3750.PP
3751.Vb 4
3752\& static void
3753\& real_invoke_pending (EV_P)
3754\& {
3755\& userdata *u = ev_userdata (EV_A);
3756\&
3757\& pthread_mutex_lock (&u\->lock);
3758\& ev_invoke_pending (EV_A);
3759\& pthread_cond_signal (&u\->invoke_cv);
3760\& pthread_mutex_unlock (&u\->lock);
3761\& }
3762.Ve
3763.PP
3764Whenever you want to start/stop a watcher or do other modifications to an
3765event loop, you will now have to lock:
3766.PP
3767.Vb 2
3768\& ev_timer timeout_watcher;
3769\& userdata *u = ev_userdata (EV_A);
3770\&
3771\& ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
3772\&
3773\& pthread_mutex_lock (&u\->lock);
3774\& ev_timer_start (EV_A_ &timeout_watcher);
3775\& ev_async_send (EV_A_ &u\->async_w);
3776\& pthread_mutex_unlock (&u\->lock);
3777.Ve
3778.PP
3779Note that sending the \f(CW\*(C`ev_async\*(C'\fR watcher is required because otherwise
3780an event loop currently blocking in the kernel will have no knowledge
3781about the newly added timer. By waking up the loop it will pick up any new
3782watchers in the next event loop iteration.
3783.SS "\s-1THREADS\s0, \s-1COROUTINES\s0, \s-1CONTINUATIONS\s0, \s-1QUEUES\s0... \s-1INSTEAD\s0 \s-1OF\s0 \s-1CALLBACKS\s0"
3784.IX Subsection "THREADS, COROUTINES, CONTINUATIONS, QUEUES... INSTEAD OF CALLBACKS"
3785While the overhead of a callback that e.g. schedules a thread is small, it
3786is still an overhead. If you embed libev, and your main usage is with some
3787kind of threads or coroutines, you might want to customise libev so that
3788doesn't need callbacks anymore.
3789.PP
3790Imagine you have coroutines that you can switch to using a function
3791\&\f(CW\*(C`switch_to (coro)\*(C'\fR, that libev runs in a coroutine called \f(CW\*(C`libev_coro\*(C'\fR
3792and that due to some magic, the currently active coroutine is stored in a
3793global called \f(CW\*(C`current_coro\*(C'\fR. Then you can build your own \*(L"wait for libev
3794event\*(R" primitive by changing \f(CW\*(C`EV_CB_DECLARE\*(C'\fR and \f(CW\*(C`EV_CB_INVOKE\*(C'\fR (note
3795the differing \f(CW\*(C`;\*(C'\fR conventions):
3796.PP
3797.Vb 2
3798\& #define EV_CB_DECLARE(type) struct my_coro *cb;
3799\& #define EV_CB_INVOKE(watcher) switch_to ((watcher)\->cb)
3800.Ve
3801.PP
3802That means instead of having a C callback function, you store the
3803coroutine to switch to in each watcher, and instead of having libev call
3804your callback, you instead have it switch to that coroutine.
3805.PP
3806A coroutine might now wait for an event with a function called
3807\&\f(CW\*(C`wait_for_event\*(C'\fR. (the watcher needs to be started, as always, but it doesn't
3808matter when, or whether the watcher is active or not when this function is
3809called):
3810.PP
3811.Vb 6
3812\& void
3813\& wait_for_event (ev_watcher *w)
3814\& {
3815\& ev_cb_set (w) = current_coro;
3816\& switch_to (libev_coro);
3817\& }
3818.Ve
3819.PP
3820That basically suspends the coroutine inside \f(CW\*(C`wait_for_event\*(C'\fR and
3821continues the libev coroutine, which, when appropriate, switches back to
3822this or any other coroutine. I am sure if you sue this your own :)
3823.PP
3824You can do similar tricks if you have, say, threads with an event queue \-
3825instead of storing a coroutine, you store the queue object and instead of
3826switching to a coroutine, you push the watcher onto the queue and notify
3827any waiters.
3828.PP
3829To embed libev, see \s-1EMBEDDING\s0, but in short, it's easiest to create two
3830files, \fImy_ev.h\fR and \fImy_ev.c\fR that include the respective libev files:
3831.PP
3832.Vb 4
3833\& // my_ev.h
3834\& #define EV_CB_DECLARE(type) struct my_coro *cb;
3835\& #define EV_CB_INVOKE(watcher) switch_to ((watcher)\->cb);
3836\& #include "../libev/ev.h"
3837\&
3838\& // my_ev.c
3839\& #define EV_H "my_ev.h"
3840\& #include "../libev/ev.c"
3841.Ve
3842.PP
3843And then use \fImy_ev.h\fR when you would normally use \fIev.h\fR, and compile
3844\&\fImy_ev.c\fR into your project. When properly specifying include paths, you
3845can even use \fIev.h\fR as header file name directly.
3476.SH "LIBEVENT EMULATION" 3846.SH "LIBEVENT EMULATION"
3477.IX Header "LIBEVENT EMULATION" 3847.IX Header "LIBEVENT EMULATION"
3478Libev offers a compatibility emulation layer for libevent. It cannot 3848Libev offers a compatibility emulation layer for libevent. It cannot
3479emulate the internals of libevent, so here are some usage hints: 3849emulate the internals of libevent, so here are some usage hints:
3850.IP "\(bu" 4
3851Only the libevent\-1.4.1\-beta \s-1API\s0 is being emulated.
3852.Sp
3853This was the newest libevent version available when libev was implemented,
3854and is still mostly unchanged in 2010.
3480.IP "\(bu" 4 3855.IP "\(bu" 4
3481Use it by including <event.h>, as usual. 3856Use it by including <event.h>, as usual.
3482.IP "\(bu" 4 3857.IP "\(bu" 4
3483The following members are fully supported: ev_base, ev_callback, 3858The following members are fully supported: ev_base, ev_callback,
3484ev_arg, ev_fd, ev_res, ev_events. 3859ev_arg, ev_fd, ev_res, ev_events.
3490Priorities are not currently supported. Initialising priorities 3865Priorities are not currently supported. Initialising priorities
3491will fail and all watchers will have the same priority, even though there 3866will fail and all watchers will have the same priority, even though there
3492is an ev_pri field. 3867is an ev_pri field.
3493.IP "\(bu" 4 3868.IP "\(bu" 4
3494In libevent, the last base created gets the signals, in libev, the 3869In libevent, the last base created gets the signals, in libev, the
3495first base created (== the default loop) gets the signals. 3870base that registered the signal gets the signals.
3496.IP "\(bu" 4 3871.IP "\(bu" 4
3497Other members are not supported. 3872Other members are not supported.
3498.IP "\(bu" 4 3873.IP "\(bu" 4
3499The libev emulation is \fInot\fR \s-1ABI\s0 compatible to libevent, you need 3874The libev emulation is \fInot\fR \s-1ABI\s0 compatible to libevent, you need
3500to use the libev header file and library. 3875to use the libev header file and library.
3518Care has been taken to keep the overhead low. The only data member the \*(C+ 3893Care has been taken to keep the overhead low. The only data member the \*(C+
3519classes add (compared to plain C\-style watchers) is the event loop pointer 3894classes add (compared to plain C\-style watchers) is the event loop pointer
3520that the watcher is associated with (or no additional members at all if 3895that the watcher is associated with (or no additional members at all if
3521you disable \f(CW\*(C`EV_MULTIPLICITY\*(C'\fR when embedding libev). 3896you disable \f(CW\*(C`EV_MULTIPLICITY\*(C'\fR when embedding libev).
3522.PP 3897.PP
3523Currently, functions, and static and non-static member functions can be 3898Currently, functions, static and non-static member functions and classes
3524used as callbacks. Other types should be easy to add as long as they only 3899with \f(CW\*(C`operator ()\*(C'\fR can be used as callbacks. Other types should be easy
3525need one additional pointer for context. If you need support for other 3900to add as long as they only need one additional pointer for context. If
3526types of functors please contact the author (preferably after implementing 3901you need support for other types of functors please contact the author
3527it). 3902(preferably after implementing it).
3528.PP 3903.PP
3529Here is a list of things available in the \f(CW\*(C`ev\*(C'\fR namespace: 3904Here is a list of things available in the \f(CW\*(C`ev\*(C'\fR namespace:
3530.ie n .IP """ev::READ"", ""ev::WRITE"" etc." 4 3905.ie n .IP """ev::READ"", ""ev::WRITE"" etc." 4
3531.el .IP "\f(CWev::READ\fR, \f(CWev::WRITE\fR etc." 4 3906.el .IP "\f(CWev::READ\fR, \f(CWev::WRITE\fR etc." 4
3532.IX Item "ev::READ, ev::WRITE etc." 3907.IX Item "ev::READ, ev::WRITE etc."
4370.PP 4745.PP
4371.Vb 2 4746.Vb 2
4372\& #include "ev_cpp.h" 4747\& #include "ev_cpp.h"
4373\& #include "ev.c" 4748\& #include "ev.c"
4374.Ve 4749.Ve
4375.SH "INTERACTION WITH OTHER PROGRAMS OR LIBRARIES" 4750.SH "INTERACTION WITH OTHER PROGRAMS, LIBRARIES OR THE ENVIRONMENT"
4376.IX Header "INTERACTION WITH OTHER PROGRAMS OR LIBRARIES" 4751.IX Header "INTERACTION WITH OTHER PROGRAMS, LIBRARIES OR THE ENVIRONMENT"
4377.SS "\s-1THREADS\s0 \s-1AND\s0 \s-1COROUTINES\s0" 4752.SS "\s-1THREADS\s0 \s-1AND\s0 \s-1COROUTINES\s0"
4378.IX Subsection "THREADS AND COROUTINES" 4753.IX Subsection "THREADS AND COROUTINES"
4379\fI\s-1THREADS\s0\fR 4754\fI\s-1THREADS\s0\fR
4380.IX Subsection "THREADS" 4755.IX Subsection "THREADS"
4381.PP 4756.PP
4428An example use would be to communicate signals or other events that only 4803An example use would be to communicate signals or other events that only
4429work in the default loop by registering the signal watcher with the 4804work in the default loop by registering the signal watcher with the
4430default loop and triggering an \f(CW\*(C`ev_async\*(C'\fR watcher from the default loop 4805default loop and triggering an \f(CW\*(C`ev_async\*(C'\fR watcher from the default loop
4431watcher callback into the event loop interested in the signal. 4806watcher callback into the event loop interested in the signal.
4432.PP 4807.PP
4433\s-1THREAD\s0 \s-1LOCKING\s0 \s-1EXAMPLE\s0 4808See also \*(L"\s-1THREAD\s0 \s-1LOCKING\s0 \s-1EXAMPLE\s0\*(R".
4434.IX Subsection "THREAD LOCKING EXAMPLE"
4435.PP
4436Here is a fictitious example of how to run an event loop in a different
4437thread than where callbacks are being invoked and watchers are
4438created/added/removed.
4439.PP
4440For a real-world example, see the \f(CW\*(C`EV::Loop::Async\*(C'\fR perl module,
4441which uses exactly this technique (which is suited for many high-level
4442languages).
4443.PP
4444The example uses a pthread mutex to protect the loop data, a condition
4445variable to wait for callback invocations, an async watcher to notify the
4446event loop thread and an unspecified mechanism to wake up the main thread.
4447.PP
4448First, you need to associate some data with the event loop:
4449.PP
4450.Vb 6
4451\& typedef struct {
4452\& mutex_t lock; /* global loop lock */
4453\& ev_async async_w;
4454\& thread_t tid;
4455\& cond_t invoke_cv;
4456\& } userdata;
4457\&
4458\& void prepare_loop (EV_P)
4459\& {
4460\& // for simplicity, we use a static userdata struct.
4461\& static userdata u;
4462\&
4463\& ev_async_init (&u\->async_w, async_cb);
4464\& ev_async_start (EV_A_ &u\->async_w);
4465\&
4466\& pthread_mutex_init (&u\->lock, 0);
4467\& pthread_cond_init (&u\->invoke_cv, 0);
4468\&
4469\& // now associate this with the loop
4470\& ev_set_userdata (EV_A_ u);
4471\& ev_set_invoke_pending_cb (EV_A_ l_invoke);
4472\& ev_set_loop_release_cb (EV_A_ l_release, l_acquire);
4473\&
4474\& // then create the thread running ev_loop
4475\& pthread_create (&u\->tid, 0, l_run, EV_A);
4476\& }
4477.Ve
4478.PP
4479The callback for the \f(CW\*(C`ev_async\*(C'\fR watcher does nothing: the watcher is used
4480solely to wake up the event loop so it takes notice of any new watchers
4481that might have been added:
4482.PP
4483.Vb 5
4484\& static void
4485\& async_cb (EV_P_ ev_async *w, int revents)
4486\& {
4487\& // just used for the side effects
4488\& }
4489.Ve
4490.PP
4491The \f(CW\*(C`l_release\*(C'\fR and \f(CW\*(C`l_acquire\*(C'\fR callbacks simply unlock/lock the mutex
4492protecting the loop data, respectively.
4493.PP
4494.Vb 6
4495\& static void
4496\& l_release (EV_P)
4497\& {
4498\& userdata *u = ev_userdata (EV_A);
4499\& pthread_mutex_unlock (&u\->lock);
4500\& }
4501\&
4502\& static void
4503\& l_acquire (EV_P)
4504\& {
4505\& userdata *u = ev_userdata (EV_A);
4506\& pthread_mutex_lock (&u\->lock);
4507\& }
4508.Ve
4509.PP
4510The event loop thread first acquires the mutex, and then jumps straight
4511into \f(CW\*(C`ev_run\*(C'\fR:
4512.PP
4513.Vb 4
4514\& void *
4515\& l_run (void *thr_arg)
4516\& {
4517\& struct ev_loop *loop = (struct ev_loop *)thr_arg;
4518\&
4519\& l_acquire (EV_A);
4520\& pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, 0);
4521\& ev_run (EV_A_ 0);
4522\& l_release (EV_A);
4523\&
4524\& return 0;
4525\& }
4526.Ve
4527.PP
4528Instead of invoking all pending watchers, the \f(CW\*(C`l_invoke\*(C'\fR callback will
4529signal the main thread via some unspecified mechanism (signals? pipe
4530writes? \f(CW\*(C`Async::Interrupt\*(C'\fR?) and then waits until all pending watchers
4531have been called (in a while loop because a) spurious wakeups are possible
4532and b) skipping inter-thread-communication when there are no pending
4533watchers is very beneficial):
4534.PP
4535.Vb 4
4536\& static void
4537\& l_invoke (EV_P)
4538\& {
4539\& userdata *u = ev_userdata (EV_A);
4540\&
4541\& while (ev_pending_count (EV_A))
4542\& {
4543\& wake_up_other_thread_in_some_magic_or_not_so_magic_way ();
4544\& pthread_cond_wait (&u\->invoke_cv, &u\->lock);
4545\& }
4546\& }
4547.Ve
4548.PP
4549Now, whenever the main thread gets told to invoke pending watchers, it
4550will grab the lock, call \f(CW\*(C`ev_invoke_pending\*(C'\fR and then signal the loop
4551thread to continue:
4552.PP
4553.Vb 4
4554\& static void
4555\& real_invoke_pending (EV_P)
4556\& {
4557\& userdata *u = ev_userdata (EV_A);
4558\&
4559\& pthread_mutex_lock (&u\->lock);
4560\& ev_invoke_pending (EV_A);
4561\& pthread_cond_signal (&u\->invoke_cv);
4562\& pthread_mutex_unlock (&u\->lock);
4563\& }
4564.Ve
4565.PP
4566Whenever you want to start/stop a watcher or do other modifications to an
4567event loop, you will now have to lock:
4568.PP
4569.Vb 2
4570\& ev_timer timeout_watcher;
4571\& userdata *u = ev_userdata (EV_A);
4572\&
4573\& ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
4574\&
4575\& pthread_mutex_lock (&u\->lock);
4576\& ev_timer_start (EV_A_ &timeout_watcher);
4577\& ev_async_send (EV_A_ &u\->async_w);
4578\& pthread_mutex_unlock (&u\->lock);
4579.Ve
4580.PP
4581Note that sending the \f(CW\*(C`ev_async\*(C'\fR watcher is required because otherwise
4582an event loop currently blocking in the kernel will have no knowledge
4583about the newly added timer. By waking up the loop it will pick up any new
4584watchers in the next event loop iteration.
4585.PP 4809.PP
4586\fI\s-1COROUTINES\s0\fR 4810\fI\s-1COROUTINES\s0\fR
4587.IX Subsection "COROUTINES" 4811.IX Subsection "COROUTINES"
4588.PP 4812.PP
4589Libev is very accommodating to coroutines (\*(L"cooperative threads\*(R"): 4813Libev is very accommodating to coroutines (\*(L"cooperative threads\*(R"):
5073.IX Item "real time" 5297.IX Item "real time"
5074The physical time that is observed. It is apparently strictly monotonic :) 5298The physical time that is observed. It is apparently strictly monotonic :)
5075.IP "wall-clock time" 4 5299.IP "wall-clock time" 4
5076.IX Item "wall-clock time" 5300.IX Item "wall-clock time"
5077The time and date as shown on clocks. Unlike real time, it can actually 5301The time and date as shown on clocks. Unlike real time, it can actually
5078be wrong and jump forwards and backwards, e.g. when the you adjust your 5302be wrong and jump forwards and backwards, e.g. when you adjust your
5079clock. 5303clock.
5080.IP "watcher" 4 5304.IP "watcher" 4
5081.IX Item "watcher" 5305.IX Item "watcher"
5082A data structure that describes interest in certain events. Watchers need 5306A data structure that describes interest in certain events. Watchers need
5083to be started (attached to an event loop) before they can receive events. 5307to be started (attached to an event loop) before they can receive events.
5084.SH "AUTHOR" 5308.SH "AUTHOR"
5085.IX Header "AUTHOR" 5309.IX Header "AUTHOR"
5086Marc Lehmann <libev@schmorp.de>, with repeated corrections by Mikael 5310Marc Lehmann <libev@schmorp.de>, with repeated corrections by Mikael
5087Magnusson and Emanuele Giaquinta. 5311Magnusson and Emanuele Giaquinta, and minor corrections by many others.

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines