Line data Source code
1 : /*
2 : MIT License
3 :
4 : Copyright (c) 2026 - A bunch of nerds
5 :
6 : Permission is hereby granted, free of charge, to any person obtaining a copy
7 : of this software and associated documentation files (the "Software"), to deal
8 : in the Software without restriction, including without limitation the rights
9 : to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 : copies of the Software, and to permit persons to whom the Software is
11 : furnished to do so, subject to the following conditions:
12 :
13 : The above copyright notice and this permission notice shall be included in all
14 : copies or substantial portions of the Software.
15 :
16 : THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 : IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 : FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 : AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 : LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 : OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 : SOFTWARE.
23 : */
24 :
25 : #pragma once
26 :
27 : #include "common.h"
28 :
29 : // Everything from here to the matching pop is the public ABI and the shared
30 : // library exports it. The library builds with -fvisibility=hidden, so anything
31 : // outside these blocks stays internal.
32 : //
33 : // Thread-safe message passing between threads. ccircq is a fixed-size queue
34 : // whose send blocks while it's full (that's its backpressure), cdynmq is a
35 : // linked-list queue whose send never blocks, and cchan is two-way communication
36 : // between an owner thread and a worker thread. Nothing is copied: A send hands
37 : // over the ownership of a pointer. cselect() waits on several queues and fds,
38 : // and ceventloop is a reactor that dispatches their readiness to callbacks.
39 : #pragma GCC visibility push(default)
40 :
41 : // A thread-safe circular queue of cmessage values with a fixed capacity. A
42 : // send waits (or fails, for the try and timed forms) while it is full. Create
43 : // it with ccircq_create() and destroy it with ccircq_destroy().
44 : typedef struct ccircq ccircq;
45 :
46 : // A thread-safe queue of cmessage values with no fixed capacity, kept in a
47 : // linked list, so a send never waits for room. Create it with cdynmq_create()
48 : // and destroy it with cdynmq_destroy().
49 : typedef struct cdynmq cdynmq;
50 :
51 : // A two-way channel between one owner thread and its worker threads, made of
52 : // two circular queues. Each call picks its direction from the calling thread.
53 : // Create it with cchan_create() and destroy it with cchan_destroy().
54 : typedef struct cchan cchan;
55 :
56 : // A message. A successful send sets the sender's data to NULL and the receiver
57 : // owns (and frees) it. data NULL with size 0 is a valid sentinel message; data
58 : // NULL with a size, or a pointer with size 0, is refused.
59 : typedef struct cmessage {
60 : void *data;
61 : size_t size;
62 : } cmessage;
63 :
64 : // Creates a circular queue that holds at most max_size messages (at least 1,
65 : // at most ccol_max_elem_count and SIZE_MAX / sizeof(cmessage), since the queue
66 : // is one array). mmgmt_procs is your allocator table, or NULL for malloc and
67 : // free; a table must set all four functions, and the queue keeps its own copy.
68 : // Gives the queue, or NULL with an error string in *err_str when err_str isn't
69 : // NULL. Destroy it with ccircq_destroy().
70 : ccircq *ccircq_create_mp(size_t max_size, ccol_memmgmt_procs *mmgmt_procs,
71 : char **err_str);
72 :
73 : // Creates a circular queue that holds at most max_size messages (at least 1,
74 : // at most ccol_max_elem_count and SIZE_MAX / sizeof(cmessage)), allocated with
75 : // malloc and free. Evaluates to the queue, or to NULL with an error string in
76 : // *err_str when err_str isn't NULL. Destroy it with ccircq_destroy().
77 : #define ccircq_create(max_size, err_str) \
78 : ccircq_create_mp((max_size), NULL, (err_str))
79 :
80 : // Internal: Destroys cq; ccircq_destroy() calls it and then clears the pointer.
81 : // Use the macro instead.
82 : void ccircq__destroy(ccircq *cq);
83 :
84 : // Destroys the queue and sets cq to NULL, so a dangling pointer can't be used
85 : // again. cq is evaluated once and must be a modifiable lvalue; NULL is fine.
86 : // Messages left in the queue aren't freed, and it asserts when the queue isn't
87 : // empty or a cselect() call or a ceventloop registration still watches it,
88 : // because the watcher points at the queue's mutex. So drain it and call
89 : // ceventloop_remove() first. The destroy waits for any callback of this queue
90 : // that was already running when the remove returned, and counts the messages
91 : // only after that; a write callback can still send in that time, so with a
92 : // write registration wait for its on_removed before you drain and destroy. A
93 : // callback of another registration may run this whole sequence. Destroying from
94 : // a callback that dispatches this same queue is a fatal error, and holding a
95 : // lock that one of its callbacks takes deadlocks.
96 : #define ccircq_destroy(cq) \
97 : ccircq__destroy_impl(cq, ccol__uniq(ccol__cq_destroy_slot, __COUNTER__))
98 :
99 : // Internal: The body of ccircq_destroy(), which calls ccircq__destroy(*slot)
100 : // and clears the pointer. slot comes from ccol__uniq(), so destroy macros can
101 : // nest without -Wshadow warnings, and cq is evaluated once.
102 : #define ccircq__destroy_impl(cq, slot) \
103 : do { \
104 : __typeof__(cq) *slot = &(cq); \
105 : ccircq__destroy(*slot); \
106 : *slot = NULL; \
107 : } while (0)
108 :
109 : // Sends msg, the send for a producer that should wait while the queue is full
110 : // (that's the backpressure). It waits with no time limit for room or for sends
111 : // to be turned off. On success msg->data becomes NULL and the queue owns it; on
112 : // failure you keep it. It gives ccol_success, ccol_invalid_args (NULL cq or
113 : // msg, or a data/size pair that doesn't match), or ccol_not_permitted when
114 : // sends are off.
115 : ccol_retval ccircq_send(ccircq *cq, cmessage *msg);
116 :
117 : // Sends msg without waiting, for a producer that must never block. On success
118 : // msg->data becomes NULL and the queue owns it; on failure you keep it. It
119 : // gives ccol_success, ccol_container_full when the queue is full,
120 : // ccol_invalid_args (NULL cq or msg, or a data/size pair that doesn't match:
121 : // NULL data needs size 0 and other data a size above 0), or ccol_not_permitted
122 : // when sends are off.
123 : ccol_retval ccircq_try_send(ccircq *cq, cmessage *msg);
124 :
125 : // Sends msg, waiting at most timeout_us microseconds for room, for a producer
126 : // that may wait but not for ever. The wait is on CLOCK_MONOTONIC, so a wall
127 : // clock step doesn't change it. 0 doesn't wait and gives ccol_container_full
128 : // for a full queue; UINT64_MAX (or any value too large for a deadline) waits
129 : // with no end. On success msg->data becomes NULL and the queue owns it; on
130 : // failure you keep it. It gives ccol_success, ccol_timed_out, ccol_invalid_args
131 : // (NULL cq or msg, or a data/size pair that doesn't match), ccol_not_permitted
132 : // when sends are off, or ccol_unexpected_failure with errno set when the wait
133 : // itself fails.
134 : ccol_retval ccircq_timed_send(ccircq *cq, cmessage *msg, uint64_t timeout_us);
135 :
136 : // Receives a message into target_buf, for a consumer with nothing else to do:
137 : // it waits with no time limit, and you then own target_buf->data and must free
138 : // it. It gives ccol_success or ccol_invalid_args (NULL cq or target_buf).
139 : // Turning sends off doesn't wake it.
140 : ccol_retval ccircq_recv(ccircq *cq, cmessage *target_buf);
141 :
142 : // Takes a message into target_buf if one is queued, without waiting, for a
143 : // consumer that must not block (after cselect(), or in a loop callback). On
144 : // success you own target_buf->data and must free it. It gives ccol_success,
145 : // ccol_container_empty when the queue is empty, or ccol_invalid_args (NULL cq
146 : // or target_buf).
147 : ccol_retval ccircq_try_recv(ccircq *cq, cmessage *target_buf);
148 :
149 : // Receives a message into target_buf, waiting at most timeout_us microseconds
150 : // on CLOCK_MONOTONIC, for a consumer that also has other work. 0 doesn't wait
151 : // and gives ccol_container_empty for an empty queue; UINT64_MAX (or any value
152 : // too large for a deadline) waits with no end. On success you own
153 : // target_buf->data and must free it. It gives ccol_success, ccol_timed_out,
154 : // ccol_invalid_args (NULL cq or target_buf), or ccol_unexpected_failure with
155 : // errno set when the wait itself fails.
156 : ccol_retval ccircq_timed_recv(ccircq *cq, cmessage *target_buf,
157 : uint64_t timeout_us);
158 :
159 : // Turns sends off, so an owner can stop new work while consumers drain what is
160 : // queued. Every blocked sender wakes and gives ccol_not_permitted; receives go
161 : // on. A queue with sends off counts as ready for the write direction of
162 : // cselect() and of a loop registration, the way POLLOUT is set on a pipe whose
163 : // reader is gone, so the waiter's send fails at once. Gives ccol_success or
164 : // ccol_invalid_args.
165 : ccol_retval ccircq_disable_sending(ccircq *cq);
166 :
167 : // Turns sends back on after ccircq_disable_sending() and wakes every blocked
168 : // sender. A full queue is then not ready for writing until it has room. Gives
169 : // ccol_success or ccol_invalid_args.
170 : ccol_retval ccircq_enable_sending(ccircq *cq);
171 :
172 : // Gives a snapshot of the number of queued messages, or (size_t)-1 for a NULL
173 : // queue.
174 : size_t ccircq_msg_count(ccircq *cq);
175 :
176 : // Creates a dynamic queue (a doubly-linked list), for a producer that must
177 : // never block: Its send fails only for lack of memory, at ccol_max_elem_count
178 : // messages, or while sends are off. mmgmt_procs is your allocator table, used
179 : // for the queue and every node a send adds, or NULL for malloc and free; a
180 : // table must set all four functions, and the queue keeps its own copy. Gives
181 : // the queue, or NULL with an error string in *err_str when err_str isn't NULL.
182 : // Destroy it with cdynmq_destroy().
183 : cdynmq *cdynmq_create_mp(ccol_memmgmt_procs *mmgmt_procs, char **err_str);
184 :
185 : // Creates a dynamic queue (a doubly-linked list) allocated with malloc and
186 : // free, for a producer that must never block. Evaluates to the queue, or to
187 : // NULL with an error string in *err_str when err_str isn't NULL. Destroy it
188 : // with cdynmq_destroy().
189 : #define cdynmq_create(err_str) cdynmq_create_mp(NULL, (err_str))
190 :
191 : // Internal: Destroys dq; cdynmq_destroy() calls it and then clears the pointer.
192 : // Use the macro instead.
193 : void cdynmq__destroy(cdynmq *dq);
194 :
195 : // Destroys the queue and its nodes and sets dq to NULL, so a dangling pointer
196 : // can't be used again. dq is evaluated once and must be a modifiable lvalue;
197 : // NULL is fine. Messages left in the queue aren't freed, and it asserts when
198 : // the queue isn't empty or a cselect() call or a ceventloop registration still
199 : // watches it, so drain it and call ceventloop_remove() first. It waits for any
200 : // callback of this queue that was already running when the remove returned,
201 : // and counts the messages only after that; with a write registration, wait for
202 : // its on_removed before you drain and destroy. Destroying from a callback that
203 : // dispatches this same queue is a fatal error, and holding a lock that one of
204 : // its callbacks takes deadlocks.
205 : #define cdynmq_destroy(dq) \
206 : cdynmq__destroy_impl(dq, ccol__uniq(ccol__dq_destroy_slot, __COUNTER__))
207 :
208 : // Internal: The body of cdynmq_destroy(), like ccircq__destroy_impl().
209 : #define cdynmq__destroy_impl(dq, slot) \
210 : do { \
211 : __typeof__(dq) *slot = &(dq); \
212 : cdynmq__destroy(*slot); \
213 : *slot = NULL; \
214 : } while (0)
215 :
216 : // Appends msg without blocking, the only send an unbounded queue needs. On
217 : // success msg->data becomes NULL and the queue owns it; on failure you keep it.
218 : // It gives ccol_success, ccol_invalid_args (NULL dq or msg, or a data/size pair
219 : // that doesn't match: NULL data needs size 0 and other data a size above 0),
220 : // ccol_not_permitted when sends are off, ccol_container_full at
221 : // ccol_max_elem_count messages, or ccol_not_enough_memory.
222 : ccol_retval cdynmq_send(cdynmq *dq, cmessage *msg);
223 :
224 : // Receives the message at the head into target_buf, for a consumer with
225 : // nothing else to do: It waits with no time limit, and you then own
226 : // target_buf->data and must free it. It gives ccol_success or
227 : // ccol_invalid_args (NULL dq or target_buf). Turning sends off doesn't wake it.
228 : ccol_retval cdynmq_recv(cdynmq *dq, cmessage *target_buf);
229 :
230 : // Takes the message at the head into target_buf if there is one, without
231 : // waiting, for a consumer that must not block (after cselect(), or in a loop
232 : // callback). On success you own target_buf->data and must free it. It gives
233 : // ccol_success, ccol_container_empty when the queue is empty (target_buf is
234 : // left alone), or ccol_invalid_args (NULL dq or target_buf).
235 : ccol_retval cdynmq_try_recv(cdynmq *dq, cmessage *target_buf);
236 :
237 : // Receives the message at the head into target_buf, waiting at most
238 : // timeout_us microseconds on CLOCK_MONOTONIC, for a consumer that also has
239 : // other work. 0 doesn't wait and gives ccol_container_empty for an empty
240 : // queue; UINT64_MAX (or any value too large for a deadline) waits with no end.
241 : // On success you own target_buf->data and must free it. It gives
242 : // ccol_success, ccol_timed_out, ccol_invalid_args (NULL dq or target_buf), or
243 : // ccol_unexpected_failure with errno set when the wait itself fails.
244 : ccol_retval cdynmq_timed_recv(cdynmq *dq, cmessage *target_buf,
245 : uint64_t timeout_us);
246 :
247 : // Turns sends off, so an owner can stop new work while consumers drain what is
248 : // queued; every later send gives ccol_not_permitted and receives go on. A
249 : // queue with sends off counts as ready for the write direction of cselect()
250 : // and of a loop registration, the way POLLOUT is set on a pipe whose reader is
251 : // gone, so the waiter's send fails at once. Gives ccol_success or
252 : // ccol_invalid_args.
253 : ccol_retval cdynmq_disable_sending(cdynmq *dq);
254 :
255 : // Turns sends back on after cdynmq_disable_sending(). Gives ccol_success or
256 : // ccol_invalid_args.
257 : ccol_retval cdynmq_enable_sending(cdynmq *dq);
258 :
259 : // Gives a snapshot of the number of queued messages, or (size_t)-1 for a NULL
260 : // queue.
261 : size_t cdynmq_msg_count(cdynmq *dq);
262 :
263 : // Creates a cchan, for two-way traffic between an owner thread and its
264 : // workers: Two circular queues of at most max_size messages each,
265 : // cchan_owner_to_workers and cchan_workers_to_owner. The calling thread becomes
266 : // the owner and every other thread is a worker; each call picks its direction
267 : // from the caller's thread ID, so no call names one. The owner must stay alive
268 : // while the channel is in use, since the OS can give its ID to a new thread,
269 : // which would then be routed as the owner. max_size is at least 1 and at most
270 : // ccol_max_elem_count and SIZE_MAX / sizeof(cmessage). mmgmt_procs is your
271 : // allocator table, or NULL for malloc and free; a table must set all four
272 : // functions, and the channel keeps its own copy. Gives the channel, or NULL
273 : // with an error string in *err_str when err_str isn't NULL. Destroy it with
274 : // cchan_destroy().
275 : cchan *cchan_create_mp(size_t max_size, ccol_memmgmt_procs *mmgmt_procs,
276 : char **err_str);
277 :
278 : // Creates a cchan allocated with malloc and free: Two circular queues of at
279 : // most max_size messages each (at least 1). The calling thread becomes the
280 : // owner, every other thread is a worker, and each later call picks its
281 : // direction from the caller's thread, so the owner must stay alive while the
282 : // channel is in use. Evaluates to the channel, or to NULL with an error string
283 : // in *err_str when err_str isn't NULL. Destroy it with cchan_destroy().
284 : #define cchan_create(max_size, err_str) \
285 : cchan_create_mp((max_size), NULL, (err_str))
286 :
287 : // Internal: Destroys ch; cchan_destroy() calls it and then clears the pointer.
288 : // Use the macro instead.
289 : void cchan__destroy(cchan *ch);
290 :
291 : // Destroys the channel and both its queues and sets ch to NULL, so a dangling
292 : // pointer can't be used again. ch is evaluated once and must be a modifiable
293 : // lvalue; NULL is fine. Messages left in either queue aren't freed, and it
294 : // asserts when a queue isn't empty or a cselect() call or a ceventloop
295 : // registration still watches it, so drain both directions and remove every
296 : // registration first. It waits for any callback of the channel that was
297 : // already running when the remove returned. Destroying from a callback that
298 : // dispatches one of its directions is a fatal error.
299 : #define cchan_destroy(ch) \
300 : cchan__destroy_impl(ch, ccol__uniq(cchan__destroy_slot, __COUNTER__))
301 :
302 : // Internal: The body of cchan_destroy(), like ccircq__destroy_impl().
303 : #define cchan__destroy_impl(ch, slot) \
304 : do { \
305 : __typeof__(ch) *slot = &(ch); \
306 : cchan__destroy(*slot); \
307 : *slot = NULL; \
308 : } while (0)
309 :
310 : // Sends msg on the calling thread's outgoing queue of ch: The owner thread
311 : // sends to cchan_owner_to_workers and any other thread to
312 : // cchan_workers_to_owner. It waits with no time limit while that queue is
313 : // full, and wakes when sends on it are turned off. On success msg->data becomes
314 : // NULL and the channel owns it; on failure you keep it. It gives ccol_success,
315 : // ccol_invalid_args (NULL ch or msg, or a data/size pair that doesn't match:
316 : // NULL data needs size 0 and other data a size above 0), or ccol_not_permitted
317 : // when sends on that direction are off.
318 : ccol_retval cchan_send(cchan *ch, cmessage *msg);
319 :
320 : // Sends msg on the calling thread's outgoing queue of ch without waiting: The
321 : // owner thread sends to cchan_owner_to_workers and any other thread to
322 : // cchan_workers_to_owner. On success msg->data becomes NULL and the channel
323 : // owns it; on failure you keep it. It gives ccol_success, ccol_container_full
324 : // when that queue is full, ccol_invalid_args (NULL ch or msg, or a data/size
325 : // pair that doesn't match), or ccol_not_permitted when sends on that direction
326 : // are off.
327 : ccol_retval cchan_try_send(cchan *ch, cmessage *msg);
328 :
329 : // Sends msg on the calling thread's outgoing queue of ch (the owner thread to
330 : // cchan_owner_to_workers, any other thread to cchan_workers_to_owner), waiting
331 : // at most timeout_us microseconds on CLOCK_MONOTONIC for room. 0 doesn't wait
332 : // and gives ccol_container_full for a full queue; UINT64_MAX (or any value too
333 : // large for a deadline) waits with no end. On success msg->data becomes NULL
334 : // and the channel owns it; on failure you keep it. It gives ccol_success,
335 : // ccol_timed_out, ccol_invalid_args, ccol_not_permitted when sends on that
336 : // direction are off, or ccol_unexpected_failure with errno set when the wait
337 : // itself fails.
338 : ccol_retval cchan_timed_send(cchan *ch, cmessage *msg, uint64_t timeout_us);
339 :
340 : // Receives into target_buf from the calling thread's incoming queue of ch: The
341 : // owner thread receives from cchan_workers_to_owner and any other thread from
342 : // cchan_owner_to_workers. It waits with no time limit for a message, and you
343 : // then own target_buf->data and must free it. It gives ccol_success or
344 : // ccol_invalid_args (NULL ch or target_buf).
345 : ccol_retval cchan_recv(cchan *ch, cmessage *target_buf);
346 :
347 : // Takes a message into target_buf from the calling thread's incoming queue of
348 : // ch (the owner thread from cchan_workers_to_owner, any other thread from
349 : // cchan_owner_to_workers) without waiting. On success you own
350 : // target_buf->data and must free it. It gives ccol_success,
351 : // ccol_container_empty when that queue is empty, or ccol_invalid_args (NULL ch
352 : // or target_buf).
353 : ccol_retval cchan_try_recv(cchan *ch, cmessage *target_buf);
354 :
355 : // Receives into target_buf from the calling thread's incoming queue of ch (the
356 : // owner thread from cchan_workers_to_owner, any other thread from
357 : // cchan_owner_to_workers), waiting at most timeout_us microseconds on
358 : // CLOCK_MONOTONIC. 0 doesn't wait and gives ccol_container_empty for an empty
359 : // queue; UINT64_MAX (or any value too large for a deadline) waits with no end.
360 : // On success you own target_buf->data and must free it. It gives
361 : // ccol_success, ccol_timed_out, ccol_invalid_args (NULL ch or target_buf), or
362 : // ccol_unexpected_failure with errno set when the wait itself fails.
363 : ccol_retval cchan_timed_recv(cchan *ch, cmessage *target_buf,
364 : uint64_t timeout_us);
365 :
366 : // The two directions of a cchan, named for the control calls that take one.
367 : typedef enum cchan_direction {
368 : cchan_owner_to_workers = 0,
369 : cchan_workers_to_owner
370 : } cchan_direction;
371 :
372 : // Turns sends on direction d of ch off, so one side can stop new work while
373 : // the other drains what is queued; the other direction isn't touched. Every
374 : // sender blocked on d wakes and gives ccol_not_permitted, and so does every
375 : // later send on d; receives go on. A direction with sends off counts as ready
376 : // for writing in cselect() and in a loop registration, so the waiter's send
377 : // fails at once. Gives ccol_success, or ccol_invalid_args for a NULL ch or a
378 : // bad d.
379 : ccol_retval cchan_disable_sending(cchan *ch, cchan_direction d);
380 :
381 : // Turns sends on direction d of ch back on after cchan_disable_sending() and
382 : // wakes every sender blocked on d; the other direction isn't touched. Gives
383 : // ccol_success, or ccol_invalid_args for a NULL ch or a bad d.
384 : ccol_retval cchan_enable_sending(cchan *ch, cchan_direction d);
385 :
386 : // Gives a snapshot of the message count of direction d, or (size_t)-1 for a
387 : // NULL ch or a bad d.
388 : size_t cchan_msg_count(cchan *ch, cchan_direction d);
389 :
390 : // The kind of object a cselectable holds.
391 : typedef enum {
392 : cselectable_type_ccircq,
393 : cselectable_type_cdynmq,
394 : cselectable_type_fd,
395 : } cselectable_type;
396 :
397 : // The direction a selectable waits on. cselect_read waits for a message to
398 : // receive. cselect_write waits until a send doesn't have to wait: The queue has
399 : // room (a ccircq below max_size, a cdynmq below ccol_max_elem_count) or its
400 : // sends are off, in which case the send gives ccol_not_permitted at once.
401 : // cselect() neither consumes nor reserves anything, so after it wakes you make
402 : // the non-blocking call yourself (ccircq_try_recv(), cdynmq_try_recv(),
403 : // ccircq_try_send() or cdynmq_send()) and check its result; another thread can
404 : // win the race in between, as with select(2).
405 : typedef enum {
406 : cselect_read,
407 : cselect_write,
408 : } cselect_dir;
409 :
410 : // One queue or fd that cselect() and ceventloop watch. Build it with
411 : // ccircq_selectable(), cdynmq_selectable(), cselectable_fd() or
412 : // cchan_selectable(). fd must be at least 0.
413 : typedef struct {
414 : cselectable_type type;
415 : cselect_dir dir;
416 : union {
417 : ccircq *cq;
418 : cdynmq *dq;
419 : int fd;
420 : };
421 : } cselectable;
422 :
423 : // Evaluates to a cselectable that wraps the circular queue q_ for a wait in
424 : // direction sel_dir (cselect_read: A message to receive; cselect_write: Room to
425 : // send, or sends turned off), to pass to cselect() or ceventloop_add(). After
426 : // the wait reports it ready, call ccircq_try_recv() or ccircq_try_send()
427 : // yourself and check the result.
428 : #define ccircq_selectable(q_, sel_dir) \
429 : ((cselectable){.type = cselectable_type_ccircq, .dir = (sel_dir), .cq = (q_)})
430 :
431 : // Evaluates to a cselectable that wraps the dynamic queue q_ for a wait in
432 : // direction sel_dir (cselect_read: A message to receive; cselect_write: Room to
433 : // send, or sends turned off), to pass to cselect() or ceventloop_add(). After
434 : // the wait reports it ready, call cdynmq_try_recv() or cdynmq_send() yourself
435 : // and check the result.
436 : #define cdynmq_selectable(q_, sel_dir) \
437 : ((cselectable){.type = cselectable_type_cdynmq, .dir = (sel_dir), .dq = (q_)})
438 :
439 : // Evaluates to a cselectable that wraps the file descriptor fd_ (at least 0)
440 : // for a wait in direction sel_dir, so cselect() and the loop can watch fds
441 : // beside queues. cselect_read watches EPOLLIN and cselect_write EPOLLOUT; both
442 : // also get EPOLLERR and EPOLLHUP, and a read selectable EPOLLRDHUP. The library
443 : // only reports readiness; you do the read or write on the fd.
444 : #define cselectable_fd(fd_, sel_dir) \
445 : ((cselectable){.type = cselectable_type_fd, .dir = (sel_dir), .fd = (fd_)})
446 :
447 : // Gives a selectable for the queue of ch that the calling thread reads from
448 : // (cselect_read, like cchan_recv()) or writes to (cselect_write, like
449 : // cchan_send()). The queue is resolved once, here, and the selectable keeps
450 : // watching it whichever thread waits on it later. In an event loop callback,
451 : // receive or send with ccircq_try_recv() or ccircq_try_send() on sel.cq, never
452 : // a cchan_ call: The loop's threads count as workers, so a cchan_ call there
453 : // can pick the other queue. A NULL ch gives a selectable that cselect()
454 : // refuses.
455 : cselectable cchan_selectable(cchan *ch, cselect_dir dir);
456 :
457 : // Waits until one of the n selectables is ready for its own direction and sets
458 : // *ready_index; the caller then makes its own non-blocking receive, send, read
459 : // or write and checks its result. An array may mix directions, queues and fds.
460 : // Ready selectables share the calls fairly: Each call scans in rotation order
461 : // from a start that moves per call, so a selectable that stays ready wins its
462 : // share. Which one a call reports isn't specified. Each producer action wakes
463 : // exactly one waiter, and a waiter that leaves without acting hands the wake
464 : // on. n goes from 1 to INT_MAX. It gives ccol_success, ccol_invalid_args (a
465 : // NULL or zero argument, a NULL queue, a negative fd, an unknown type or dir),
466 : // ccol_not_enough_memory (nothing linked stays linked, no message moves), or
467 : // ccol_unexpected_failure when a system call or a primitive init fails. Without
468 : // fds it uses only condition variables. With fds it first asks poll(2) without
469 : // waiting and uses epoll (kqueue on the BSDs and macOS) only when it must wait,
470 : // so every fd must be something epoll can watch: A regular file or a directory
471 : // gives ccol_unexpected_failure. The wait has no time limit. See also
472 : // cselect_timed().
473 : ccol_retval cselect(size_t *ready_index, size_t n, cselectable *selectables);
474 :
475 : // Waits at most timeout_us microseconds on CLOCK_MONOTONIC until one of the n
476 : // selectables (1 to INT_MAX; queues and fds in any mix of directions) is ready
477 : // for its own direction, and sets *ready_index. It neither receives nor sends:
478 : // you then make your own non-blocking receive, send, read or write and check
479 : // its result, since another thread can win the race. Ready selectables share
480 : // the calls fairly, and which one a call reports isn't specified. UINT64_MAX
481 : // waits with no limit, and 0 polls once, still reporting what is ready at the
482 : // moment of the call. Any other value waits at least that long, even past the
483 : // INT_MAX milliseconds of one kernel wait, and looks once more at every
484 : // selectable before it reports a timeout. It gives ccol_success,
485 : // ccol_timed_out (*ready_index is left alone), ccol_invalid_args (a NULL or
486 : // zero argument, a NULL queue, a negative fd, an unknown type or dir),
487 : // ccol_not_enough_memory (nothing linked stays linked, no message moves), or
488 : // ccol_unexpected_failure when a system call, a primitive init or the timed
489 : // wait fails; an fd that epoll can't watch, such as a regular file or a
490 : // directory, gives ccol_unexpected_failure.
491 : ccol_retval cselect_timed(size_t *ready_index, size_t n,
492 : cselectable *selectables, uint64_t timeout_us);
493 :
494 : // Waits with no time limit until one of the selectables listed after
495 : // ready_index is ready, for a fixed set written at the call site, for example
496 : // cselect_va(&idx, ccircq_selectable(q0, cselect_read),
497 : // cchan_selectable(ch, cselect_read)). It sets *ready_index to the position of
498 : // the ready one in the list and doesn't receive or send; you make that call
499 : // yourself and check its result. It evaluates to a ccol_retval: ccol_success,
500 : // ccol_invalid_args (a NULL ready_index, a NULL queue, a negative fd, an
501 : // unknown type or dir), ccol_not_enough_memory, or ccol_unexpected_failure
502 : // when a system call fails or an fd can't be watched by epoll (a regular file
503 : // or a directory). Each argument is evaluated once. It uses a statement
504 : // expression, so it needs GNU C.
505 : #define cselect_va(ready_index, ...) \
506 : __extension__({ \
507 : cselectable cselect__arr[] = {__VA_ARGS__}; \
508 : cselect((ready_index), sizeof(cselect__arr) / sizeof(cselect__arr[0]), \
509 : cselect__arr); \
510 : })
511 :
512 : // Waits at most timeout_us microseconds until one of the selectables listed
513 : // after timeout_us is ready, for a fixed set written at the call site, and
514 : // sets *ready_index to its position in the list. UINT64_MAX waits with no
515 : // limit and 0 polls once. It doesn't receive or send; you make that call
516 : // yourself and check its result. It evaluates to a ccol_retval: ccol_success,
517 : // ccol_timed_out when none is ready in time, ccol_invalid_args (a NULL
518 : // ready_index, a NULL queue, a negative fd, an unknown type or dir),
519 : // ccol_not_enough_memory, or ccol_unexpected_failure when a system call fails
520 : // or an fd can't be watched by epoll. Each argument is evaluated once. It uses
521 : // a statement expression, so it needs GNU C.
522 : #define cselect_timed_va(ready_index, timeout_us, ...) \
523 : __extension__({ \
524 : cselectable cselect__arr[] = {__VA_ARGS__}; \
525 : cselect_timed((ready_index), \
526 : sizeof(cselect__arr) / sizeof(cselect__arr[0]), \
527 : cselect__arr, (timeout_us)); \
528 : })
529 :
530 : // A long-lived reactor. Exactly one poller thread waits on epoll (kqueue on the
531 : // BSDs and macOS), on purpose: Many threads waiting on one epoll set all wake
532 : // for one event, and EPOLLEXCLUSIVE doesn't help with that. With
533 : // num_reactor_threads > 1 the callbacks run on a separate pool of dispatch
534 : // workers, and two things still hold. The callbacks of one registration never
535 : // run at the same time, and neither do the read and the write registration of
536 : // one fd, so state shared across both directions of an fd needs no lock. And a
537 : // removed registration's fd number can be reused at once: A dispatch checks
538 : // liveness right before it calls a callback, so a stale dispatch does nothing,
539 : // and the loop never collects a second dispatch for an entry that has one in
540 : // flight, which makes ceventloop_modify from a callback safe. In every
541 : // configuration the calls that take a ceventloop_reg resolve it through a
542 : // generation-tagged slot table first, so threads may race them on one handle,
543 : // or use it long after a remove, and the loser just gets ccol_invalid_args (or
544 : // generation 0). Like cselect(), the loop only reports readiness; your callback
545 : // does the receive or the send.
546 : typedef struct ceventloop__s ceventloop__s;
547 :
548 : // The loop handle: A slot index and a generation packed into a value. It isn't
549 : // a pointer, so never cast it. Compare it with CEVENTLOOP_NULL (0). Every use
550 : // is resolved through the library's slot table, so a stale handle is detected
551 : // and never dereferenced.
552 : typedef uint64_t ceventloop;
553 :
554 : // "No loop", the failure value of a create.
555 : #define CEVENTLOOP_NULL ((ceventloop)0)
556 :
557 : // The handle of one registration, the same design as ceventloop scoped to one
558 : // loop. Its slot is freed by ceventloop_remove, after which every call with it
559 : // gives ccol_invalid_args (generation 0).
560 : typedef uint64_t ceventloop_reg;
561 :
562 : // "No registration", the failure value of ceventloop_add.
563 : #define CEVENTLOOP_REG_NULL ((ceventloop_reg)0)
564 :
565 : // Runs when a registration becomes readable. The callback does its own read()
566 : // or recv() on sel->fd, or its own ccircq_try_recv() or cdynmq_try_recv() on
567 : // sel->cq or sel->dq (for a channel queue that's ccircq_try_recv(), never
568 : // cchan_try_recv()), and copes with finding nothing, since another consumer may
569 : // have won. Several sends can collapse into one notification; as long as a
570 : // callback moved a message and the queue is still ready, the loop dispatches
571 : // again, so receiving one message per call still drains a burst. reg is the
572 : // registration's own handle, valid even in a dispatch that runs before
573 : // ceventloop_add has returned. sel->dir is the current direction (modify can
574 : // change it), and arg is what you passed to ceventloop_add. The same parameters
575 : // apply to the writable and error callbacks.
576 : typedef void (*ceventloop_readable_fn)(ceventloop loop, ceventloop_reg reg,
577 : cselectable *sel, void *arg);
578 :
579 : // Runs when a registration becomes writable. The callback does its own write()
580 : // or send(), or for a queue its own ccircq_try_send() or cdynmq_send() (the
581 : // queue may have room, or its sends may be off and the send gives
582 : // ccol_not_permitted), and copes with a full queue, since another producer may
583 : // have won. reg is the registration's own handle, sel->dir its current
584 : // direction, and arg what you passed to ceventloop_add.
585 : typedef void (*ceventloop_writable_fn)(ceventloop loop, ceventloop_reg reg,
586 : cselectable *sel, void *arg);
587 :
588 : // Runs on a condition that the registration's direction has no other handler
589 : // for. EPOLLERR and EPOLLHUP come here when the direction isn't also ready, and
590 : // so does EPOLLRDHUP (a peer's close) for a read registration with no
591 : // on_readable. When the direction is ready too, its own handler wins, so bytes
592 : // that arrived before the error are still delivered. With on_error NULL, an
593 : // error or hang-up goes to the direction's handler, as libevent and libuv do,
594 : // and that handler's read or write reports it; a read or write also clears a
595 : // socket error, so a transient one costs one failed receive. With handlers for
596 : // both directions one event reaches on_readable and then on_writable. Queue
597 : // selectables never get here. A registration may carry only on_error, to hear
598 : // that an fd died. Conditions are level-triggered: The loop keeps reporting one
599 : // until it clears or you remove or pause the registration, so a handler that
600 : // reads an end of file must remove the registration (before closing the fd). On
601 : // the BSDs and macOS an error-only registration may hear each condition only
602 : // once. reg is the registration's own handle, sel its selectable, and arg what
603 : // you passed to ceventloop_add.
604 : typedef void (*ceventloop_error_fn)(ceventloop loop, ceventloop_reg reg,
605 : cselectable *sel, void *arg);
606 :
607 : // Runs exactly once for every registration that was really added, when the
608 : // loop can prove that you may free arg: After a ceventloop_remove (from any
609 : // thread, a callback of the same registration included) once every dispatch in
610 : // flight or already collected has finished, or during a destroy of the loop. It
611 : // never runs inside ceventloop_remove, but on the reactor thread a bounded time
612 : // later; ceventloop_destroy runs every due one before it returns. The thread
613 : // holds no lock of this module, so on_removed may take any lock of yours.
614 : // Destroying the owning loop from it is fatal. With on_removed NULL you get
615 : // only the weaker promise of ceventloop_remove().
616 : typedef void (*ceventloop_removed_fn)(void *arg);
617 :
618 : // The callbacks of one registration, each of which may be NULL. For an fd the
619 : // loop doesn't arm a direction without a handler of its own. An fd event that
620 : // no handler can take is dropped and the loop stops watching that registration
621 : // (a hang-up would otherwise repeat on every wait) until ceventloop_resume() or
622 : // a successful ceventloop_modify(). on_removed may be NULL when arg needs no
623 : // notice before it's freed.
624 : typedef struct ceventloop_handlers {
625 : ceventloop_readable_fn on_readable;
626 : ceventloop_writable_fn on_writable;
627 : ceventloop_error_fn on_error;
628 : ceventloop_removed_fn on_removed;
629 : } ceventloop_handlers;
630 :
631 : // Creates a loop and starts its threads, so it's ready to dispatch when the
632 : // call returns. num_reactor_threads is the total thread count: 1 means one
633 : // thread polls and runs every callback (no dispatch pool at all), and more
634 : // means one poller plus num_reactor_threads - 1 dispatch workers. Never call
635 : // ceventloop_shutdown from a callback. The registry of fds and entries has
636 : // num_lock_stripes (at least 1) independent mutex and map pairs, and each fd or
637 : // queue bridge belongs to one stripe, so add, remove and modify for different
638 : // fds run in parallel. max_events_per_wait (1 to INT_MAX) sizes the poller's
639 : // batch buffer. mmgmt_procs is your allocator table, or NULL for malloc and
640 : // free; a table must set all four functions. It gives the loop handle, or
641 : // CEVENTLOOP_NULL with an error string in *err_str (when err_str isn't NULL)
642 : // on bad arguments, a failed allocation or system call, when the process has
643 : // no thread-specific key left for the two keys every loop needs (created once
644 : // per process), and after the library's exit destructors have released the
645 : // slot table. Destroy the loop with ceventloop_destroy().
646 : ceventloop ceventloop_create_mp(size_t max_events_per_wait,
647 : size_t num_lock_stripes,
648 : size_t num_reactor_threads,
649 : ccol_memmgmt_procs *mmgmt_procs,
650 : char **err_str);
651 :
652 : // Creates an event loop allocated with malloc and free and starts its
653 : // threads, so it's ready to dispatch when the call returns.
654 : // num_reactor_threads is the total thread count: 1 runs every callback on the
655 : // one poller thread, and more adds num_reactor_threads - 1 dispatch workers.
656 : // num_lock_stripes (at least 1) is the number of independent registry locks,
657 : // so registrations of different fds can change in parallel, and
658 : // max_events_per_wait (1 to INT_MAX) sizes the poller's batch. Evaluates to
659 : // the loop handle, or to CEVENTLOOP_NULL with an error string in *err_str when
660 : // err_str isn't NULL. Destroy the loop with ceventloop_destroy().
661 : #define ceventloop_create(max_events_per_wait, num_lock_stripes, \
662 : num_reactor_threads, err_str) \
663 : ceventloop_create_mp((max_events_per_wait), (num_lock_stripes), \
664 : (num_reactor_threads), NULL, (err_str))
665 :
666 : // Registers sel with the loop for one direction, sel.dir, so its readiness
667 : // reaches your callbacks, and gives the handle. For both directions of one fd,
668 : // add twice; to change direction over time, use ceventloop_modify. A second
669 : // registration for a direction already in use on the same fd is refused. Queues
670 : // have no such limit: Any number of registrations, in any loops, and cselect()
671 : // calls can watch one queue. Each producer or consumer call wakes exactly one
672 : // listener; after its callback, a listener hands the wake on while the queue is
673 : // still ready, and so does one that is removed or whose loop shuts down before
674 : // it acted. A registration whose callback moved a message is dispatched again
675 : // while the queue stays ready, and a wake that every listener declines stops
676 : // after visiting each once. A write registration that always sends is
677 : // dispatched while the queue has room, like a writable fd. Sends turned off
678 : // wake a write registration once. The registration is live before the call
679 : // returns, so a callback may run first; it gets its handle as reg. On failure
680 : // it gives CEVENTLOOP_REG_NULL and *err_str names the class: "shut down",
681 : // "direction already in use", "failed to allocate", or "a system call failed"
682 : // (a regular file or a directory always fails that way). Thread-safe, also from
683 : // a callback.
684 : ceventloop_reg ceventloop_add(ceventloop loop, cselectable sel,
685 : ceventloop_handlers handlers, void *arg,
686 : char **err_str);
687 :
688 : // An identity token for the fd behind reg, for your own bookkeeping across fd
689 : // reuse. It's unique in the loop, made when the fd is first registered, shared
690 : // by every registration on that fd and kept across ceventloop_modify. Stamp a
691 : // connection with it after the add and compare later. Correctness never depends
692 : // on it. It gives 0 (never a real generation) for a NULL, removed or stale reg
693 : // or loop, whatever thread removed it.
694 : uint64_t ceventloop_reg_generation(ceventloop loop, ceventloop_reg reg);
695 :
696 : // Changes the direction of an fd registration (a queue's direction is part of
697 : // its identity, so a queue gives ccol_invalid_args; remove and add instead).
698 : // Later callbacks see the new sel->dir. The fd's interest mask is recomputed
699 : // with no moment where the fd isn't registered. It also re-arms a registration
700 : // that the loop stopped watching after an fd event that none of its handlers
701 : // could take, even when new_dir is the current direction. It gives
702 : // ccol_success, ccol_invalid_args for a bad or stale loop or reg, a queue
703 : // registration or a bad new_dir, and ccol_not_permitted when another
704 : // registration on the fd holds new_dir. Thread-safe, also from a callback.
705 : ccol_retval ceventloop_modify(ceventloop loop, ceventloop_reg reg,
706 : cselect_dir new_dir);
707 :
708 : // Stops event delivery for an fd registration and keeps it whole: Its slot,
709 : // its count in ceventloop_reg_count and its generation stay, and only the fd's
710 : // interest mask leaves it out. No callback runs for it while paused; the other
711 : // direction of the fd isn't touched. It's the cheap form of a remove followed
712 : // by an add (no allocation, no registry churn, one epoll_ctl on one thread).
713 : // Pausing a paused registration succeeds. It gives ccol_success, or
714 : // ccol_invalid_args for a bad or stale loop or reg (one removed at the same
715 : // time included) or a queue registration. Thread-safe, also from a callback.
716 : // Undo it with ceventloop_resume().
717 : ccol_retval ceventloop_pause(ceventloop loop, ceventloop_reg reg);
718 :
719 : // Puts a registration that ceventloop_pause() paused back into the fd's
720 : // interest mask, so its callbacks run again, and re-arms one that the loop
721 : // stopped watching after an fd event that none of its handlers could take.
722 : // Resuming anything else succeeds and does nothing. It gives ccol_success, or
723 : // ccol_invalid_args for a bad or stale loop or reg (the connection may have
724 : // closed meanwhile) or a queue registration. Thread-safe, also from a callback
725 : // and from a thread other than the one that paused it.
726 : ccol_retval ceventloop_resume(ceventloop loop, ceventloop_reg reg);
727 :
728 : // Removes a registration. It may run from the registration's own callback,
729 : // from any thread, and during a dispatch of it. After it returns the loop calls
730 : // none of its callbacks again, collected ones included, but it doesn't wait for
731 : // a dispatch already running: To free an arg that a callback uses, wait for
732 : // on_removed (waiting here could deadlock on your locks). From the
733 : // registration's own callback, or when it was never dispatched, you may free
734 : // arg at once. It never closes the fd. Remove every registration of an fd
735 : // before you close it; once the last one is gone the loop has stopped watching
736 : // the fd, so the number can be registered again independently. A registration
737 : // whose fd was closed first keeps the number, and an add that reuses it fails.
738 : // For a queue the waiter is unlinked before the call returns, and destroying
739 : // the queue waits for a callback still running, so drain, remove, destroy is
740 : // safe from any thread that isn't running one of its callbacks. It gives
741 : // ccol_success (also for a call that races another remove of the same reg) or
742 : // ccol_invalid_args for a bad or stale loop or reg, including one an earlier
743 : // call already removed.
744 : ccol_retval ceventloop_remove(ceventloop loop, ceventloop_reg reg);
745 :
746 : // Gives the number of live registrations (one fd with both directions counts
747 : // 2), or (size_t)-1 for a bad or stale loop.
748 : size_t ceventloop_reg_count(ceventloop loop);
749 :
750 : // Stops the poller and the dispatch workers and joins them, after each finishes
751 : // its current job, so no dispatch is in flight when it returns. It may be
752 : // called more than once; ceventloop_destroy calls it when needed. From then on
753 : // the loop's queue registrations take no wake (one they held goes to the
754 : // queue's next listener), registrations stay until removed or destroyed, and
755 : // ceventloop_add is refused. It gives ccol_success, ccol_invalid_args for a bad
756 : // or stale loop, or ccol_not_permitted from a callback on one of the loop's
757 : // threads, which would join itself.
758 : ccol_retval ceventloop_shutdown(ceventloop loop);
759 :
760 : // Internal: Destroys the loop; ceventloop_destroy() calls it and then clears
761 : // the handle. It shuts the loop down (the same drain as ceventloop_shutdown,
762 : // with loop still resolving, so a callback can remove its registrations, close
763 : // its fd and free arg while another thread destroys the loop), then frees every
764 : // registration left, unlinking queue registrations from their queues and
765 : // running every due on_removed. After the drain the handle stops resolving. A
766 : // stale, racing or forged handle is a fatal error (CEVENTLOOP_NULL is a no-op),
767 : // and so is a call from a callback on one of the loop's threads. Destroy a
768 : // watched queue only after removing its registration; the queue destroy
769 : // asserts otherwise.
770 : void ceventloop__destroy(ceventloop loop);
771 :
772 : // Internal: The cleanup handler of the _scoped macros. NULL does nothing. gcov
773 : // can't count the closing brace of this always-inline function at -O3, hence
774 : // the marker on that one line; don't copy it to a line a test can reach.
775 69 : static inline __attribute__((always_inline)) void ceventloop__destroy_cleanup(
776 : ceventloop *lp) {
777 69 : if (lp && *lp) {
778 65 : ceventloop__destroy(*lp);
779 67 : *lp = CEVENTLOOP_NULL;
780 : }
781 : } /* LCOV_EXCL_LINE */
782 :
783 : // Destroys the loop and sets loop to CEVENTLOOP_NULL, so the stale handle
784 : // isn't used again (loop is evaluated once and must be a modifiable lvalue;
785 : // CEVENTLOOP_NULL does nothing). It first shuts the loop down and drains it
786 : // while the handle still works, so a callback that runs meanwhile can remove
787 : // its registrations, close its fd and free its arg. Then it frees every
788 : // registration left, unlinks queue registrations from their queues, runs every
789 : // due on_removed, and waits for every resolved use of the handle to finish. A
790 : // stale or forged handle, a concurrent destroy of the same handle, and a call
791 : // from one of the loop's own callbacks are fatal errors. Destroy a watched
792 : // queue only after you remove its registration.
793 : #define ceventloop_destroy(loop) \
794 : ceventloop__destroy_impl(loop, \
795 : ccol__uniq(ceventloop__destroy_slot, __COUNTER__))
796 :
797 : // Internal: The body of ceventloop_destroy(), like ccircq__destroy_impl().
798 : #define ceventloop__destroy_impl(loop, slot) \
799 : do { \
800 : __typeof__(loop) *slot = &(loop); \
801 : ceventloop__destroy(*slot); \
802 : *slot = CEVENTLOOP_NULL; \
803 : } while (0)
804 :
805 : // Declares an uninitialized loop handle variable called name, for a loop that
806 : // you create later with ceventloop_create() and destroy yourself with
807 : // ceventloop_destroy().
808 : #define ceventloop_declare(name) ceventloop name
809 :
810 : // Declares a loop handle variable called name that starts at CEVENTLOOP_NULL
811 : // and is destroyed when it goes out of scope, so no exit path can leak the
812 : // loop. Create the loop into it later with ceventloop_create().
813 : #define ceventloop_declare_scoped(name) \
814 : ceventloop name ccol__destructor(ceventloop__destroy_cleanup) = \
815 : CEVENTLOOP_NULL
816 :
817 : // Declares a loop handle variable called name and creates the loop with the
818 : // default allocator, for code that can't go on without its loop: A failed
819 : // create stops the program with a fatal error that names the variable and the
820 : // reason. max_events_per_wait (1 to INT_MAX) sizes the poller's batch,
821 : // num_lock_stripes (at least 1) is the number of registry locks, and
822 : // num_reactor_threads (at least 1) is the total thread count. You destroy the
823 : // loop with ceventloop_destroy(), after removing every registration. For
824 : // example ceventloop_construct(loop, 32, 1, 1).
825 : #define ceventloop_construct(name, max_events_per_wait, num_lock_stripes, \
826 : num_reactor_threads) \
827 : ceventloop name = CEVENTLOOP_NULL; \
828 : do { \
829 : char *ceventloop__err = NULL; \
830 : (name) = ceventloop_create((max_events_per_wait), (num_lock_stripes), \
831 : (num_reactor_threads), &ceventloop__err); \
832 : if (!(name)) { \
833 : ccol__fatal_err("ceventloop_construct('%s'): %s", #name, \
834 : ceventloop__err ? ceventloop__err : "unknown error"); \
835 : } \
836 : } while (0)
837 :
838 : // Declares a loop handle variable called name and creates the loop with the
839 : // default allocator; a failed create stops the program with a fatal error that
840 : // names the variable and the reason. The loop is destroyed when name goes out
841 : // of scope, so no exit path can leak it; remove its registrations first.
842 : // max_events_per_wait (1 to INT_MAX) sizes the poller's batch,
843 : // num_lock_stripes (at least 1) is the number of registry locks, and
844 : // num_reactor_threads (at least 1) is the total thread count.
845 : #define ceventloop_construct_scoped(name, max_events_per_wait, \
846 : num_lock_stripes, num_reactor_threads) \
847 : ceventloop name ccol__destructor(ceventloop__destroy_cleanup) = \
848 : CEVENTLOOP_NULL; \
849 : do { \
850 : char *ceventloop__err = NULL; \
851 : (name) = ceventloop_create((max_events_per_wait), (num_lock_stripes), \
852 : (num_reactor_threads), &ceventloop__err); \
853 : if (!(name)) { \
854 : ccol__fatal_err("ceventloop_construct_scoped('%s'): %s", #name, \
855 : ceventloop__err ? ceventloop__err : "unknown error"); \
856 : } \
857 : } while (0)
858 :
859 : #pragma GCC visibility pop
|