cthreadcomm · Section 3
ceventloop_add
NAME
ceventloop_add - register a selectable with an event loop
LIBRARY
C Collections (libccollections, -lccollections)
SYNOPSIS
#include <ccollections/cthreadcomm.h>
ceventloop_reg ceventloop_add(ceventloop loop, cselectable sel,
ceventloop_handlers handlers, void *arg,
char **err_str);
DESCRIPTION
This function registers sel with loop, and the loop then dispatches the readiness of sel to handlers for the whole life of the registration, or until a call to ceventloop_remove(). You build sel exactly as you build one for cselect(), and you can use cselectable_fd, ccircq_selectable, cdynmq_selectable and cchan_selectable directly. One registration covers exactly one direction, which is sel.dir. If you want both directions live on one fd at the same time (for example a full-duplex pipe that a program reads and writes together), call ceventloop_add() twice and you get two independent handles. If you want to change the direction of one registration over time (for example a connecting socket, which wants write interest until the connect finishes and read interest after that), use one registration and ceventloop_modify(3). The function refuses a second selectable for a direction that is already in use on the same fd, such as two read registrations on one fd; the call then returns CEVENTLOOP_REG_NULL and err_str names that cause (see RETURN VALUE). A queue selectable and a cchan selectable have no such restriction. You can make any number of ceventloop_add() calls for the same queue and the same direction, in one ceventloop or in several, and mix them with a cselect() call that runs at the same time on the same queue and direction. All of them are live together, and each one gets its turn. cselect() gives the same guarantee: Any number of threads can watch one queue at the same time. When a message arrives while more than one such listener is registered, the library wakes exactly one listener for each producer call and each consumer call. Once the callback of the woken listener returns, that listener checks whether the queue is ready for its direction, and if it is, it passes the wake to the next listener in the line, so no live listener is passed over for ever. A cselect() caller that wakes and then leaves without acting on the queue passes the wake on in the same way, and so does a registration that is removed, or whose loop is shut down or destroyed, before it acted on its wake, so no wake is lost. A registration of a loop that is shut down takes no further wakes, and the other listeners of the queue keep getting every message while it waits for its remove or for the destroy of its loop. A registration whose callback moved at least one message is dispatched again for as long as the queue stays ready for its direction. Moved means that for a read registration the queue holds fewer messages after the callback than before it, and for a write registration it holds more. This holds for each registration on its own, wherever it sits in the line and whatever the other listeners of the queue do. So a backlog drains without another send or receive, even when each callback receives one message, and a listener that declines the queue never holds up one that takes it. A registration whose callback neither receives nor sends passes the wake on, and a wake that every listener declines stops once it has visited each of them, so listeners that ignore a ready queue do not spin. A write registration whose callback sends on every call is dispatched again for as long as the queue has room, exactly as a writable fd is, so remove it when it has nothing to send. A queue whose sends are turned off is ready for a write registration, in the way a pipe whose reader has gone is ready for POLLOUT. Turning sends off calls on_writable once, a write registration that is added while sends are off gets one call as soon as it is added, and the send of the callback then returns ccol_not_permitted, which moves nothing, so the wake is passed on as described above. The registration is called again only after a later event on the queue, such as a receive or another change of the send state. A queue that you register this way must live longer than its registration. ccircq_destroy(3), cdynmq_destroy(3) and cchan_destroy(3) assert if a live registration, a cselect() call or a cselect_timed() call watches the queue; without those asserts the waiter would stay linked and point to the mutex of the queue, which the destroy is about to free. Call ceventloop_remove() before you destroy the queue. Destroying the loop first is fine, because ceventloop_destroy() and ceventloop_remove() always unlink the waiter of a queue before anything touches it again. ceventloop_remove() does not wait for a callback that it already gave to a reactor thread, so the destroy that comes after it blocks until any such callback is done with the queue. The page of that destroy names the two things that a caller must not do while it waits. on_readable, on_writable and on_error share one prototype: void fn(ceventloop loop, ceventloop_reg reg, cselectable *sel, void *arg); loop is the loop that owns the registration, sel is its selectable and arg is the arg of this call. reg is the handle of the registration itself, exactly the value that ceventloop_add() returns for it, and a callback can pass it to ceventloop_remove(3), ceventloop_pause(3), ceventloop_resume(3), ceventloop_modify(3) and ceventloop_reg_generation(3). The registration is live, and a callback of it can run, before ceventloop_add() returns: With num_reactor_threads > 1 a callback can run on a dispatch worker while the calling thread is inside this function, for example when the fd is ready already at the time of the call. reg is valid in that callback too, so a callback never has to read the handle from storage that the calling thread writes after this call returns. handlers.on_readable reports readiness only, for every type of selectable, and ceventloop never does the receive itself. For an fd selectable the callback makes its own read(2) or recv(2) call on sel->fd. For a queue selectable or a cchan selectable, the callback makes its own ccircq_try_recv() or cdynmq_try_recv() call on sel->cq or sel->dq. For a cchan selectable that call is ccircq_try_recv() on sel->cq, and never cchan_try_recv(): The callback runs on a thread of the loop, which the channel counts as a worker, so a cchan_* call there can reach the other queue of the channel (see cchan_selectable(3)). In both cases another consumer can get to the data first. That TOCTOU race is part of the design and is the same contract as the write direction of cselect(): The receive call of the callback can find nothing, and the callback must handle that well. For a queue selectable one notification does not always mean exactly one message, because several sends can run faster than the dispatch, and the callback then sees them as one notification. A callback that receives one message on each call drains a burst all the same, because the loop dispatches the listeners again while the queue stays ready after a callback that moved a message (see above). A callback can also receive in a loop until the call returns ccol_container_empty, which drains a burst in fewer dispatches. handlers.on_writable runs with no payload, for both kinds of selectable. The caller makes its own write(2) or send(2) call, or for a queue its own try-send call, which does not block: ccircq_try_send() on sel->cq for a circular queue or a cchan selectable, and cdynmq_send() on sel->dq for a dynamic queue. handlers.on_error runs only for an fd selectable, for each condition that the direction of the registration has no other handler for. EPOLLERR and EPOLLHUP go there whenever the direction is not also ready. For a read registration with on_readable set to NULL, the close or the shutdown of the peer's end goes there too; that is EPOLLRDHUP, which an ordinary TCP close(2) raises without EPOLLHUP. If the direction does have its own handler, that handler wins the same event whenever the direction is also ready. When data arrives together with the error, a read registration with on_readable set gets on_readable and not on_error: EPOLLIN and EPOLLRDHUP are not mutually exclusive with EPOLLERR and EPOLLHUP, and the loop delivers the bytes that arrived before the peer went away. For the same reason a write registration with on_writable set gets on_writable, since EPOLLOUT is not mutually exclusive with EPOLLERR and EPOLLHUP either: A socket in an error state is writable too, because a write(2) call on it returns an error at once and does not block. A queue selectable never produces an error condition. A registration with on_error set to NULL gets EPOLLERR and EPOLLHUP through the handler of its own direction instead, as libevent and libuv deliver them: on_readable for a read registration, on_writable for a write registration. The read(2), recv(2), write(2) or send(2) call of that handler then reports the condition, with -1 and the error in errno, or with 0 for an end of file. A read or a write of a socket also clears a pending socket error, so a transient error (such as the ICMP port unreachable that a connected UDP socket reports as ECONNREFUSED) costs one failed receive, and the datagrams that arrive after it reach on_readable as usual. When both directions of one fd have such a handler, one event reaches both: on_readable first, then on_writable, one after the other on one thread, and each one sees whatever the other left of the condition. Each of on_readable, on_writable and on_error can be NULL. For an fd selectable the loop does not arm a direction that has no handler of its own, so a registration can carry on_error alone and leave the handler of its own direction NULL. Such an error-only registration costs no dispatch until something goes wrong, in both directions and for every kind of fd that the loop watches (a socket, a pipe, a FIFO or a terminal). That includes an error-only registration on the write direction of a healthy socket, which is writable from the moment it is registered, and one on either end of a pipe, where the close of the other end is the error that it reports. Every condition here, an error included, is level-triggered: The loop reports it, and calls the handler, again and again until a call removes or pauses the registration or the condition clears. A hang-up stays true, so a pipe whose writer closed, or a socket whose peer is gone, keeps reporting it, and a read(2) of it keeps returning 0. A handler that reads an end of file must therefore remove the registration (or pause it), exactly as it must for any other readiness that it leaves in place. Remove it before you close the fd; see ceventloop_remove(3). On the BSDs and macOS an error-only registration (on_error alone) can hear each error or hang-up once, when it happens, and not on every wait, because the kernel filter that watches it there can be edge-triggered; a handler that removes or pauses the registration works the same on every system. An fd event that no handler of the registration can take is dropped, and the loop also stops watching that registration, because the hang-up behind it can stay true and would otherwise be reported on every wait. Only a registration with neither the handler of its direction nor on_error ends up there, for example a read registration with both on_readable and on_error set to NULL whose peer hangs up. The registration stays registered, and a registration for the other direction of the same fd stays watched. ceventloop_resume(3) and a successful ceventloop_modify(3) arm it again, whether the modify changes the direction or keeps it. handlers.on_removed, unlike the other three, is not tied to a readiness event. It runs exactly once, at the moment when the library can prove that the caller can free arg. After ceventloop_remove() it runs asynchronously and never from inside that call, while ceventloop_destroy(3) runs every on_removed that is due from inside the call, on the destroying thread, before it returns. The NOTES of ceventloop_remove(3) give the exact guarantee and explain why ceventloop_remove() itself cannot always give it synchronously. You can leave on_removed NULL for a registration whose arg needs no notice before a free. Calling ceventloop_destroy(3) on the owning loop from on_removed is fatal: On an ordinary removal on_removed runs on the reactor thread, where a destroy of its own loop is refused, and during a destroy the handle is already destroyed. A callback runs on one of the background reactor threads of loop and never on the thread that calls this function, and how long a callback can take depends on how the loop is configured. With the default of one reactor thread, that one thread both polls and runs the callbacks, so a callback that blocks stalls every other registration on the loop for as long as it blocks; keep such a callback short and give slow work to a thread of your own. With more than one reactor thread there is one dedicated poller and the callbacks run on a separate dispatch pool, which is what that configuration is for, so a callback can take real time without starving the polling. A callback holds no internal lock of the loop while it runs, so it can take an application lock of its own, and it can call ceventloop_modify(3), ceventloop_pause(3) and ceventloop_remove(3). Those calls keep working while ceventloop_shutdown(3) or ceventloop_destroy(3) drains the loop, because loop stays a live handle until that drain ends. So a callback that removes every registration of its fd and then frees arg is safe during a destroy on another thread: No callback of those registrations runs after the removals return. With more than one reactor thread, the loop never runs the callback of one registration concurrently with itself (see num_reactor_threads in ceventloop_create_mp(3)). A read registration and a write registration that share one fd never run at the same time as each other either, so a pair of callbacks that shares state across both directions of one fd (such as one TLS connection object) needs no lock of its own for that. This rule does not extend to two different fds: The callbacks of different registrations can run at the same time on different reactor threads.
PARAMETERS
loop ceventloop to register with.
sel What to watch. See DESCRIPTION.
handlers Group of callbacks. Each callback can be NULL.
arg Opaque pointer that the loop gives to every callback of this
registration.
err_str Optional pointer that gets an error string on failure, and
NULL on success.
RETURN VALUE
A new registration handle on success. CEVENTLOOP_REG_NULL on failure. The call fails when loop is CEVENTLOOP_NULL, a stale handle or a handle that has already been destroyed; when sel is malformed because its type or dir is not valid, its queue pointer is NULL or its fd is negative; when loop is shut down (ceventloop_shutdown(3)) and nothing of it dispatches any more; when the direction is already in use on that fd; or when an allocation or a system call failed (epoll_ctl or kevent, eventfd, or the initialisation of a mutex or a condition variable). An fd that names a regular file or a directory is always refused this way, because epoll(7) cannot watch such a file (epoll_ctl(2) fails with EPERM). The FreeBSD build refuses it too, even though kqueue(2) could watch it, so that the same program behaves the same on both systems. When err_str is not NULL, *err_str names the cause, with one message per class. A loop that is shut down gives a message containing "shut down". A direction already in use gives one containing "direction already in use", and no retry can succeed in that case. A failed allocation gives one containing "failed to allocate", and a failed system call one containing "a system call failed".
NOTES
Like ceventloop itself, ceventloop_reg is an opaque VALUE handle and not a pointer. Never cast it to or from void*, never compare it through a pointer cast, and never treat it as an address. Compare it with CEVENTLOOP_REG_NULL, or test it for truth, since CEVENTLOOP_REG_NULL is 0. Every use of a ceventloop_reg is resolved against its loop's registration table before anything is dereferenced, so a stale or removed handle is always caught and refused cleanly, never turned into a use-after-free. That holds even while another thread races a ceventloop_modify, ceventloop_pause, ceventloop_resume, ceventloop_remove or ceventloop_reg_generation call on the very same registration.
THREAD SAFETY
Safe to call at the same time as ceventloop_remove() and ceventloop_modify(), and from a callback running on the reactor thread.
EXAMPLES
void on_msg(ceventloop loop, ceventloop_reg reg, cselectable *sel, void *arg) { (void)loop; (void)reg; (void)arg; cmessage msg; if (ccircq_try_recv(sel->cq, &msg) != ccol_success) return; printf("job: %.*s\n", (int)msg.size, (char *)msg.data); free(msg.data); } ccircq *jobs = ccircq_create(64, NULL); ceventloop_handlers handlers = { .on_readable = on_msg }; ceventloop_reg reg = ceventloop_add( loop, ccircq_selectable(jobs, cselect_read), handlers, NULL, NULL);
SEE ALSO
ceventloop_create(3), ceventloop_modify(3), ceventloop_pause(3), ceventloop_resume(3), ceventloop_remove(3), ceventloop_reg_generation(3), cselectable_fd(3), ccircq_selectable(3), cdynmq_selectable(3), cchan_selectable(3), ccircq_destroy(3), cdynmq_destroy(3), cchan_destroy(3)