forked from grame-cncm/faust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscheduler.cpp
1391 lines (1133 loc) · 38.2 KB
/
scheduler.cpp
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
/************************************************************************
FAUST Architecture File
Copyright (C) 2010-2012 GRAME, Centre National de Creation Musicale
---------------------------------------------------------------------
This Architecture section is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; If not, see <http://www.gnu.org/licenses/>.
EXCEPTION : As a special exception, you may create a larger work
that contains this FAUST architecture section and distribute
that work under terms of your choice, so long as this FAUST
architecture section is not modified.
************************************************************************
************************************************************************/
#include <stdlib.h>
#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <math.h>
// For AVOIDDENORMALS
#include "faust/dsp/dsp.h"
#ifdef __cplusplus
extern "C" {
#endif
// Globals
static int GetPID()
{
#ifdef WIN32
return _getpid();
#else
return getpid();
#endif
}
#define WORK_STEALING_INDEX 0
#define LAST_TASK_INDEX 1
#define MASTER_THREAD 0
#define MAX_STEAL_DUR 50 // in usec
#define DEFAULT_CLOCKS_PER_SEC 2500000000 // in cycles (2,5 Ghz)
#define JACK_SCHED_POLICY SCHED_FIFO
#define KDSPMESURE 50
#define MEAN_TRESHOLD 0.1f // in percentage
#ifdef __ICC
#define INLINE __forceinline
#else
#define INLINE inline
#endif
#ifdef __linux__
// handle 32/64 bits int size issues
#ifdef __x86_64__
#define UInt32 unsigned int
#define UInt64 unsigned long int
#else
#define UInt32 unsigned int
#define UInt64 unsigned long long int
#endif
#endif
#ifdef __APPLE__
#include <mach/mach.h>
#elif defined(_WIN32)
#include <windows.h>
#else
#include <semaphore.h>
#include <errno.h>
#endif
/*
Copyright (C) 2012 Paul Davis
Author: David Robillard
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
static int GetPID()
{
#ifdef WIN32
return _getpid();
#else
return getpid();
#endif
}
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/**
Unnamed (process local) counting semaphore.
The civilized person's synchronisation primitive. A counting semaphore is
an integer which is always non-negative, so, an attempted decrement (or
"wait") will block if the value is 0, until another thread does an increment
(or "post").
At least on Lignux, the main advantage of this is that it is fast and the
only safe way to reliably signal from a real-time audio thread. The
counting semantics also complement ringbuffers of events nicely.
*/
class Semaphore
{
public:
/**
Create a new semaphore.
Chances are you want 1 wait() per 1 post(), an initial value of 0.
*/
inline Semaphore(unsigned initial);
inline ~Semaphore();
/** Post/Increment/Signal */
inline void post();
/** Wait/Decrement. Returns false on error. */
inline bool wait();
/** Attempt Wait/Decrement. Returns true iff a decrement occurred. */
inline bool try_wait();
private:
#if defined(__APPLE__)
semaphore_t _sem; // sem_t is a worthless broken mess on OSX
#elif defined(_WIN32)
HANDLE _sem; // types are overrated anyway
#else
char fName[128];
sem_t* _sem;
#endif
};
#ifdef __APPLE__
inline Semaphore::Semaphore(unsigned initial)
{
if (semaphore_create(mach_task_self(), &_sem, SYNC_POLICY_FIFO, initial)) {
throw -1;
}
}
inline Semaphore::~Semaphore()
{
semaphore_destroy(mach_task_self(), _sem);
}
inline void Semaphore::post()
{
semaphore_signal(_sem);
}
inline bool Semaphore::wait()
{
if (semaphore_wait(_sem) != KERN_SUCCESS) {
return false;
}
return true;
}
inline bool Semaphore::try_wait()
{
const mach_timespec_t zero = { 0, 0 };
return semaphore_timedwait(_sem, zero) == KERN_SUCCESS;
}
#elif defined(_WIN32)
inline Semaphore::Semaphore(unsigned initial)
{
if (!(_sem = CreateSemaphore(NULL, initial, LONG_MAX, NULL))) {
throw -1;
}
}
inline Semaphore::~Semaphore()
{
CloseHandle(_sem);
}
inline void Semaphore::post()
{
ReleaseSemaphore(_sem, 1, NULL);
}
inline bool Semaphore::wait()
{
if (WaitForSingleObject(_sem, INFINITE) != WAIT_OBJECT_0) {
return false;
}
return true;
}
inline bool Semaphore::try_wait()
{
return WaitForSingleObject(_sem, 0) == WAIT_OBJECT_0;
}
#else /* !defined(__APPLE__) && !defined(_WIN32) */
Semaphore::Semaphore(unsigned initial)
{
sprintf(fName, "faust_sem_%d_%p", GetPID(), this);
if ((_sem = sem_open(fName, O_CREAT, 0777, 0)) == (sem_t*)SEM_FAILED) {
printf("Allocate: can't check in named semaphore name = %s err = %s", fName, strerror(errno));
throw -1;
}
}
inline Semaphore::~Semaphore()
{
sem_unlink(fName);
sem_close(_sem);
}
inline void Semaphore::post()
{
sem_post(_sem);
}
inline bool Semaphore::wait()
{
while (sem_wait(_sem)) {
if (errno != EINTR) {
return false; // We are all doomed
}
// Otherwise, interrupted (rare/weird), so try again.
}
return true;
}
inline bool Semaphore::try_wait()
{
return (sem_trywait(_sem) == 0);
}
#endif
#ifdef __APPLE__
//#include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacTypes.h>
#include <MacTypes.h>
#include <libkern/OSAtomic.h>
#endif
static void Yield();
/**
* Returns the number of clock cycles elapsed since the last reset
* of the processor
*/
static INLINE UInt64 DSP_rdtsc(void)
{
union {
UInt32 i32[2];
UInt64 i64;
} count;
__asm__ __volatile__("rdtsc" : "=a" (count.i32[0]), "=d" (count.i32[1]));
return count.i64;
}
#if defined(__i386__) || defined(__x86_64__)
#define LOCK "lock ; "
static INLINE void NOP(void)
{
/*
#ifndef __APPLE__
__asm__ __volatile__("nop \n\t");
#endif
*/
}
static INLINE char CAS1(volatile void* addr, volatile int value, int newvalue)
{
return __sync_bool_compare_and_swap((int*)addr, value, newvalue);
}
static INLINE int atomic_xadd(volatile int* atomic, int val)
{
return __sync_add_and_fetch(atomic, val);
}
#endif
/*
static INLINE int INC_ATOMIC(volatile int* val)
{
int actual;
do {
actual = *val;
} while (!CAS1(val, actual, actual + 1));
return actual;
}
static INLINE int DEC_ATOMIC(volatile int* val)
{
int actual;
do {
actual = *val;
} while (!CAS1(val, actual, actual - 1));
return actual;
}
*/
static INLINE int INC_ATOMIC(volatile int* val)
{
return atomic_xadd(val, 1);
}
static INLINE int DEC_ATOMIC(volatile int* val)
{
return atomic_xadd(val, -1);
}
// To be used in lock-free queue
struct AtomicCounter
{
union {
struct {
short fHead;
short fTail;
} scounter;
int fValue;
} info;
INLINE AtomicCounter()
{
info.fValue = 0;
}
INLINE AtomicCounter& operator=(AtomicCounter& obj)
{
info.fValue = obj.info.fValue;
return *this;
}
INLINE AtomicCounter& operator=(volatile AtomicCounter& obj)
{
info.fValue = obj.info.fValue;
return *this;
}
};
/* use 512KB stack per thread - the default is way too high to be feasible
* with mlockall() on many systems */
#define THREAD_STACK 524288
#ifdef __APPLE__
#include <mach/thread_policy.h>
#include <mach/thread_act.h>
#include <mach/mach_time.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#define THREAD_SET_PRIORITY 0
#define THREAD_SCHEDULED_PRIORITY 1
static void get_affinity(pthread_t thread)
{
thread_affinity_policy theTCPolicy;
mach_msg_type_number_t count = THREAD_AFFINITY_POLICY_COUNT;
boolean_t get_default = false;
kern_return_t res = thread_policy_get(pthread_mach_thread_np(thread), THREAD_AFFINITY_POLICY, (thread_policy_t)&theTCPolicy, &count, &get_default);
if (res == KERN_SUCCESS) {
//printf("get_affinity = %d\n", theTCPolicy.affinity_tag);
}
}
static void set_affinity(pthread_t thread, int tag)
{
thread_affinity_policy theTCPolicy;
theTCPolicy.affinity_tag = tag;
kern_return_t res = thread_policy_set(pthread_mach_thread_np(thread), THREAD_AFFINITY_POLICY, (thread_policy_t)&theTCPolicy, THREAD_AFFINITY_POLICY_COUNT);
if (res == KERN_SUCCESS) {
//printf("set_affinity = %d\n", theTCPolicy.affinity_tag);
}
}
static UInt32 GetThreadPriority(pthread_t thread, int inWhichPriority);
// returns the thread's priority as it was last set by the API
static UInt32 GetThreadSetPriority(pthread_t thread)
{
return GetThreadPriority(thread, THREAD_SET_PRIORITY);
}
// returns the thread's priority as it was last scheduled by the Kernel
static UInt32 GetThreadScheduledPriority(pthread_t thread)
{
return GetThreadPriority(thread, THREAD_SCHEDULED_PRIORITY);
}
static int SetThreadToPriority(pthread_t thread, UInt32 inPriority, Boolean inIsFixed, UInt64 period, UInt64 computation, UInt64 constraint)
{
if (inPriority == 96) {
// REAL-TIME / TIME-CONSTRAINT THREAD
thread_time_constraint_policy_data_t theTCPolicy;
theTCPolicy.period = period;
theTCPolicy.computation = computation;
theTCPolicy.constraint = constraint;
theTCPolicy.preemptible = true;
kern_return_t res = thread_policy_set(pthread_mach_thread_np(thread), THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&theTCPolicy, THREAD_TIME_CONSTRAINT_POLICY_COUNT);
return (res == KERN_SUCCESS) ? 0 : -1;
} else {
// OTHER THREADS
thread_extended_policy_data_t theFixedPolicy;
thread_precedence_policy_data_t thePrecedencePolicy;
SInt32 relativePriority;
// [1] SET FIXED / NOT FIXED
theFixedPolicy.timeshare = !inIsFixed;
thread_policy_set(pthread_mach_thread_np(thread), THREAD_EXTENDED_POLICY, (thread_policy_t)&theFixedPolicy, THREAD_EXTENDED_POLICY_COUNT);
// [2] SET PRECEDENCE
// N.B.: We expect that if thread A created thread B, and the program wishes to change
// the priority of thread B, then the call to change the priority of thread B must be
// made by thread A.
// This assumption allows us to use pthread_self() to correctly calculate the priority
// of the feeder thread (since precedency policy's importance is relative to the
// spawning thread's priority.)
relativePriority = inPriority - GetThreadSetPriority(pthread_self());
thePrecedencePolicy.importance = relativePriority;
kern_return_t res = thread_policy_set(pthread_mach_thread_np(thread), THREAD_PRECEDENCE_POLICY, (thread_policy_t)&thePrecedencePolicy, THREAD_PRECEDENCE_POLICY_COUNT);
return (res == KERN_SUCCESS) ? 0 : -1;
}
}
static UInt32 GetThreadPriority(pthread_t thread, int inWhichPriority)
{
thread_basic_info_data_t threadInfo;
policy_info_data_t thePolicyInfo;
unsigned int count;
// get basic info
count = THREAD_BASIC_INFO_COUNT;
thread_info(pthread_mach_thread_np(thread), THREAD_BASIC_INFO, (thread_info_t)&threadInfo, &count);
switch (threadInfo.policy) {
case POLICY_TIMESHARE:
count = POLICY_TIMESHARE_INFO_COUNT;
thread_info(pthread_mach_thread_np(thread), THREAD_SCHED_TIMESHARE_INFO, (thread_info_t)&(thePolicyInfo.ts), &count);
if (inWhichPriority == THREAD_SCHEDULED_PRIORITY) {
return thePolicyInfo.ts.cur_priority;
} else {
return thePolicyInfo.ts.base_priority;
}
break;
case POLICY_FIFO:
count = POLICY_FIFO_INFO_COUNT;
thread_info(pthread_mach_thread_np(thread), THREAD_SCHED_FIFO_INFO, (thread_info_t)&(thePolicyInfo.fifo), &count);
if ((thePolicyInfo.fifo.depressed) && (inWhichPriority == THREAD_SCHEDULED_PRIORITY)) {
return thePolicyInfo.fifo.depress_priority;
}
return thePolicyInfo.fifo.base_priority;
break;
case POLICY_RR:
count = POLICY_RR_INFO_COUNT;
thread_info(pthread_mach_thread_np(thread), THREAD_SCHED_RR_INFO, (thread_info_t)&(thePolicyInfo.rr), &count);
if ((thePolicyInfo.rr.depressed) && (inWhichPriority == THREAD_SCHEDULED_PRIORITY)) {
return thePolicyInfo.rr.depress_priority;
}
return thePolicyInfo.rr.base_priority;
break;
}
return 0;
}
static int GetParams(pthread_t thread, UInt64* period, UInt64* computation, UInt64* constraint)
{
thread_time_constraint_policy_data_t theTCPolicy;
mach_msg_type_number_t count = THREAD_TIME_CONSTRAINT_POLICY_COUNT;
boolean_t get_default = false;
kern_return_t res = thread_policy_get(pthread_mach_thread_np(thread),
THREAD_TIME_CONSTRAINT_POLICY,
(thread_policy_t)&theTCPolicy,
&count,
&get_default);
if (res == KERN_SUCCESS) {
*period = theTCPolicy.period;
*computation = theTCPolicy.computation;
*constraint = theTCPolicy.constraint;
return 0;
} else {
return -1;
}
}
static double gTimeRatio = 0;
static UInt64 gPeriod = 0;
static UInt64 gComputation = 0;
static UInt64 gConstraint = 0;
/* This should only be called ONCE per process. */
static void InitTime()
{
mach_timebase_info_data_t info;
mach_timebase_info(&info);
gTimeRatio = ((double)info.numer / (double)info.denom) / 1000;
}
UInt64 GetMicroSeconds(void)
{
return UInt64(mach_absolute_time() * gTimeRatio);
}
void GetRealTime()
{
if (gPeriod == 0) {
InitTime();
GetParams(pthread_self(), &gPeriod, &gComputation, &gConstraint);
}
}
static void SetRealTime()
{
SetThreadToPriority(pthread_self(), 96, true, gPeriod, gComputation, gConstraint);
}
static void CancelThread(pthread_t fThread)
{
mach_port_t machThread = pthread_mach_thread_np(fThread);
thread_terminate(machThread);
}
static void Yield()
{
//sched_yield();
}
int get_max_cpu()
{
int physical_count = 0;
size_t size = sizeof(physical_count);
sysctlbyname("hw.physicalcpu", &physical_count, &size, NULL, 0);
int logical_count = 0;
sysctlbyname("hw.logicalcpu", &logical_count, &size, NULL, 0);
return physical_count;
}
#endif
#ifdef __linux__
static int faust_sched_policy = -1;
static struct sched_param faust_rt_param;
void GetRealTime()
{
if (faust_sched_policy == -1) {
memset(&faust_rt_param, 0, sizeof(faust_rt_param));
pthread_getschedparam(pthread_self(), &faust_sched_policy, &faust_rt_param);
}
}
static void SetRealTime()
{
faust_rt_param.sched_priority--;
pthread_setschedparam(pthread_self(), faust_sched_policy, &faust_rt_param);
}
static void CancelThread(pthread_t fThread)
{
pthread_cancel(fThread);
pthread_join(fThread, NULL);
}
static void Yield()
{
pthread_yield();
}
// TODO
static UInt64 GetMicroSeconds(void)
{
return 0;
}
static void get_affinity(pthread_t thread) {}
static void set_affinity(pthread_t thread, int tag) {}
int get_max_cpu()
{
return sysconf(_SC_NPROCESSORS_ONLN);
}
#endif
static INLINE int Range(int min, int max, int val)
{
if (val < min) {
return min;
} else if (val > max) {
return max;
} else {
return val;
}
}
#if defined(LLVM_50) || defined(LLVM_40) || defined(LLVM_39) || defined(LLVM_38) || defined(LLVM_37) || defined(LLVM_36) || defined(LLVM_35) || defined(LLVM_34)
extern "C" void computeThreadExternal(void* dsp, int num_thread) __attribute__((weak_import));
#else
void computeThreadExternal(void* dsp, int num_thread);
#endif
class DynThreadAdapter {
private:
UInt64 fTiming[KDSPMESURE];
UInt64 fStart;
UInt64 fStop;
int fCounter;
float fOldMean;
int fOldfDynamicNumThreads;
bool fDynAdapt;
INLINE float ComputeMean()
{
float mean = 0;
for (int i = 0; i < KDSPMESURE; i++) {
mean += float(fTiming[i]);
}
mean /= float(KDSPMESURE);
return mean;
}
public :
DynThreadAdapter():fCounter(0), fOldMean(1000000000.f), fOldfDynamicNumThreads(1)
{
memset(fTiming, 0, sizeof(long long int ) * KDSPMESURE);
fDynAdapt = getenv("OMP_DYN_THREAD") ? strtol(getenv("OMP_DYN_THREAD"), NULL, 10) : false;
}
INLINE void StartMeasure()
{
if (fDynAdapt) {
//fStart = DSP_rdtsc();
fStart = GetMicroSeconds();
}
}
INLINE void StopMeasure(int staticthreadnum, int& dynthreadnum)
{
if (!fDynAdapt) {
return;
}
//fStop = DSP_rdtsc();
fStop = GetMicroSeconds();
fCounter = (fCounter + 1) % KDSPMESURE;
if (fCounter == 0) {
float mean = ComputeMean();
// Recompute dynthreadnum is timing différence is sufficient...
//printf("mean = %f fOldMean = %f\n", mean, fOldMean);
if (fabs(mean - fOldMean) / fOldMean > MEAN_TRESHOLD) {
if (mean > fOldMean) { // Worse...
if (fOldfDynamicNumThreads > dynthreadnum) {
fOldfDynamicNumThreads = dynthreadnum;
dynthreadnum += 1;
} else {
fOldfDynamicNumThreads = dynthreadnum;
dynthreadnum -= 1;
}
} else { // Better...
if (fOldfDynamicNumThreads > dynthreadnum) {
fOldfDynamicNumThreads = dynthreadnum;
dynthreadnum -= 1;
} else {
fOldfDynamicNumThreads = dynthreadnum;
dynthreadnum += 1;
}
}
fOldMean = mean;
dynthreadnum = Range(1, staticthreadnum, dynthreadnum);
//printf("dynthreadnum = %d\n", dynthreadnum);
}
}
// And keep computation time
fTiming[fCounter] = fStop - fStart;
}
};
#define Value(e) (e).info.fValue
#define Head(e) (e).info.scounter.fHead
#define IncHead(e) (e).info.scounter.fHead++
#define DecHead(e) (e).info.scounter.fHead--
#define Tail(e) (e).info.scounter.fTail
#define IncTail(e) (e).info.scounter.fTail++
#define DecTail(e) (e).info.scounter.fTail--
class TaskQueue
{
private:
int* fTaskList;
int fTaskQueueSize;
volatile AtomicCounter fCounter;
UInt64 fStealingStart;
UInt64 fMaxStealing;
public:
INLINE TaskQueue()
{}
INLINE void Init(int task_queue_size)
{
fTaskQueueSize = task_queue_size;
fTaskList = new int[fTaskQueueSize];
for (int i = 0; i < fTaskQueueSize; i++) {
fTaskList[i] = -1;
}
fStealingStart = 0;
int clock_per_microsec = (getenv("CLOCKSPERSEC")
? strtoll(getenv("CLOCKSPERSEC"), NULL, 10)
: DEFAULT_CLOCKS_PER_SEC) / 1000000;
fMaxStealing = getenv("OMP_STEALING_DUR")
? strtoll(getenv("OMP_STEALING_DUR"), NULL, 10) * clock_per_microsec
: MAX_STEAL_DUR * clock_per_microsec;
}
INLINE ~TaskQueue()
{
delete[] fTaskList;
}
INLINE void InitOne()
{
for (int i = 0; i < fTaskQueueSize; i++) {
fTaskList[i] = -1;
}
fCounter.info.fValue = 0;
fStealingStart = 0;
}
INLINE void PushHead(int item)
{
fTaskList[Head(fCounter)] = item;
IncHead(fCounter);
}
INLINE int PopHead()
{
AtomicCounter old_val;
AtomicCounter new_val;
do {
old_val = fCounter;
new_val = old_val;
if (Head(old_val) == Tail(old_val)) {
return WORK_STEALING_INDEX;
} else {
DecHead(new_val);
}
} while (!CAS1(&fCounter, Value(old_val), Value(new_val)));
return fTaskList[Head(old_val) - 1];
}
INLINE int PopTail()
{
AtomicCounter old_val;
AtomicCounter new_val;
do {
old_val = fCounter;
new_val = old_val;
if (Head(old_val) == Tail(old_val)) {
return WORK_STEALING_INDEX;
} else {
IncTail(new_val);
}
} while (!CAS1(&fCounter, Value(old_val), Value(new_val)));
return fTaskList[Tail(old_val)];
}
INLINE void MeasureStealingDur()
{
// Takes first timestamp
if (fStealingStart == 0) {
fStealingStart = DSP_rdtsc();
} else if ((DSP_rdtsc() - fStealingStart) > fMaxStealing) {
Yield();
}
}
INLINE void ResetStealingDur()
{
fStealingStart = 0;
}
static INLINE int GetNextTask(TaskQueue* task_queue_list, int cur_thread, int num_threads)
{
int tasknum;
for (int i = 0; i < num_threads; i++) {
if ((tasknum = task_queue_list[i].PopTail()) != WORK_STEALING_INDEX) {
#ifdef __linux__
//if (cur_thread != MASTER_THREAD)
task_queue_list[cur_thread].ResetStealingDur();
#endif
return tasknum; // Task is found
}
}
//NOP();
#ifdef __linux__
//if (cur_thread != MASTER_THREAD)
task_queue_list[cur_thread].MeasureStealingDur();
#endif
return WORK_STEALING_INDEX; // Otherwise will try "workstealing" again next cycle...
}
INLINE void InitTaskList(int task_list_size, int* task_list, int thread_num, int cur_thread)
{
int task_slice = task_list_size / thread_num;
int task_slice_rest = task_list_size % thread_num;
// cur_thread takes it's slice of tasks
for (int index = 0; index < task_slice; index++) {
PushHead(task_list[cur_thread * task_slice + index]);
}
// Thread 0 takes remaining ready tasks
if (cur_thread == 0) {
for (int index = 0; index < task_slice_rest; index++) {
PushHead(task_list[thread_num * task_slice + index]);
}
}
}
static INLINE void InitAll(TaskQueue* task_queue_list, int num_threads)
{
for (int i = 0; i < num_threads; i++) {
task_queue_list[i].InitOne();
}
}
};
class TaskGraph
{
private:
volatile int* fTaskList;
int fTaskQueueSize;
public:
TaskGraph(int task_queue_size)
{
fTaskQueueSize = task_queue_size;
fTaskList = new int[fTaskQueueSize];
for (int i = 0; i < fTaskQueueSize; i++) {
fTaskList[i] = 0;
}
}
INLINE ~TaskGraph()
{
delete[] fTaskList;
}
INLINE void InitTask(int task, int val)
{
fTaskList[task] = val;
}
void Display()
{
for (int i = 0; i < fTaskQueueSize; i++) {
printf("Task = %d activation = %d\n", i, fTaskList[i]);
}
}
INLINE void ActivateOutputTask(TaskQueue& queue, int task, int* tasknum)
{
if (DEC_ATOMIC(&fTaskList[task]) == 0) {
if (*tasknum == WORK_STEALING_INDEX) {
*tasknum = task;
} else {
queue.PushHead(task);
}
}
}
INLINE void ActivateOutputTask(TaskQueue& queue, int task)
{
if (DEC_ATOMIC(&fTaskList[task]) == 0) {
queue.PushHead(task);
}
}
INLINE void ActivateOneOutputTask(TaskQueue& queue, int task, int* tasknum)
{
if (DEC_ATOMIC(&fTaskList[task]) == 0) {
*tasknum = task;
} else {
*tasknum = queue.PopHead();
}
}
INLINE void GetReadyTask(TaskQueue& queue, int* tasknum)
{
if (*tasknum == WORK_STEALING_INDEX) {
*tasknum = queue.PopHead();
}
}
};
class DSPThread;
class DSPThreadPool {
private:
DSPThread** fThreadPool;
int fThreadCount;
volatile int fCurThreadCount;
public:
DSPThreadPool(int thread_pool_size);
~DSPThreadPool();
void StartAll(int num_thread, bool realtime, void* dsp);
void StopAll();
void SignalAll(int num_thread);
void SignalOne()
{
DEC_ATOMIC(&fCurThreadCount);
}
bool IsFinished()
{
return (fCurThreadCount == 0);
}
};
class DSPThread {
private:
pthread_t fThread;