-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy paththreadpool.hpp
1336 lines (1155 loc) · 41.2 KB
/
threadpool.hpp
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
// solid/utility/threadpool.hpp
//
// Copyright (c) 2023 Valentin Palade (vipalade @ gmail . com)
//
// This file is part of SolidFrame framework.
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.
//
#pragma once
#include <atomic>
#include <bit>
#include <deque>
#include <functional>
#include <thread>
#include <type_traits>
#if !defined(__cpp_lib_atomic_wait)
#include "solid/utility/atomic_wait"
#endif
#include "solid/system/exception.hpp"
#include "solid/system/log.hpp"
#include "solid/system/spinlock.hpp"
#include "solid/system/statistic.hpp"
#include "solid/utility/common.hpp"
#include "solid/utility/function.hpp"
#include "solid/utility/innerlist.hpp"
namespace solid {
struct ThreadPoolStatistic : solid::Statistic {
std::atomic_uint_fast64_t create_context_count_ = {0};
std::atomic_uint_fast64_t delete_context_count_ = {0};
std::atomic_uint_fast64_t run_one_free_count_ = {0};
std::atomic_uint_fast64_t max_run_one_free_count_ = {0};
std::atomic_uint_fast64_t run_one_context_count_ = {0};
std::atomic_uint_fast64_t max_run_one_context_count_ = {0};
std::atomic_uint_fast64_t run_one_push_count_ = {0};
std::atomic_uint_fast64_t max_run_one_push_count_ = {0};
std::atomic_uint_fast64_t run_all_wake_count_ = {0};
std::atomic_uint_fast64_t max_run_all_wake_count_ = {0};
std::atomic_uint_fast64_t push_one_count_[2];
std::atomic_uint_fast64_t push_all_count_ = {0};
std::atomic_uint_fast64_t push_all_wake_count_ = {0};
std::atomic_uint_fast64_t max_consume_all_count_ = {0};
std::atomic_uint_fast64_t run_all_count_ = {0};
std::atomic_uint_fast64_t max_run_all_count_ = {0};
std::atomic_uint_fast64_t push_one_wait_lock_count_ = {0};
std::atomic_uint_fast64_t push_one_wait_pushing_count_ = {0};
std::atomic_uint_fast64_t pop_one_wait_lock_count_ = {0};
std::atomic_uint_fast64_t pop_one_wait_popping_count_ = {0};
std::atomic_uint_fast64_t push_all_wait_lock_count_ = {0};
std::atomic_uint_fast64_t push_all_wait_pushing_count_ = {0};
std::atomic_uint_fast64_t push_one_latency_min_us_ = {0};
std::atomic_uint_fast64_t push_one_latency_max_us_ = {0};
std::atomic_uint_fast64_t push_one_latency_sum_us_ = {0};
ThreadPoolStatistic();
void createContext()
{
++create_context_count_;
}
void deleteContext()
{
++delete_context_count_;
}
void runOneFreeCount(const uint64_t _count)
{
++run_one_free_count_;
solid_statistic_max(max_run_one_free_count_, _count);
}
void runOneContextPush(const uint64_t _count)
{
++run_one_push_count_;
solid_statistic_max(max_run_one_push_count_, _count);
}
void runOneContextCount(const uint64_t _inc, const uint64_t _count)
{
run_one_context_count_ += _inc;
solid_statistic_max(max_run_one_context_count_, _count);
}
void runWakeCount(const uint64_t _count)
{
++run_all_wake_count_;
solid_statistic_max(max_run_all_wake_count_, _count);
}
void tryConsumeAnAllTaskFilled(const bool _should_retry, const uint64_t _count)
{
++run_all_count_;
solid_statistic_max(max_run_all_count_, _count);
}
void tryConsumeAnAllTaskNotFilled(const bool _should_retry)
{
}
void consumeAll(const uint64_t _count)
{
solid_statistic_max(max_consume_all_count_, _count);
}
void pushOne(const bool _with_context, const uint64_t _duration_us)
{
++push_one_count_[_with_context];
solid_statistic_min(push_one_latency_min_us_, _duration_us);
solid_statistic_max(push_one_latency_max_us_, _duration_us);
push_one_latency_sum_us_ += _duration_us;
}
void pushAll(const bool _should_wake)
{
++push_all_count_;
}
void pushOneWaitLock()
{
++push_one_wait_lock_count_;
}
void pushOneWaitPushing()
{
++push_one_wait_pushing_count_;
}
void popOneWaitLock()
{
++pop_one_wait_lock_count_;
}
void popOneWaitPopping()
{
++pop_one_wait_popping_count_;
}
void pushAllWaitLock()
{
++push_all_wait_lock_count_;
}
void pushAllWaitPushing()
{
++push_all_wait_pushing_count_;
}
std::ostream& print(std::ostream& _ros) const override;
void clear();
};
struct EmptyThreadPoolStatistic : solid::Statistic {
void createContext() {}
void deleteContext() {}
void runOneFreeCount(const uint64_t _count) {}
void runOneContextPush(const uint64_t _count) {}
void runOneContextCount(const uint64_t _inc, const uint64_t _count) {}
void runWakeCount(const uint64_t _count) {}
void tryConsumeAnAllTaskFilled(const bool _should_retry, const uint64_t _count) {}
void tryConsumeAnAllTaskNotFilled(const bool _should_retry) {}
void consumeAll(const uint64_t _count) {}
void pushOne(const bool _with_context, const uint64_t _duration_us) {}
void pushAll(const bool _should_wake) {}
void pushOneWaitLock() {}
void pushOneWaitPushing() {}
void popOneWaitLock() {}
void popOneWaitPopping() {}
void pushAllWaitLock() {}
void pushAllWaitPushing() {}
std::ostream& print(std::ostream& _ros) const override { return _ros; }
void clear() {}
};
struct ThreadPoolConfiguration {
static constexpr size_t default_one_capacity = 8 * 1024;
static constexpr size_t default_all_capacity = 1024;
size_t thread_count_ = 1;
size_t one_capacity_ = default_one_capacity;
size_t all_capacity_ = default_all_capacity;
size_t spin_count_ = 1;
ThreadPoolConfiguration(
const size_t _thread_count = 1,
const size_t _one_capacity = 10 * 1024,
const size_t _all_capacity = 1024,
const size_t _spin_count = 1)
: thread_count_(_thread_count)
, one_capacity_(_one_capacity)
, all_capacity_(_all_capacity)
, spin_count_(_spin_count)
{
}
auto& threadCount(const size_t _value)
{
thread_count_ = _value;
return *this;
}
auto& oneCapacity(const size_t _value)
{
one_capacity_ = _value;
return *this;
}
auto& allCapacity(const size_t _value)
{
all_capacity_ = _value;
return *this;
}
auto& spinCount(const size_t _value)
{
spin_count_ = _value;
return *this;
}
};
template <class TaskOne, class TaskAll, class Stats = ThreadPoolStatistic>
class ThreadPool;
template <class TP, class ContextStub>
class SynchronizationContext {
TP* pthread_pool_ = nullptr;
ContextStub* pcontext_ = nullptr;
template <class TaskOne, class TaskAll, class Stats>
friend class ThreadPool;
SynchronizationContext(TP* _pthread_pool, ContextStub* _pcontext)
: pthread_pool_(_pthread_pool)
, pcontext_(_pcontext)
{
}
public:
SynchronizationContext() {}
SynchronizationContext(const SynchronizationContext& _other) = delete;
SynchronizationContext(SynchronizationContext&& _other) noexcept
: pthread_pool_(_other.pthread_pool_)
, pcontext_(_other.pcontext_)
{
_other.pthread_pool_ = nullptr;
_other.pcontext_ = nullptr;
}
~SynchronizationContext()
{
clear();
}
SynchronizationContext& operator=(const SynchronizationContext& _other) = delete;
SynchronizationContext& operator=(SynchronizationContext&& _other) noexcept
{
if (this != &_other) {
clear();
pthread_pool_ = _other.pthread_pool_;
pcontext_ = _other.pcontext_;
_other.pcontext_ = nullptr;
_other.pcontext_ = nullptr;
}
return *this;
}
void clear()
{
if (!empty()) {
pthread_pool_->release(pcontext_);
pcontext_ = nullptr;
pthread_pool_ = nullptr;
}
}
bool empty() const
{
return pthread_pool_ == nullptr;
}
template <class Task>
void push(Task&& _task)
{
solid_check(!empty());
pthread_pool_->impl_.doPushOne(std::forward<Task>(_task), pcontext_);
}
};
namespace tpimpl {
template <typename T>
typename std::decay<T>::type decay_copy(T&& v)
{
return std::forward<T>(v);
}
template <class Task>
class alignas(hardware_destructive_interference_size) TaskData {
std::aligned_storage_t<sizeof(Task), alignof(Task)> data_;
public:
Task& task() noexcept
{
return *std::launder(reinterpret_cast<Task*>(&data_));
}
template <class T>
void task(T&& _rt)
{
::new (&data_) Task(std::forward<T>(_rt));
}
void destroy()
{
std::destroy_at(std::launder(reinterpret_cast<Task*>(&data_)));
}
};
template <class Task>
class TaskList {
enum {
InnerLinkOrder = 0,
InnerLinkFree = 0,
InnerLinkCount
};
struct TaskNode : TaskData<Task>, inner::Node<InnerLinkCount> {
uint64_t id_ = 0;
uint64_t all_id_ = 0;
};
using TaskDqT = std::deque<TaskNode>;
using OrderListT = inner::List<TaskDqT, InnerLinkOrder>;
using FreeListT = inner::List<TaskDqT, InnerLinkFree>;
TaskDqT tasks_;
OrderListT order_tasks_;
FreeListT free_tasks_;
public:
TaskList()
: order_tasks_(tasks_)
, free_tasks_(tasks_)
{
}
void push(Task&& _task, const uint64_t _all_id, const uint64_t _id)
{
size_t index = InvalidIndex{};
if (!free_tasks_.empty()) {
index = free_tasks_.backIndex();
free_tasks_.popBack();
} else {
index = tasks_.size();
tasks_.emplace_back();
}
auto& rnode = tasks_[index];
rnode.id_ = _id;
rnode.all_id_ = _all_id;
rnode.task(std::move(_task));
if (order_tasks_.empty()) {
order_tasks_.pushBack(index);
} else {
auto tmp_index = order_tasks_.backIndex();
while (tmp_index != InvalidIndex() && overflow_safe_less(_id, tasks_[tmp_index].id_)) {
tmp_index = order_tasks_.previousIndex(tmp_index);
}
if (tmp_index != InvalidIndex()) {
order_tasks_.insertAfter(tmp_index, index);
} else {
order_tasks_.pushFront(index);
}
}
}
bool pop(TaskData<Task>& _task_data, uint64_t& _rall_id, const uint64_t _id)
{
if (!order_tasks_.empty() && order_tasks_.front().id_ == _id) {
_task_data.task(std::move(order_tasks_.front().task()));
_rall_id = order_tasks_.front().all_id_;
order_tasks_.front().destroy();
free_tasks_.pushBack(order_tasks_.popFront());
return true;
}
return false;
}
};
struct LocalContext {
uint64_t next_all_id_ = 1;
uint64_t all_count_ = 0;
uint64_t one_free_count_ = 0;
uint64_t one_context_count_ = 0;
uint64_t one_context_push_count_ = 0;
uint64_t wake_count_ = 0;
};
/*
NOTE:
Because we want to execute each TaskOne within the exact TaskAll context
acquired at pushOne, we cannot notify the Threads on pushAll.
In case multiple TaskAll were pushed and after that we have a TaskOne,
the processing will get delayed because we need to build the All context by
running all the TaskAll.
*/
template <class TaskOne, class TaskAll, class Stats>
class ThreadPool : NonCopyable {
public:
static constexpr size_t spin_count = 10;
struct ContextStub {
using TaskQueueT = TaskList<TaskOne>;
std::atomic_size_t use_count_{1};
std::atomic_uint_fast64_t produce_id_{0};
SpinLock spin_;
TaskQueueT task_q_;
alignas(hardware_destructive_interference_size) std::atomic_uint_fast64_t consume_id_{0};
void acquire()
{
++use_count_;
}
bool release()
{
return use_count_.fetch_sub(1) == 1;
}
void push(TaskOne&& _task, const uint64_t _all_id, const uint64_t _consume_id)
{
task_q_.push(std::move(_task), _all_id, _consume_id);
}
bool pop(TaskData<TaskOne>& _task_data, uint64_t& _rall_id, const uint64_t _consume_id)
{
return task_q_.pop(_task_data, _rall_id, _consume_id);
}
};
private:
enum struct EventE : uint8_t {
Fill,
Stop,
Wake,
};
using AtomicCounterT = std::atomic<uint8_t>;
using AtomicCounterValueT = AtomicCounterT::value_type;
template <class IndexT>
inline constexpr static auto computeCounter(const IndexT _index, const size_t _capacity) noexcept
{
return (_index / _capacity) & std::numeric_limits<AtomicCounterValueT>::max();
}
struct OneStub {
AtomicCounterT produce_count_{0};
AtomicCounterT consume_count_{std::numeric_limits<AtomicCounterValueT>::max()};
std::uint8_t event_ = {to_underlying(EventE::Fill)};
TaskData<TaskOne>* data_ptr_ = nullptr;
ContextStub* pcontext_ = nullptr;
uint64_t all_id_ = 0;
uint64_t context_produce_id_ = 0;
auto& task() noexcept
{
return data_ptr_->task();
}
template <class T>
void task(T&& _rt)
{
data_ptr_->task(std::forward<T>(_rt));
}
void destroy()
{
data_ptr_->destroy();
}
void clear() noexcept
{
pcontext_ = nullptr;
all_id_ = 0;
context_produce_id_ = 0;
}
void waitWhilePushOne(Stats& _rstats, const AtomicCounterValueT _count, const size_t _spin_count) noexcept
{
auto spin = _spin_count;
while (true) {
const auto cnt = produce_count_.load();
if (cnt == _count) {
break;
} else if (_spin_count && !spin--) {
_rstats.pushOneWaitLock();
std::atomic_wait_explicit(&produce_count_, cnt, std::memory_order_relaxed);
spin = _spin_count;
}
}
}
void notifyWhilePushOne(std::chrono::time_point<std::chrono::steady_clock> const& _start, uint64_t& _rduration) noexcept
{
using namespace std::chrono;
event_ = to_underlying(EventE::Fill);
++consume_count_;
std::atomic_notify_all(&consume_count_);
_rduration = duration_cast<microseconds>(steady_clock::now() - _start).count();
}
void waitWhileStop(Stats& _rstats, const AtomicCounterValueT _count, const size_t _spin_count) noexcept
{
waitWhilePushOne(_rstats, _count, _spin_count);
}
void waitWhilePushAll(Stats& _rstats, const AtomicCounterValueT _count, const size_t _spin_count) noexcept
{
waitWhilePushOne(_rstats, _count, _spin_count);
}
void notifyWhileStop() noexcept
{
event_ = to_underlying(EventE::Stop);
++consume_count_;
std::atomic_notify_all(&consume_count_);
}
void notifyWhilePushAll() noexcept
{
event_ = to_underlying(EventE::Wake);
++consume_count_;
std::atomic_notify_all(&consume_count_);
}
template <
class Fnc,
class AllFnc,
typename... Args>
EventE waitWhilePop(Stats& _rstats, const AtomicCounterValueT _count, const size_t _spin_count, const Fnc& _try_consume_an_all_fnc, AllFnc& _all_fnc, Args&&... _args) noexcept
{
auto spin = _spin_count;
while (true) {
const auto cnt = consume_count_.load();
if (cnt == _count) {
return static_cast<EventE>(event_);
} else if (!_try_consume_an_all_fnc(&consume_count_, _count, _all_fnc, _args...) && _spin_count && !spin--) {
// std::atomic_wait_explicit(&consume_count_, cnt, std::memory_order_relaxed);
std::atomic_wait(&consume_count_, cnt);
_rstats.popOneWaitPopping();
spin = _spin_count;
}
}
}
void notifyWhilePop() noexcept
{
++produce_count_;
std::atomic_notify_all(&produce_count_);
}
};
struct AllStub {
AtomicCounterT produce_count_{0};
AtomicCounterT consume_count_{std::numeric_limits<AtomicCounterValueT>::max()};
std::atomic_uint32_t use_count_ = {0};
std::atomic_uint64_t id_ = {0};
TaskData<TaskAll>* data_ptr_ = nullptr;
auto& task() noexcept
{
return data_ptr_->task();
}
template <class T>
void task(T&& _rt)
{
data_ptr_->task(std::forward<T>(_rt));
}
void destroy()
{
data_ptr_->destroy();
}
void waitWhilePushAll(Stats& _rstats, const AtomicCounterValueT _count, const size_t _spin_count) noexcept
{
auto spin = _spin_count;
while (true) {
const auto cnt = produce_count_.load();
if (cnt == _count) {
break;
} else if (_spin_count && !spin--) {
_rstats.pushOneWaitLock();
// std::atomic_wait_explicit(&produce_count_, cnt, std::memory_order_relaxed);
std::atomic_wait(&produce_count_, cnt);
spin = _spin_count;
}
}
}
void notifyWhilePushAll(const uint32_t _thread_count, const uint64_t _id) noexcept
{
use_count_.store(_thread_count);
id_.store(_id);
++consume_count_;
}
bool notifyWhilePop() noexcept
{
if (use_count_.fetch_sub(1) == 1) {
destroy();
++produce_count_;
std::atomic_notify_all(&produce_count_);
return true;
}
return false;
}
bool isFilled(const uint64_t _id, const size_t _capacity) const
{
const auto count = consume_count_.load();
const AtomicCounterValueT expected_count = computeCounter(_id, _capacity);
return count == expected_count && id_.load() == _id;
}
};
using AllStubT = AllStub;
using OneStubT = OneStub;
using ThreadVectorT = std::vector<std::thread>;
size_t spin_count_ = 1;
/* alignas(hardware_constructive_interference_size) */ struct {
size_t capacity_{0};
std::unique_ptr<OneStubT[]> tasks_;
std::unique_ptr<TaskData<TaskOne>[]> datas_;
} one_;
/* alignas(hardware_constructive_interference_size) */ struct {
size_t capacity_{0};
std::atomic_size_t pending_count_{0};
std::atomic_uint_fast64_t push_index_{1};
std::atomic_uint_fast64_t commited_index_{0};
std::unique_ptr<AllStubT[]> tasks_;
std::unique_ptr<TaskData<TaskAll>[]> datas_;
} all_;
Stats statistic_;
using AtomicIndexT = std::atomic_size_t;
using AtomicIndexValueT = std::atomic_size_t::value_type;
alignas(hardware_destructive_interference_size * 2) AtomicIndexT push_one_index_{0};
alignas(hardware_destructive_interference_size * 2) AtomicIndexT pop_one_index_{0};
ThreadVectorT threads_;
std::atomic<bool> running_{false};
std::tuple<AtomicIndexValueT, AtomicCounterValueT> pushOneIndex() noexcept
{
const auto index = push_one_index_.fetch_add(1);
return {index % one_.capacity_, computeCounter(index, one_.capacity_)};
}
std::tuple<AtomicIndexValueT, AtomicCounterValueT> popOneIndex() noexcept
{
const auto index = pop_one_index_.fetch_add(1);
return {index % one_.capacity_, computeCounter(index, one_.capacity_)};
}
auto pushAllId() noexcept
{
return all_.push_index_.fetch_add(1);
}
void commitAllId(const uint64_t _id)
{
uint64_t id = _id - 1;
while (!all_.commited_index_.compare_exchange_weak(id, _id)) {
id = _id - 1;
cpu_pause();
}
}
public:
ThreadPool() = default;
template <
class StartFnc,
class StopFnc,
class OneFnc,
class AllFnc,
typename... Args>
void doStart(
const ThreadPoolConfiguration& _config,
StartFnc _start_fnc,
StopFnc _stop_fnc,
OneFnc _one_fnc,
AllFnc _all_fnc,
Args&&... _args);
void doStop();
template <class Tsk>
void doPushOne(Tsk&& _task, ContextStub* _pctx);
template <class Tsk>
void doPushAll(Tsk&& _task);
const Stats& statistic() const
{
return statistic_;
}
void clearStatistic()
{
statistic_.clear();
}
void release(ContextStub* _pctx)
{
if (_pctx) {
if (_pctx->release()) {
statistic_.deleteContext();
delete _pctx;
}
}
}
ContextStub* doCreateContext();
size_t capacityOne() const
{
return one_.capacity_;
}
size_t capacityAll() const
{
return all_.capacity_;
}
private:
template <
class OneFnc,
class AllFnc,
typename... Args>
void doRun(
const size_t _thread_index,
OneFnc& _one_fnc,
AllFnc& _all_fnc,
Args&&... _args);
template <
class AllFnc,
typename... Args>
bool tryConsumeAnAllTask(AtomicCounterT* _pcounter,
const AtomicCounterValueT _count, LocalContext& _rlocal_context, AllFnc& _all_fnc, Args&&... _args);
template <
class AllFnc,
typename... Args>
void consumeAll(LocalContext& _rlocal_context, const uint64_t _all_id, AllFnc& _all_fnc, Args&&... _args);
};
} // namespace tpimpl
template <class TaskOne, class TaskAll, class Stats>
class ThreadPool {
template <class TP, class ContextStub>
friend class SynchronizationContext;
using ImplT = tpimpl::ThreadPool<TaskOne, TaskAll, Stats>;
using ThisT = ThreadPool<TaskOne, TaskAll, Stats>;
ImplT impl_;
public:
using SynchronizationContextT = SynchronizationContext<ThisT, typename ImplT::ContextStub>;
using ConfigurationT = ThreadPoolConfiguration;
ThreadPool() = default;
template <
class StartFnc,
class StopFnc,
class OneFnc,
class AllFnc,
typename... Args>
ThreadPool(
const ThreadPoolConfiguration& _config,
StartFnc _start_fnc,
StopFnc _stop_fnc,
OneFnc _one_fnc,
AllFnc _all_fnc,
Args&&... _args)
{
impl_.doStart(
_config,
_start_fnc,
_stop_fnc,
_one_fnc,
_all_fnc,
std::forward<Args>(_args)...);
}
template <
class StartFnc,
class StopFnc,
class OneFnc,
class AllFnc,
typename... Args>
void start(
const ThreadPoolConfiguration& _config,
StartFnc _start_fnc,
StopFnc _stop_fnc,
OneFnc _one_fnc,
AllFnc _all_fnc,
Args&&... _args)
{
impl_.doStart(
_config,
_start_fnc,
_stop_fnc,
_one_fnc,
_all_fnc,
std::forward<Args>(_args)...);
}
void stop()
{
impl_.doStop();
}
~ThreadPool()
{
impl_.doStop();
}
SynchronizationContextT createSynchronizationContext()
{
return SynchronizationContextT{this, impl_.doCreateContext()};
}
const Stats& statistic() const
{
return impl_.statistic();
}
void clearStatistic()
{
impl_.clearStatistic();
}
template <class Tsk>
void pushOne(Tsk&& _task)
{
impl_.doPushOne(std::forward<Tsk>(_task), nullptr);
}
template <class Tsk>
void pushAll(Tsk&& _task)
{
impl_.doPushAll(std::forward<Tsk>(_task));
}
size_t capacityOne() const
{
return impl_.capacityOne();
}
size_t capacityAll() const
{
return impl_.capacityAll();
}
private:
void release(typename ImplT::ContextStub* _pctx)
{
impl_.release(_pctx);
}
};
template <class... ArgTypes, size_t OneFunctionDataSize, size_t AllFunctionDataSize, class Stats>
class ThreadPool<Function<void(ArgTypes...), OneFunctionDataSize>, Function<void(ArgTypes...), AllFunctionDataSize>, Stats> {
template <class TP, class ContextStub>
friend class SynchronizationContext;
using OneFunctionT = Function<void(ArgTypes...), OneFunctionDataSize>;
using AllFunctionT = Function<void(ArgTypes...), AllFunctionDataSize>;
using ImplT = tpimpl::ThreadPool<OneFunctionT, AllFunctionT, Stats>;
using ThisT = ThreadPool<OneFunctionT, AllFunctionT, Stats>;
ImplT impl_;
public:
using SynchronizationContextT = SynchronizationContext<ThisT, typename ImplT::ContextStub>;
using ConfigurationT = ThreadPoolConfiguration;
template <class T>
static constexpr bool is_small_one_type()
{
return OneFunctionT::template is_small_type<T>();
}
template <class T>
static constexpr bool is_small_all_type()
{
return AllFunctionT::template is_small_type<T>();
}
ThreadPool() = default;
template <class StartFnc,
class StopFnc, typename... Args>
ThreadPool(
const ThreadPoolConfiguration& _config,
StartFnc _start_fnc,
StopFnc _stop_fnc,
Args&&... _args)
{
impl_.doStart(
_config,
_start_fnc,
_stop_fnc,
[]<typename... ArgsB>(OneFunctionT& _rfnc, ArgsB&&... _argsb) {
_rfnc(_argsb...);
_rfnc.reset();
},
[]<typename... ArgsB>(AllFunctionT& _rfnc, ArgsB&&... _argsb) {
_rfnc(_argsb...);
},
std::forward<Args>(_args)...);
}
template <class StartFnc,
class StopFnc, typename... Args>
void start(const ThreadPoolConfiguration& _config,
StartFnc _start_fnc,
StopFnc _stop_fnc,
Args... _args)
{
impl_.doStart(
_config,
_start_fnc,
_stop_fnc,
[]<typename... ArgsB>(OneFunctionT& _rfnc, ArgsB&&... _argsb) {
_rfnc(_argsb...);
_rfnc.reset();
},
[]<typename... ArgsB>(AllFunctionT& _rfnc, ArgsB&&... _argsb) {
_rfnc(_argsb...);
},
std::forward<Args>(_args)...);
}
void stop()
{
impl_.doStop();
}
~ThreadPool()
{
impl_.doStop();
}
SynchronizationContextT createSynchronizationContext()
{
return SynchronizationContextT{this, impl_.doCreateContext()};
}
const Stats& statistic() const
{
return impl_.statistic();
}
void clearStatistic()
{
impl_.clearStatistic();
}
template <class Tsk>
void pushOne(Tsk&& _task)
{
impl_.doPushOne(std::forward<Tsk>(_task), nullptr);
}
template <class Tsk>
void pushAll(Tsk&& _task)
{
impl_.doPushAll(std::forward<Tsk>(_task));
}
size_t capacityOne() const
{
return impl_.capacityOne();
}
size_t capacityAll() const
{
return impl_.capacityAll();
}
private:
void release(typename ImplT::ContextStub* _pctx)
{
impl_.release(_pctx);
}
};
namespace tpimpl {
//-----------------------------------------------------------------------------
template <class TaskOne, class TaskAll, class Stats>
template <
class StartFnc,
class StopFnc,
class OneFnc,
class AllFnc,