C Collections

cthreadcomm · Section 3

ceventloop_construct_scoped

ceventloop_construct_scoped - declare, initialise, and auto-destroy a ceventloop on scope exit

C Collections (libccollections, -lccollections)

#include <ccollections/cthreadcomm.h>
 
ceventloop_construct_scoped(name, max_events_per_wait, num_lock_stripes,
                            num_reactor_threads);

Declares a ceventloop variable called name, tags it with the
GCC and Clang cleanup attribute, and initialises it with
ceventloop_create(). If the create fails, the macro calls
ccol__fatal_err(). When the variable leaves its scope the loop is
destroyed automatically, with no explicit ceventloop_destroy()
call, and that destroy shuts every reactor thread down, joins each one
and frees every registration.

name                  Name of the variable for the ceventloop handle.
max_events_per_wait   Size of the polling thread's event batch buffer,
                      from 1 to INT_MAX. It must also be small enough
                      that max_events_per_wait times the size of one
                      kernel event record (struct epoll_event on Linux,
                      struct kevent on FreeBSD) fits in a size_t.
num_lock_stripes      Number of independent lock stripes for the
                      registry of fds and entries, at least 1. With 1
                      there is a single shared lock.
num_reactor_threads   Number of background reactor threads, at least 1.
                      With 1, a single thread both polls and dispatches
                      the callbacks in line.

A failure ends in ccol__fatal_err().
 
If you count on no callback being able to reach something that lives in
this loop's scope, such as a mutex or a buffer that a callback's arg
points at, that must stay true up to and including the join at the end
of the scope. Holding up to an explicit ceventloop_remove(3) call
before that point is not enough: A callback can outlive the return of
that call, as the notes of ceventloop_remove(3) explain, and the
implicit shutdown at the end of the scope behaves the same way.

{
    ceventloop_construct_scoped(loop, 32, 1, 1);
    ceventloop_reg reg = ceventloop_add(loop, cselectable_fd(fd, cselect_read),
                                        handlers, NULL, NULL);
    /* ... */
}  /* the library shuts loop down here, joins every reactor thread,
      and destroys the loop */

ceventloop_construct(3), ceventloop_declare_scoped(3), ceventloop_create(3), ceventloop_remove(3)