1 /// @file htslib/thread_pool.h
2 /// Thread pool for multi-threading applications.
3 /*
4     Copyright (c) 2013-2017, 2019 Genome Research Ltd.
5 
6     Author: James Bonfield <jkb@sanger.ac.uk>
7 
8 Permission is hereby granted, free of charge, to any person obtaining a copy
9 of this software and associated documentation files (the "Software"), to deal
10 in the Software without restriction, including without limitation the rights
11 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 copies of the Software, and to permit persons to whom the Software is
13 furnished to do so, subject to the following conditions:
14 
15 The above copyright notice and this permission notice shall be included in
16 all copies or substantial portions of the Software.
17 
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 DEALINGS IN THE SOFTWARE.  */
25 
26 /*
27  * This file implements a thread pool for multi-threading applications.  It
28  * consists of two distinct interfaces: thread pools and thread process
29  * queues (a queue of both jobs to-do and of the results of completed jobs).
30  * Do not confuse "process" here with a unix PID; rather it is analogous to a
31  * program reading a stream of data blocks, processing them in some manner,
32  * and outputting a stream of new data blocks.
33  *
34  * The pool of threads is given a function pointer and void* data to pass in.
35  * This means the pool can run jobs of multiple types, albeit first come
36  * first served with no job scheduling except to pick tasks for the
37  * processes that have room to store the result.
38  *
39  * Upon completion, the return value from the function pointer is
40  * added to back to the process result queue if required.  We may have
41  * multiple "processes" in use for the one pool.
42  *
43  * To see example usage, please look at the #ifdef TEST_MAIN code in
44  * thread_pool.c.
45  */
46 
47 module htslib.thread_pool;
48 
49 extern (C):
50 
51 /*-----------------------------------------------------------------------------
52  * Opaque data types.
53  *
54  * Actual definitions are in thread_pool_internal.h, but these should only
55  * be used by thread_pool.c itself.
56  */
57 
58 /**
59  * An hts_tpool_process implements a queue of input jobs to process and a
60  * queue of resulting output  post-processing.  Internally it consists of two
61  * buffered queues, analogous to the pipes in a unix pipeline:
62  *    ...input | process |  output...
63  *
64  * Both input and output queues have size limits to prevent either queue from
65  * growing too large and serial numbers to ensure sequential consumption of
66  * the output.
67  *
68  * The thread pool may have many heterogeneous tasks, each using its own
69  * process mixed into the same thread pool.
70  */
71 struct hts_tpool_process;
72 
73 /**
74  * The single pool structure itself.
75  *
76  * This knows nothing about the nature of the jobs or where their output is
77  * going, but it maintains a list of process-queues associated with this pool
78  * from which the jobs are taken.
79  */
80 struct hts_tpool;
81 
82 /**
83  * An output, after job has executed.
84  */
85 struct hts_tpool_result;
86 
87 /*-----------------------------------------------------------------------------
88  * Thread pool external functions
89  */
90 
91 /**
92  * Creates a worker pool with n worker threads.
93  *
94  * Returns pool pointer on success;
95  *         NULL on failure
96  *
97  * The hts_tpool struct returned by a successful call should be freed
98  * via hts_tpool_destroy() when it is no longer needed.
99  */
100 hts_tpool* hts_tpool_init(int n);
101 
102 /**
103  * Returns the number of requested threads for a pool.
104  */
105 int hts_tpool_size(hts_tpool* p);
106 
107 /// Add an item to the work pool.
108 /**
109  * @param p     Thread pool
110  * @param q     Process queue
111  * @param func  Function run by the thread pool
112  * @param arg   Data for use by func()
113  * @return 0 on success
114  *        -1 on failure
115  */
116 // FIXME: should this drop the hts_tpool*p argument? It's just q->p
117 int hts_tpool_dispatch(
118     hts_tpool* p,
119     hts_tpool_process* q,
120     void* function(void* arg) func,
121     void* arg);
122 
123 /// Add an item to the work pool, with nonblocking option.
124 /**
125  * @param p         Thread pool
126  * @param q         Process queue
127  * @param func      Function run by the thread pool
128  * @param arg       Data for use by func()
129  * @param nonblock  Non-blocking flag (see description)
130  * @return 0 on success
131  *        -1 on failure
132  *
133  * The @p nonblock parameter can take one of the following values:
134  *      0 => block if input queue is full
135  *     +1 => don't block if input queue is full, but do not add task
136  *     -1 => add task regardless of whether queue is full (over-size)
137  *
138  * If @p nonblock is +1 and the queue is full, -1 will be returned and
139  * `errno` is set to `EAGAIN`.
140  */
141 int hts_tpool_dispatch2(
142     hts_tpool* p,
143     hts_tpool_process* q,
144     void* function(void* arg) func,
145     void* arg,
146     int nonblock);
147 
148 /// Add an item to the work pool, with nonblocking and cleanup callbacks.
149 /**
150  * @param p               Thread pool
151  * @param q               Process queue
152  * @param exec_func       Function run by the thread pool
153  * @param arg             Data for use by func()
154  * @param job_cleanup     Callback to clean up when discarding jobs
155  * @param result_cleanup  Callback to clean up when discarding result data
156  * @param nonblock        Non-blocking flag (see description)
157  * @return 0 on success
158  *        -1 on failure
159  *
160  * The @p nonblock parameter can take one of the following values:
161  *      0 => block if input queue is full
162  *     +1 => don't block if input queue is full, but do not add task
163  *     -1 => add task regardless of whether queue is full (over-size)
164  *
165  * If @p nonblock is +1 and the queue is full, -1 will be returned and
166  * `errno` is set to `EAGAIN`.
167  *
168  * The job_cleanup() and result_cleanup() callbacks are used when discarding
169  * data from a queue, for example when calling hts_tpool_process_reset()
170  * or hts_tpool_process_destroy().
171  *
172  * If not NULL, job_cleanup() will be called for each pending job with the
173  * value of @p arg that was set for that job.  This can be used to free
174  * any data associated with @p arg, and also @p arg itself.
175  *
176  * Similarly, result_cleanup() can be used to free any results left by
177  * jobs that had started before hts_tpool_process_reset() was called.
178  * The argument passed to result_cleanup() is the pointer that would
179  * have been returned by calling hts_tpool_result_data() on the result
180  * when pulled from the queue.
181  *
182  * job_cleanup() and result_cleanup() are only called when discarding jobs.
183  * For jobs that are processed normally, it is the resposibility of
184  * exec_func() and / or consumers of any results to do any cleaning up
185  * necessary.
186  */
187 int hts_tpool_dispatch3(
188     hts_tpool* p,
189     hts_tpool_process* q,
190     void* function(void* arg) exec_func,
191     void* arg,
192     void function(void* arg) job_cleanup,
193     void function(void* data) result_cleanup,
194     int nonblock);
195 
196 /**
197  * Wakes up a single thread stuck in dispatch and make it return with
198  * errno EAGAIN.
199  */
200 void hts_tpool_wake_dispatch(hts_tpool_process* q);
201 
202 /**
203  * Flushes the process-queue, but doesn't exit. This simply drains the queue
204  * and ensures all worker threads have finished their current tasks
205  * associated with this process.
206  *
207  * NOT: This does not mean the worker threads are not executing jobs in
208  * another process-queue.
209  *
210  * Returns 0 on success;
211  *        -1 on failure
212  */
213 int hts_tpool_process_flush(hts_tpool_process* q);
214 
215 /**
216  * Resets a process to the initial state.
217  *
218  * This removes any queued up input jobs, disables any notification of
219  * new results/output, flushes what is left and then discards any
220  * queued output.  Anything consumer stuck in a wait on results to
221  * appear should stay stuck and will only wake up when new data is
222  * pushed through the queue.
223  *
224  * Returns 0 on success;
225  *        -1 on failure
226  */
227 int hts_tpool_process_reset(hts_tpool_process* q, int free_results);
228 
229 /** Returns the process queue size */
230 int hts_tpool_process_qsize(hts_tpool_process* q);
231 
232 /**
233  * Destroys a thread pool.  The threads are joined into the main
234  * thread so they will finish their current work load.
235  */
236 void hts_tpool_destroy(hts_tpool* p);
237 
238 /**
239  * Destroys a thread pool without waiting on jobs to complete.
240  * Use hts_tpool_kill(p) to quickly exit after a fatal error.
241  */
242 void hts_tpool_kill(hts_tpool* p);
243 
244 /**
245  * Pulls the next item off the process result queue.  The caller should free
246  * it (and any internals as appropriate) after use.  This doesn't wait for a
247  * result to be present.
248  *
249  * Results will be returned in strict order.
250  *
251  * Returns hts_tpool_result pointer if a result is ready.
252  *         NULL if not.
253  */
254 hts_tpool_result* hts_tpool_next_result(hts_tpool_process* q);
255 
256 /**
257  * Pulls the next item off the process result queue.  The caller should free
258  * it (and any internals as appropriate) after use.  This will wait for
259  * a result to be present if none are currently available.
260  *
261  * Results will be returned in strict order.
262  *
263  * Returns hts_tpool_result pointer if a result is ready.
264  *         NULL on error or during shutdown.
265  */
266 hts_tpool_result* hts_tpool_next_result_wait(hts_tpool_process* q);
267 
268 /**
269  * Frees a result 'r' and if free_data is true also frees
270  * the internal r->data result too.
271  */
272 void hts_tpool_delete_result(hts_tpool_result* r, int free_data);
273 
274 /**
275  * Returns the data portion of a hts_tpool_result, corresponding
276  * to the actual "result" itself.
277  */
278 void* hts_tpool_result_data(hts_tpool_result* r);
279 
280 /**
281  * Initialises a thread process-queue.
282  *
283  * In_only, if true, indicates that the process generates does not need to
284  * hold any output.  Otherwise an output queue is used to store the results
285  * of processing each input job.
286  *
287  * Results hts_tpool_process pointer on success;
288  *         NULL on failure
289  *
290  * The hts_tpool_process struct returned by a successful call should be freed
291  * via hts_tpool_process_destroy() when it is no longer needed.
292  */
293 hts_tpool_process* hts_tpool_process_init(hts_tpool* p, int qsize, int in_only);
294 
295 /** Deallocates memory for a thread process-queue.
296  * Must be called before the thread pool is destroyed.
297  */
298 void hts_tpool_process_destroy(hts_tpool_process* q);
299 
300 /**
301  * Returns true if there are no items in the process results queue and
302  * also none still pending.
303  */
304 int hts_tpool_process_empty(hts_tpool_process* q);
305 
306 /**
307  * Returns the number of completed jobs in the process results queue.
308  */
309 int hts_tpool_process_len(hts_tpool_process* q);
310 
311 /**
312  * Returns the number of completed jobs in the process results queue plus the
313  * number running and queued up to run.
314  */
315 int hts_tpool_process_sz(hts_tpool_process* q);
316 
317 /**
318  * Shutdown a process.
319  *
320  * This sets the shutdown flag and wakes any threads waiting on process
321  * condition variables.
322  */
323 void hts_tpool_process_shutdown(hts_tpool_process* q);
324 
325 /**
326  * Attach and detach a thread process-queue with / from the thread pool
327  * scheduler.
328  *
329  * We need to do attach after making a thread process, but may also wish
330  * to temporarily detach if we wish to stop running jobs on a specific
331  * process while permitting other process to continue.
332  */
333 void hts_tpool_process_attach(hts_tpool* p, hts_tpool_process* q);
334 
335 void hts_tpool_process_detach(hts_tpool* p, hts_tpool_process* q);
336 
337 /**
338  * Increment and decrement the reference count in a process-queue.
339  * If the queue is being driven from two external (non thread-pool)
340  * threads, eg "main" and a "reader", this permits each end to
341  * decrement its use of the process-queue independently.
342  */
343 void hts_tpool_process_ref_incr(hts_tpool_process* q);
344 
345 void hts_tpool_process_ref_decr(hts_tpool_process* q);
346