forked from samtools/htslib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread_pool.c
1376 lines (1127 loc) · 39.5 KB
/
thread_pool.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* thread_pool.c -- A pool of generic worker threads
Copyright (c) 2013-2017 Genome Research Ltd.
Author: James Bonfield <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE. */
#ifndef TEST_MAIN
#include <config.h>
#endif
#include <stdlib.h>
#include <inttypes.h>
#include <signal.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <assert.h>
#include <stdarg.h>
#include <unistd.h>
#include <limits.h>
#include "thread_pool_internal.h"
//#define DEBUG
#ifdef DEBUG
static int worker_id(hts_tpool *p) {
int i;
pthread_t s = pthread_self();
for (i = 0; i < p->tsize; i++) {
if (pthread_equal(s, p->t[i].tid))
return i;
}
return -1;
}
int DBG_OUT(FILE *fp, char *fmt, ...) {
va_list args;
va_start(args, fmt);
return vfprintf(fp, fmt, args);
}
#else
#define DBG_OUT(...) do{}while(0)
#endif
/* ----------------------------------------------------------------------------
* A process-queue to hold results from the thread pool.
*
* Each thread pool may have jobs of multiple types being queued up and
* interleaved, so we attach several job process-queues to a single pool.
*
* The jobs themselves are expected to push their results onto their
* appropriate results queue.
*/
/*
* Adds a result to the end of the process result queue.
*
* Returns 0 on success;
* -1 on failure
*/
static int hts_tpool_add_result(hts_tpool_job *j, void *data) {
hts_tpool_process *q = j->q;
hts_tpool_result *r;
pthread_mutex_lock(&q->p->pool_m);
DBG_OUT(stderr, "%d: Adding result to queue %p, serial %"PRId64", %d of %d\n",
worker_id(j->p), q, j->serial, q->n_output+1, q->qsize);
if (--q->n_processing == 0)
pthread_cond_signal(&q->none_processing_c);
/* No results queue is fine if we don't want any results back */
if (q->in_only) {
pthread_mutex_unlock(&q->p->pool_m);
return 0;
}
if (!(r = malloc(sizeof(*r))))
return -1;
r->next = NULL;
r->data = data;
r->serial = j->serial;
q->n_output++;
if (q->output_tail) {
q->output_tail->next = r;
q->output_tail = r;
} else {
q->output_head = q->output_tail = r;
}
assert(r->serial >= q->next_serial // Or it will never be dequeued ...
|| q->next_serial == INT_MAX); // ... unless flush in progress.
if (r->serial == q->next_serial) {
DBG_OUT(stderr, "%d: Broadcasting result_avail (id %"PRId64")\n",
worker_id(j->p), r->serial);
pthread_cond_broadcast(&q->output_avail_c);
DBG_OUT(stderr, "%d: Broadcast complete\n", worker_id(j->p));
}
pthread_mutex_unlock(&q->p->pool_m);
return 0;
}
static void wake_next_worker(hts_tpool_process *q, int locked);
/* Core of hts_tpool_next_result() */
static hts_tpool_result *hts_tpool_next_result_locked(hts_tpool_process *q) {
hts_tpool_result *r, *last;
if (q->shutdown)
return NULL;
for (last = NULL, r = q->output_head; r; last = r, r = r->next) {
if (r->serial == q->next_serial)
break;
}
if (r) {
// Remove r from out linked list
if (q->output_head == r)
q->output_head = r->next;
else
last->next = r->next;
if (q->output_tail == r)
q->output_tail = last;
if (!q->output_head)
q->output_tail = NULL;
q->next_serial++;
q->n_output--;
if (q->qsize && q->n_output < q->qsize) {
// Not technically input full, but can guarantee there is
// room for the input to go somewhere so we still signal.
// The waiting code will then check the condition again.
if (q->n_input < q->qsize)
pthread_cond_signal(&q->input_not_full_c);
if (!q->shutdown)
wake_next_worker(q, 1);
}
}
return r;
}
/*
* Pulls the next item off the process result queue. The caller should free
* it (and any internals as appropriate) after use. This doesn't wait for a
* result to be present.
*
* Results will be returned in strict order.
*
* Returns hts_tpool_result pointer if a result is ready.
* NULL if not.
*/
hts_tpool_result *hts_tpool_next_result(hts_tpool_process *q) {
hts_tpool_result *r;
DBG_OUT(stderr, "Requesting next result on queue %p\n", q);
pthread_mutex_lock(&q->p->pool_m);
r = hts_tpool_next_result_locked(q);
pthread_mutex_unlock(&q->p->pool_m);
DBG_OUT(stderr, "(q=%p) Found %p\n", q, r);
return r;
}
/*
* Pulls the next item off the process result queue. The caller should free
* it (and any internals as appropriate) after use. This will wait for
* a result to be present if none are currently available.
*
* Results will be returned in strict order.
*
* Returns hts_tpool_result pointer if a result is ready.
* NULL on error or during shutdown.
*/
hts_tpool_result *hts_tpool_next_result_wait(hts_tpool_process *q) {
hts_tpool_result *r;
pthread_mutex_lock(&q->p->pool_m);
while (!(r = hts_tpool_next_result_locked(q))) {
/* Possible race here now avoided via _locked() call, but incase... */
struct timeval now;
struct timespec timeout;
gettimeofday(&now, NULL);
timeout.tv_sec = now.tv_sec + 10;
timeout.tv_nsec = now.tv_usec * 1000;
q->ref_count++;
if (q->shutdown) {
int rc = --q->ref_count;
pthread_mutex_unlock(&q->p->pool_m);
if (rc == 0)
hts_tpool_process_destroy(q);
return NULL;
}
pthread_cond_timedwait(&q->output_avail_c, &q->p->pool_m, &timeout);
q->ref_count--;
}
pthread_mutex_unlock(&q->p->pool_m);
return r;
}
/*
* Returns true if there are no items in the process results queue and
* also none still pending.
*/
int hts_tpool_process_empty(hts_tpool_process *q) {
int empty;
pthread_mutex_lock(&q->p->pool_m);
empty = q->n_input == 0 && q->n_processing == 0 && q->n_output == 0;
pthread_mutex_unlock(&q->p->pool_m);
return empty;
}
void hts_tpool_process_ref_incr(hts_tpool_process *q) {
pthread_mutex_lock(&q->p->pool_m);
q->ref_count++;
pthread_mutex_unlock(&q->p->pool_m);
}
void hts_tpool_process_ref_decr(hts_tpool_process *q) {
pthread_mutex_lock(&q->p->pool_m);
if (--q->ref_count <= 0) {
pthread_mutex_unlock(&q->p->pool_m);
hts_tpool_process_destroy(q);
return;
}
// maybe also call destroy here if needed?
pthread_mutex_unlock(&q->p->pool_m);
}
/*
* Returns the number of completed jobs in the process results queue.
*/
int hts_tpool_process_len(hts_tpool_process *q) {
int len;
pthread_mutex_lock(&q->p->pool_m);
len = q->n_output;
pthread_mutex_unlock(&q->p->pool_m);
return len;
}
/*
* Returns the number of completed jobs in the process results queue plus the
* number running and queued up to run.
*/
int hts_tpool_process_sz(hts_tpool_process *q) {
int len;
pthread_mutex_lock(&q->p->pool_m);
len = q->n_output + q->n_input + q->n_processing;
pthread_mutex_unlock(&q->p->pool_m);
return len;
}
/*
* Shutdown a process.
*
* This sets the shutdown flag and wakes any threads waiting on process
* condition variables.
*/
void hts_tpool_process_shutdown(hts_tpool_process *q) {
pthread_mutex_lock(&q->p->pool_m);
q->shutdown = 1;
pthread_cond_broadcast(&q->output_avail_c);
pthread_cond_broadcast(&q->input_not_full_c);
pthread_cond_broadcast(&q->input_empty_c);
pthread_cond_broadcast(&q->none_processing_c);
pthread_mutex_unlock(&q->p->pool_m);
}
/*
* Frees a result 'r' and if free_data is true also frees
* the internal r->data result too.
*/
void hts_tpool_delete_result(hts_tpool_result *r, int free_data) {
if (!r)
return;
if (free_data && r->data)
free(r->data);
free(r);
}
/*
* Returns the data portion of a hts_tpool_result, corresponding
* to the actual "result" itself.
*/
void *hts_tpool_result_data(hts_tpool_result *r) {
return r->data;
}
/*
* Initialises a thread process-queue.
*
* In_only, if true, indicates that the process generates does not need to
* hold any output. Otherwise an output queue is used to store the results
* of processing each input job.
*
* Results hts_tpool_process pointer on success;
* NULL on failure
*/
hts_tpool_process *hts_tpool_process_init(hts_tpool *p, int qsize, int in_only) {
hts_tpool_process *q = malloc(sizeof(*q));
pthread_cond_init(&q->output_avail_c, NULL);
pthread_cond_init(&q->input_not_full_c, NULL);
pthread_cond_init(&q->input_empty_c, NULL);
pthread_cond_init(&q->none_processing_c,NULL);
q->p = p;
q->input_head = NULL;
q->input_tail = NULL;
q->output_head = NULL;
q->output_tail = NULL;
q->next_serial = 0;
q->curr_serial = 0;
q->n_input = 0;
q->n_output = 0;
q->n_processing= 0;
q->qsize = qsize;
q->in_only = in_only;
q->shutdown = 0;
q->wake_dispatch = 0;
q->ref_count = 1;
q->next = NULL;
q->prev = NULL;
hts_tpool_process_attach(p, q);
return q;
}
/* Deallocates memory for a thread process-queue.
* Must be called before the thread pool is destroyed.
*/
void hts_tpool_process_destroy(hts_tpool_process *q) {
DBG_OUT(stderr, "Destroying results queue %p\n", q);
if (!q)
return;
// Ensure it's fully drained before destroying the queue
hts_tpool_process_reset(q, 0);
pthread_mutex_lock(&q->p->pool_m);
hts_tpool_process_detach(q->p, q);
hts_tpool_process_shutdown(q);
// Maybe a worker is scanning this queue, so delay destruction
if (--q->ref_count > 0) {
pthread_mutex_unlock(&q->p->pool_m);
return;
}
pthread_cond_destroy(&q->output_avail_c);
pthread_cond_destroy(&q->input_not_full_c);
pthread_cond_destroy(&q->input_empty_c);
pthread_cond_destroy(&q->none_processing_c);
pthread_mutex_unlock(&q->p->pool_m);
free(q);
DBG_OUT(stderr, "Destroyed results queue %p\n", q);
}
/*
* Attach and detach a thread process-queue with / from the thread pool
* scheduler.
*
* We need to do attach after making a thread process, but may also wish
* to temporarily detach if we wish to stop running jobs on a specific
* process while permitting other process to continue.
*/
void hts_tpool_process_attach(hts_tpool *p, hts_tpool_process *q) {
pthread_mutex_lock(&p->pool_m);
if (p->q_head) {
q->next = p->q_head;
q->prev = p->q_head->prev;
p->q_head->prev->next = q;
p->q_head->prev = q;
} else {
q->next = q;
q->prev = q;
}
p->q_head = q;
assert(p->q_head && p->q_head->prev && p->q_head->next);
pthread_mutex_unlock(&p->pool_m);
}
void hts_tpool_process_detach(hts_tpool *p, hts_tpool_process *q) {
pthread_mutex_lock(&p->pool_m);
if (!p->q_head || !q->prev || !q->next)
goto done;
hts_tpool_process *curr = p->q_head, *first = curr;
do {
if (curr == q) {
q->next->prev = q->prev;
q->prev->next = q->next;
p->q_head = q->next;
q->next = q->prev = NULL;
// Last one
if (p->q_head == q)
p->q_head = NULL;
break;
}
curr = curr->next;
} while (curr != first);
done:
pthread_mutex_unlock(&p->pool_m);
}
/* ----------------------------------------------------------------------------
* The thread pool.
*/
#define TDIFF(t2,t1) ((t2.tv_sec-t1.tv_sec)*1000000 + t2.tv_usec-t1.tv_usec)
/*
* A worker thread.
*
* Once woken, each thread checks each process-queue in the pool in turn,
* looking for input jobs that also have room for the output (if it requires
* storing). If found, we execute it and repeat.
*
* If we checked all input queues and find no such job, then we wait until we
* are signalled to check again.
*/
static void *tpool_worker(void *arg) {
hts_tpool_worker *w = (hts_tpool_worker *)arg;
hts_tpool *p = w->p;
hts_tpool_job *j;
for (;;) {
// Pop an item off the pool queue
pthread_mutex_lock(&p->pool_m);
assert(p->q_head == 0 || (p->q_head->prev && p->q_head->next));
int work_to_do = 0;
hts_tpool_process *first = p->q_head, *q = first;
do {
if (p->shutdown)
break;
// Iterate over queues, finding one with jobs and also
// room to put the result.
//if (q && q->input_head && !hts_tpool_process_output_full(q)) {
if (q && q->input_head && q->qsize - q->n_output > p->tsize - p->nwaiting) {
//printf("Work\n");
work_to_do = 1;
break;
}
if (q) q = q->next;
} while (q && q != first);
if (p->shutdown) {
shutdown:
#ifdef DEBUG
fprintf(stderr, "%d: Shutting down\n", worker_id(p));
#endif
pthread_mutex_unlock(&p->pool_m);
return NULL;
}
if (!work_to_do) {
// We scanned all queues and cannot process any, so we wait.
p->nwaiting++;
// Push this thread to the top of the waiting stack
if (p->t_stack_top == -1 || p->t_stack_top > w->idx)
p->t_stack_top = w->idx;
p->t_stack[w->idx] = 1;
// printf("%2d: no work. In=%d Proc=%d Out=%d full=%d\n",
// w->idx, p->q_head->n_input, p->q_head->n_processing, p->q_head->n_output,
// hts_tpool_process_output_full(p->q_head));
pthread_cond_wait(&w->pending_c, &p->pool_m);
p->t_stack[w->idx] = 0;
/* Find new t_stack_top */
int i;
p->t_stack_top = -1;
for (i = 0; i < p->tsize; i++) {
if (p->t_stack[i]) {
p->t_stack_top = i;
break;
}
}
p->nwaiting--;
pthread_mutex_unlock(&p->pool_m);
continue; // To outer for(;;) loop.
}
// Otherwise work_to_do, so process as many items in this queue as
// possible before switching to another queue. This means threads
// often end up being dedicated to one type of work.
q->ref_count++;
while (q->input_head && q->qsize - q->n_output > q->n_processing) {
if (p->shutdown)
goto shutdown;
j = q->input_head;
assert(j->p == p);
if (!(q->input_head = j->next))
q->input_tail = NULL;
// Transitioning from full queue to not-full means we can wake up
// any blocked dispatch threads. We broadcast this as it's only
// happening once (on the transition) rather than every time we
// are below qsize.
// (I wish I could remember why io_lib rev 3660 changed this from
// == to >=, but keeping it just incase!)
q->n_processing++;
if (q->n_input-- >= q->qsize)
pthread_cond_broadcast(&q->input_not_full_c);
if (q->n_input == 0)
pthread_cond_signal(&q->input_empty_c);
p->njobs--; // Total number of jobs; used to adjust to CPU scaling
pthread_mutex_unlock(&p->pool_m);
DBG_OUT(stderr, "%d: Processing queue %p, serial %"PRId64"\n",
worker_id(j->p), q, j->serial);
hts_tpool_add_result(j, j->func(j->arg));
//memset(j, 0xbb, sizeof(*j));
free(j);
pthread_mutex_lock(&p->pool_m);
}
if (--q->ref_count == 0) // we were the last user
hts_tpool_process_destroy(q);
else
// Out of jobs on this queue, so restart search from next one.
// This is equivalent to "work-stealing".
p->q_head = q->next;
pthread_mutex_unlock(&p->pool_m);
}
}
static void wake_next_worker(hts_tpool_process *q, int locked) {
hts_tpool *p = q->p;
if (!locked)
pthread_mutex_lock(&p->pool_m);
// Update the q_head to be this queue so we'll start processing
// the queue we know to have results.
assert(q->prev && q->next); // attached
p->q_head = q;
// Wake up if we have more jobs waiting than CPUs. This partially combats
// CPU frequency scaling effects. Starting too many threads and then
// running out of jobs can cause each thread to have lots of start/stop
// cycles, which then translates often to CPU frequency scaling
// adjustments. Instead it is better to only start as many threads as we
// need to keep the throughput up, meaning some threads run flat out and
// others are idle.
//
// This isn't perfect as we need to know how many can actually start,
// rather than how many are waiting. A limit on output queue size makes
// these two figures different.
assert(p->njobs >= q->n_input);
int running = p->tsize - p->nwaiting;
int sig = p->t_stack_top >= 0 && p->njobs > p->tsize - p->nwaiting
&& (!q || q->n_processing < q->qsize - q->n_output);
//#define AVG_USAGE
#ifdef AVG_USAGE
// Track average number of running threads and try to keep close.
// We permit this to change, but slowly. This avoids "boom and bust" cycles
// where we read a lot of data, start a lot of jobs, then become idle again.
// This way some threads run steadily and others dormant, which is better
// for throughput.
//
// It's 50:50 if this is a good thing. It helps some tasks quite significantly
// while slightly hindering other (perhaps more usual) jobs.
if (++p->n_count == 256) {
p->n_count >>= 1;
p->n_running >>= 1;
}
p->n_running += running;
// Built in lag to avoid see-sawing. Is this safe in all cases?
if (sig && p->n_count >= 128 && running*p->n_count > p->n_running+1) sig=0;
#endif
if (0) {
printf("%d waiting, %d running, %d output, %d, arun %d => %d\t", p->njobs,
running, q->n_output, q->qsize - q->n_output,
p->n_running/p->n_count, sig);
int i;
for (i = 0; i < p->tsize; i++)
putchar("x "[p->t_stack[i]]);
putchar('\n');
}
if (sig)
pthread_cond_signal(&p->t[p->t_stack_top].pending_c);
if (!locked)
pthread_mutex_unlock(&p->pool_m);
}
/*
* Creates a worker pool with n worker threads.
*
* Returns pool pointer on success;
* NULL on failure
*/
hts_tpool *hts_tpool_init(int n) {
int i;
hts_tpool *p = malloc(sizeof(*p));
p->tsize = n;
p->njobs = 0;
p->nwaiting = 0;
p->shutdown = 0;
p->q_head = NULL;
p->t_stack = NULL;
p->n_count = 0;
p->n_running = 0;
p->t = malloc(n * sizeof(p->t[0]));
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&p->pool_m, &attr);
pthread_mutexattr_destroy(&attr);
if (!(p->t_stack = malloc(n * sizeof(*p->t_stack))))
return NULL;
p->t_stack_top = -1;
pthread_mutex_lock(&p->pool_m);
for (i = 0; i < n; i++) {
hts_tpool_worker *w = &p->t[i];
p->t_stack[i] = 0;
w->p = p;
w->idx = i;
pthread_cond_init(&w->pending_c, NULL);
if (0 != pthread_create(&w->tid, NULL, tpool_worker, w)) {
pthread_mutex_unlock(&p->pool_m);
return NULL;
}
}
pthread_mutex_unlock(&p->pool_m);
return p;
}
/*
* Returns the number of requested threads for a pool.
*/
int hts_tpool_size(hts_tpool *p) {
return p->tsize;
}
/*
* Adds an item to the work pool.
*
* Returns 0 on success
* -1 on failure
*/
int hts_tpool_dispatch(hts_tpool *p, hts_tpool_process *q,
void *(*func)(void *arg), void *arg) {
return hts_tpool_dispatch2(p, q, func, arg, 0);
}
/*
* As above but optional non-block flag.
*
* nonblock 0 => block if input queue is full
* nonblock +1 => don't block if input queue is full, but do not add task
* nonblock -1 => add task regardless of whether queue is full (over-size)
*/
int hts_tpool_dispatch2(hts_tpool *p, hts_tpool_process *q,
void *(*func)(void *arg), void *arg, int nonblock) {
hts_tpool_job *j;
pthread_mutex_lock(&p->pool_m);
DBG_OUT(stderr, "Dispatching job for queue %p, serial %"PRId64"\n",
q, q->curr_serial);
if (q->n_input >= q->qsize && nonblock == 1) {
pthread_mutex_unlock(&p->pool_m);
errno = EAGAIN;
return -1;
}
if (!(j = malloc(sizeof(*j)))) {
pthread_mutex_unlock(&p->pool_m);
return -1;
}
j->func = func;
j->arg = arg;
j->next = NULL;
j->p = p;
j->q = q;
j->serial = q->curr_serial++;
if (nonblock == 0) {
while (q->n_input >= q->qsize && !q->shutdown && !q->wake_dispatch)
pthread_cond_wait(&q->input_not_full_c, &q->p->pool_m);
if (q->shutdown) {
free(j);
pthread_mutex_unlock(&p->pool_m);
return -1;
}
if (q->wake_dispatch) {
//fprintf(stderr, "Wake => non-block for this operation\n");
q->wake_dispatch = 0;
}
}
p->njobs++; // total across all queues
q->n_input++; // queue specific
if (q->input_tail) {
q->input_tail->next = j;
q->input_tail = j;
} else {
q->input_head = q->input_tail = j;
}
DBG_OUT(stderr, "Dispatched (serial %"PRId64")\n", j->serial);
// Let a worker know we have data.
// Keep incoming queue at 1 per running thread, so there is always
// something waiting when they end their current task. If we go above
// this signal to start more threads (if available). This has the effect
// of concentrating jobs to fewer cores when we are I/O bound, which in
// turn benefits systems with auto CPU frequency scaling.
if (!q->shutdown)
wake_next_worker(q, 1);
pthread_mutex_unlock(&p->pool_m);
return 0;
}
/*
* Wakes up a single thread stuck in dispatch and make it return with
* errno EAGAIN.
*/
void hts_tpool_wake_dispatch(hts_tpool_process *q) {
pthread_mutex_lock(&q->p->pool_m);
q->wake_dispatch = 1;
pthread_cond_signal(&q->input_not_full_c);
pthread_mutex_unlock(&q->p->pool_m);
}
/*
* Flushes the process-queue, but doesn't exit. This simply drains the queue
* and ensures all worker threads have finished their current tasks
* associated with this process.
*
* NOT: This does not mean the worker threads are not executing jobs in
* another process-queue.
*
* Returns 0 on success;
* -1 on failure
*/
int hts_tpool_process_flush(hts_tpool_process *q) {
int i;
hts_tpool *p = q->p;
DBG_OUT(stderr, "Flushing pool %p\n", p);
// Drains the queue
pthread_mutex_lock(&p->pool_m);
// Wake up everything for the final sprint!
for (i = 0; i < p->tsize; i++)
if (p->t_stack[i])
pthread_cond_signal(&p->t[i].pending_c);
// Ensure there is room for the final sprint.
// Shouldn't be possible to get here, but just incase.
if (q->qsize < q->n_output + q->n_input + q->n_processing)
q->qsize = q->n_output + q->n_input + q->n_processing;
// Wait for n_input and n_processing to hit zero.
while (q->n_input || q->n_processing) {
while (q->n_input)
pthread_cond_wait(&q->input_empty_c, &p->pool_m);
if (q->shutdown) break;
while (q->n_processing)
pthread_cond_wait(&q->none_processing_c, &p->pool_m);
if (q->shutdown) break;
}
pthread_mutex_unlock(&p->pool_m);
DBG_OUT(stderr, "Flushed complete for pool %p, queue %p\n", p, q);
return 0;
}
/*
* Resets a process to the initial state.
*
* This removes any queued up input jobs, disables any notification of
* new results/output, flushes what is left and then discards any
* queued output. Anything consumer stuck in a wait on results to
* appear should stay stuck and will only wake up when new data is
* pushed through the queue.
*
* Returns 0 on success;
* -1 on failure
*/
int hts_tpool_process_reset(hts_tpool_process *q, int free_results) {
pthread_mutex_lock(&q->p->pool_m);
// prevent next_result from returning data during our flush
q->next_serial = INT_MAX;
// Purge any queued input not yet being acted upon
hts_tpool_job *j, *jn;
for (j = q->input_head; j; j = jn) {
//fprintf(stderr, "Discard input %d\n", j->serial);
jn = j->next;
free(j);
}
q->input_head = q->input_tail = NULL;
q->n_input = 0;
// Purge any queued output, thus ensuring we have room to flush.
hts_tpool_result *r, *rn;
for (r = q->output_head; r; r = rn) {
//fprintf(stderr, "Discard output %d\n", r->serial);
rn = r->next;
hts_tpool_delete_result(r, free_results);
}
q->output_head = q->output_tail = NULL;
q->n_output = 0;
pthread_mutex_unlock(&q->p->pool_m);
// Wait for any jobs being processed to complete.
// (TODO: consider how to cancel any currently processing jobs.
// Probably this is too hard.)
if (hts_tpool_process_flush(q) != 0)
return -1;
// Discard any new output.
pthread_mutex_lock(&q->p->pool_m);
for (r = q->output_head; r; r = rn) {
//fprintf(stderr, "Discard output %d\n", r->serial);
rn = r->next;
hts_tpool_delete_result(r, free_results);
}
q->output_head = q->output_tail = NULL;
q->n_output = 0;
// Finally reset the serial back to the starting point.
q->next_serial = q->curr_serial = 0;
pthread_cond_signal(&q->input_not_full_c);
pthread_mutex_unlock(&q->p->pool_m);
return 0;
}
/* Returns the process queue size */
int hts_tpool_process_qsize(hts_tpool_process *q) {
return q->qsize;
}
/*
* Destroys a thread pool. The threads are joined into the main
* thread so they will finish their current work load.
*/
void hts_tpool_destroy(hts_tpool *p) {
int i;
DBG_OUT(stderr, "Destroying pool %p\n", p);
/* Send shutdown message to worker threads */
pthread_mutex_lock(&p->pool_m);
p->shutdown = 1;
DBG_OUT(stderr, "Sending shutdown request\n");
for (i = 0; i < p->tsize; i++)
pthread_cond_signal(&p->t[i].pending_c);
pthread_mutex_unlock(&p->pool_m);
DBG_OUT(stderr, "Shutdown complete\n");
for (i = 0; i < p->tsize; i++)
pthread_join(p->t[i].tid, NULL);
pthread_mutex_destroy(&p->pool_m);
for (i = 0; i < p->tsize; i++)
pthread_cond_destroy(&p->t[i].pending_c);
if (p->t_stack)
free(p->t_stack);
free(p->t);
free(p);
DBG_OUT(stderr, "Destroyed pool %p\n", p);
}
/*
* Destroys a thread pool without waiting on jobs to complete.
* Use hts_tpool_kill(p) to quickly exit after a fatal error.
*/
void hts_tpool_kill(hts_tpool *p) {
int i;
DBG_OUT(stderr, "Destroying pool %p, kill=%d\n", p, kill);
for (i = 0; i < p->tsize; i++)
pthread_kill(p->t[i].tid, SIGINT);
pthread_mutex_destroy(&p->pool_m);
for (i = 0; i < p->tsize; i++)
pthread_cond_destroy(&p->t[i].pending_c);
if (p->t_stack)
free(p->t_stack);
free(p->t);
free(p);
DBG_OUT(stderr, "Destroyed pool %p\n", p);
}
/*=============================================================================
* Test app.
*
* This can be considered both as a basic test and as a worked example for
* various usage patterns.
*=============================================================================
*/
#ifdef TEST_MAIN
#include <stdio.h>
#ifndef TASK_SIZE
#define TASK_SIZE 1000