C Collections

cthreadcomm · Section 3

cselect, cselect_timed

cselect, cselect_timed - wait for readiness on any of several queues or file descriptors (blocking)

C Collections (libccollections, -lccollections)

#include <ccollections/cthreadcomm.h>
 
ccol_retval cselect(size_t *ready_index, size_t n,
                        cselectable *selectables);
 
ccol_retval cselect_timed(size_t *ready_index, size_t n,
                        cselectable *selectables, uint64_t timeout_us);

The call blocks the caller's thread until at least one of the n
selectables is ready, writes the 0-based index of that selectable into
*ready_index and returns.
 
cselect() never does the receive or the send itself, for any type
of selectable; it only reports readiness.  Right after it returns, the
caller has to make its own non-blocking receive or send on the
selectable that won: ccircq_try_recv(), cdynmq_try_recv(),
ccircq_try_send() or cdynmq_send() for a queue
selectable, and read(2), recv(2), write(2) or send(2) on
selectables[*ready_index].fd for an fd selectable.  Another consumer or
producer can get in between the return of cselect() and that call.
That is the same time-of-check to time-of-use contract as POSIX
select(2), so the call must not block and the caller must check its
result.
 
cselect_timed() takes one more argument, timeout_us.  UINT64_MAX
behaves like cselect() and waits forever, and 0 polls without
blocking.  Any other value is the longest time, in microseconds, to
wait before the call returns ccol_timed_out.  A value too large to form
a deadline saturates to the latest deadline the clock can hold and
never wraps around into the past.  The deadline is computed once,
before the wait loop, from CLOCK_MONOTONIC, so changing the system time
cannot make the timeout longer.
 
cselect() is the same as cselect_timed(ready_index, n,
selectables, UINT64_MAX).
 
A cselectable holds a ccircq, a cdynmq or a
raw file descriptor, and you build one with ccircq_selectable(),
cdynmq_selectable(), cchan_selectable() or
cselectable_fd().  A channel is turned into one of its circular
queues before it gets here, so cselect() treats it exactly like a
plain circular queue.
 
With at least one fd selectable, the call first asks poll(2), without
waiting, which fds are ready in the direction of their selectables.  If
it finds a ready selectable at that point, it makes no other system
call for its fds.  Only a call that has to wait watches the file
descriptors through an epoll(7) instance on Linux, or a kqueue(2) on
the BSDs and macOS, created with close-on-exec, together with one wake
descriptor (an eventfd(2) on Linux) per queue selectable, and closes
them all before it returns.  Each fd is watched for the rest of the
call, level-triggered, in the direction of its selectable, and the call
never changes or closes the fd itself.  A call with queue selectables
only creates no file descriptor at all.
 
The call allocates a small amount of memory per selectable and frees all
of it on every return path.  Any number of threads can call
cselect() on the same queue at the same time.
 
A producer wakes exactly one waiter for each message it sends or each
slot it frees, never all of them at once.  A caller that stops watching
a queue while the queue is still ready for its direction passes the
wake on to the next waiter, so the notification it got is never lost.
That holds for every way of leaving the call: Another selectable
becomes ready, the deadline passes, an fd fires, or the call returns an
error.  No waiter is left sleeping on a queue that has something for
it.
 
Every selectable is checked at least once before the call waits, so a
selectable that is ready at the start is reported, also with a
timeout_us of 0.  No wakeup is lost: A send or a free that happens
between that check and the wait ends the wait too.  A spurious wakeup
or a signal neither ends the wait early nor moves the deadline.  On the
fd path the remaining time is rounded up to whole milliseconds, so the
wait never ends before the deadline.  A timeout longer than one kernel
wait can take (INT_MAX milliseconds, about 24.8 days) takes several
waits, and ccol_timed_out comes only once the whole timeout_us has
passed.  After the deadline the call checks the file descriptors one
last time and then returns ccol_timed_out.  If the wait itself fails,
the call returns ccol_unexpected_failure.
 
When several selectables are ready, the call does not always report the
one with the lowest index.  Each call checks the selectables in rotation
order, from a start index that moves on with every call the thread
makes, and a ready file descriptor competes in that check the same way
as a ready queue.  Every selectable that stays ready therefore wins its
share of the calls, and a ready selectable is never more than a few
calls behind any other, so a file descriptor that a worker watches for
a stop request is reported even when a queue next to it never runs
empty.  Which of several ready selectables a call reports is not
specified; a caller that needs one of them to take priority has to
check that one itself.
 
The call takes its locks in one fixed order, so it cannot deadlock with
a producer, a consumer or another cselect() on the same queues.

ready_index   Pointer to a size_t that receives the 0-based index of the
              selectable that became ready.  It is only valid when the
              call returns ccol_success.
n             Number of elements in the selectables array, from 1 to
              INT_MAX; any other value is refused with
              ccol_invalid_args (see RETURN VALUE).  It must also be no
              larger than SIZE_MAX / sizeof(internal waiter node).  No
              realistic caller gets near either limit.
selectables   Array of n cselectable values to watch.
timeout_us    For cselect_timed only.  Longest wait in microseconds.
              UINT64_MAX waits forever, as cselect does.  0 polls
              without blocking but still reports every selectable that
              is ready at the moment of the call.  Any other value waits
              at least that many microseconds before a timeout is
              reported.

ccol_success            A selectable is ready and *ready_index is set.
                        The caller must then make its own receive or
                        send call (see DESCRIPTION).
 
ccol_timed_out          For cselect_timed only.  timeout_us passed
                        before any selectable became ready.
                        *ready_index is left unchanged.
 
ccol_invalid_args       ready_index or selectables is NULL; n is 0; n
                        is larger than INT_MAX, because the index of a
                        matched selectable is narrowed through a plain
                        int; n is larger than SIZE_MAX /
                        sizeof(internal waiter node), because the
                        internal array of waiter nodes, one per
                        selectable, would overflow size_t (no n that a
                        caller can realistically build reaches either
                        limit); a queue selectable holds a NULL queue
                        pointer; an fd selectable holds a negative fd;
                        a type tag is unknown to the library; or a dir
                        is neither cselect_read nor
                        cselect_write.
ccol_not_enough_memory  An internal allocation failed: The array of
                        waiter nodes, one per selectable, or, with fd
                        selectables, the fd state or the wait's event
                        buffer.  No waiter is left behind and no message
                        is moved.
ccol_unexpected_failure poll(2), epoll_create1(2), eventfd(2) or
                        epoll_ctl(2) failed with an errno that the
                        library does not expect, or the internal mutex
                        or condition variable could not be initialised.
                        A failed system call on the fds needs at least
                        one fd selectable.  cselect_timed() also
                        returns this code in one more case, which needs
                        no fd selectable and a timeout_us other than
                        UINT64_MAX: The internal timed wait on a
                        condition variable fails with an error that is
                        not a timeout.  Treat it as a fatal problem in
                        the environment, such as a full fd table or
                        memory under pressure.  An fd selectable that
                        is not open, or that names a file epoll(7)
                        cannot watch, gives this code on every call as
                        well.  Regular files and directories are such
                        files: epoll_ctl(2) refuses them with EPERM,
                        while poll(2) and select(2) report them as
                        always ready, and the call refuses them the
                        same way whether or not it has to wait.  The
                        BSD and macOS builds refuse them too, even
                        though kqueue(2) can watch them, so that the
                        same program behaves the same on every system.

The waiter nodes, one per selectable, are allocated on the heap for the
length of the call and freed on every return path, error paths
included, so a large n never overflows the stack.
 
Any number of threads can call cselect() on the same queue at the
same time, because the waiter list is a linked list that grows as
needed and has no fixed capacity.
 
When several cselect() threads watch a queue that becomes ready, the
producer wakes only one of them, taking the waiters in turn.  The waiter
that wakes always passes the notification on to the next waiter in line
before it returns, whether or not its own receive or send succeeds, so
every interested waiter gets a chance to see the same readiness.  This
chain of single wakes avoids a thundering herd, and it also avoids the
liveness gap that would otherwise open when several messages arrive, or
several slots are freed, in quick succession.
 
Sends on a queue can be turned off with ccircq_disable_sending() or
cdynmq_disable_sending().  Read-direction waiters on that queue stay
registered and keep waiting for a message.  For the write direction, a
queue whose sends are off counts as ready, the same way a pipe whose
reader has gone is ready for POLLOUT: Every write-direction waiter is
woken at once, a call that starts while sends are off returns at once
(also on a full circular queue), and the ccircq_try_send() or
cdynmq_send() that the caller makes next returns
ccol_not_permitted.  A write select is ready, then, whenever a send
would not wait, because the queue has room or because its sends are
off.
 
Every file descriptor must stay open for the whole cselect() call;
closing an fd that a running cselect() watches is undefined
behaviour.
 
The same goes for a queue or a cchan handed to
ccircq_selectable(), cdynmq_selectable() or
cchan_selectable(): It must not be destroyed while a
cselect() or cselect_timed() call watches it.
ccircq_destroy(), cdynmq_destroy() and
cchan_destroy() assert when the queue has a linked waiter, from
a cselect() or cselect_timed() call in progress or from a live
ceventloop registration.  Without the assert, the waiter node
would stay linked and keep pointing at the mutex of a queue that the
destroy is about to free.
 
The same fd can appear in several selectables of one call, with the
directions mixed in any way, and even the same direction twice; watching
one connected socket for readability and writability at once is a
typical case.  Selectables that share an fd are combined into one
registration underneath.  When that registration fires, cselect()
finds the index to return by walking the selectables that share the fd
in the order the caller gave them, and picks the first one whose own
direction is really satisfied by what became ready.
 
Internally the call uses POSIX mutexes and condition variables plus
poll(2), and, when it has to wait and there is an fd selectable,
epoll(7) and eventfd(2) on Linux, or kqueue(2) and a wake descriptor on
the BSDs and macOS.  This page names the epoll(7) calls of the Linux
build; the other builds work the same way.

/* Fan-in from two circular queues and a cchan: */
size_t idx;
ccol_retval r = cselect(&idx, 3,
    (cselectable[]){
        ccircq_selectable(q0, cselect_read),
        ccircq_selectable(q1, cselect_read),
        cchan_selectable(ch, cselect_read),
    });
if (r == ccol_success) {
    printf("selectable %zu is ready\n", idx);
}
 
/* Equivalent using the convenience macro: */
r = cselect_va(&idx,
        ccircq_selectable(q0, cselect_read),
        ccircq_selectable(q1, cselect_read),
        cchan_selectable(ch, cselect_read));
 
/* Mixed read+write: wake when q0 has room OR dq has a message: */
r = cselect_va(&idx,
        ccircq_selectable(q0, cselect_write),
        cdynmq_selectable(dq,  cselect_read));
 
/* Fan-in from a queue and a pipe read end: */
int pfd[2];
if (pipe(pfd) != 0) { perror("pipe"); exit(1); }
r = cselect_va(&idx,
        ccircq_selectable(q0, cselect_read),
        cselectable_fd(pfd[0], cselect_read));
if (r == ccol_success) {
    cmessage msg;
    if (idx == 0) {
        /* queue is ready; claim it ourselves (zero-copy) */
        if (ccircq_try_recv(q0, &msg) == ccol_success) {
            printf("queue message size: %zu\n", msg.size);
            free(msg.data);
        }
    } else {
        /* fd is ready; read it ourselves */
        char buf[512];
        ssize_t n = read(pfd[0], buf, sizeof(buf));
        printf("read %zd bytes from fd\n", n);
    }
}
 
/* Timed wait with 500 ms deadline: */
r = cselect_timed_va(&idx, 500000,
        ccircq_selectable(q0, cselect_read));
if (r == ccol_timed_out) {
    printf("no source ready within 500 ms\n");
}
 
/* Watch one connected socket for either direction, whichever comes first: */
r = cselect_va(&idx,
        cselectable_fd(sock_fd, cselect_read),
        cselectable_fd(sock_fd, cselect_write));
if (r == ccol_success) {
    if (idx == 0) {
        char buf[512];
        ssize_t n = read(sock_fd, buf, sizeof(buf));
        printf("read %zd bytes\n", n);
    } else if (write(sock_fd, "hi", 2) < 0) {
        perror("write");  /* EAGAIN: a different writer used the room */
    }
}

cselect_timed(3), cselect_va(3), cselect_timed_va(3), cchan_selectable(3), ccircq_selectable(3), cdynmq_selectable(3), cselectable_fd(3), ccircq_try_recv(3), cdynmq_try_recv(3), cchan_try_recv(3), ccircq_destroy(3), cdynmq_destroy(3), cchan_destroy(3)