-
Notifications
You must be signed in to change notification settings - Fork 1
/
tasksys.cpp
1439 lines (1190 loc) · 41.3 KB
/
tasksys.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
/*
Copyright (c) 2011-2012, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
This file implements simple task systems that provide the three
entrypoints used by ispc-generated to code to handle 'launch' and 'sync'
statements in ispc programs. See the section "Task Parallelism: Language
Syntax" in the ispc documentation for information about using task
parallelism in ispc programs, and see the section "Task Parallelism:
Runtime Requirements" for information about the task-related entrypoints
that are implemented here.
There are several task systems in this file, built using:
- Microsoft's Concurrency Runtime (ISPC_USE_CONCRT)
- Apple's Grand Central Dispatch (ISPC_USE_GCD)
- bare pthreads (ISPC_USE_PTHREADS, ISPC_USE_PTHREADS_FULLY_SUBSCRIBED)
- Cilk Plus (ISPC_USE_CILK)
- TBB (ISPC_USE_TBB_TASK_GROUP, ISPC_USE_TBB_PARALLEL_FOR)
- OpenMP (ISPC_USE_OMP)
- HPX (ISPC_USE_HPX)
The task system implementation can be selected at compile time, by defining
the appropriate preprocessor symbol on the command line (for e.g.: -D ISPC_USE_TBB).
Not all combinations of platform and task system are meaningful.
If no task system is requested, a reasonable default task system for the platform
is selected. Here are the task systems that can be selected:
#define ISPC_USE_GCD
#define ISPC_USE_CONCRT
#define ISPC_USE_PTHREADS
#define ISPC_USE_PTHREADS_FULLY_SUBSCRIBED
#define ISPC_USE_CILK
#define ISPC_USE_OMP
#define ISPC_USE_TBB_TASK_GROUP
#define ISPC_USE_TBB_PARALLEL_FOR
The ISPC_USE_PTHREADS_FULLY_SUBSCRIBED model essentially takes over the machine
by assigning one pthread to each hyper-thread, and then uses spinlocks and atomics
for task management. This model is useful for KNC where tasks can take over
the machine, but less so when there are other tasks that need running on the machine.
#define ISPC_USE_CREW
#define ISPC_USE_HPX
The HPX model requires the HPX runtime environment to be set up. This can be
done manually, e.g. with hpx::init, or by including hpx/hpx_main.hpp which
uses the main() function as entry point and sets up the runtime system.
Number of threads can be specified as commandline parameter with
--hpx:threads, use "all" to spawn one thread per processing unit.
*/
#if !(defined ISPC_USE_CONCRT || defined ISPC_USE_GCD || \
defined ISPC_USE_PTHREADS || defined ISPC_USE_PTHREADS_FULLY_SUBSCRIBED || \
defined ISPC_USE_TBB_TASK_GROUP || defined ISPC_USE_TBB_PARALLEL_FOR || \
defined ISPC_USE_OMP || defined ISPC_USE_CILK || \
defined ISPC_USE_HPX)
// If no task model chosen from the compiler cmdline, pick a reasonable default
#if defined(_WIN32) || defined(_WIN64)
#define ISPC_USE_CONCRT
#elif defined(__linux__)
#define ISPC_USE_PTHREADS
#elif defined(__APPLE__)
#define ISPC_USE_GCD
#endif
#if defined(__KNC__)
#define ISPC_USE_PTHREADS
#endif
#endif // No task model specified on compiler cmdline
#if defined(_WIN32) || defined(_WIN64)
#define ISPC_IS_WINDOWS
#elif defined(__linux__)
#define ISPC_IS_LINUX
#elif defined(__APPLE__)
#define ISPC_IS_APPLE
#endif
#if defined(__KNC__)
#define ISPC_IS_KNC
#endif
#define DBG(x)
#ifdef ISPC_IS_WINDOWS
#define NOMINMAX
#include <windows.h>
#endif // ISPC_IS_WINDOWS
#ifdef ISPC_USE_CONCRT
#include <concrt.h>
using namespace Concurrency;
#endif // ISPC_USE_CONCRT
#ifdef ISPC_USE_GCD
#include <dispatch/dispatch.h>
#include <pthread.h>
#endif // ISPC_USE_GCD
#ifdef ISPC_USE_PTHREADS
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <vector>
#include <algorithm>
#endif // ISPC_USE_PTHREADS
#ifdef ISPC_USE_PTHREADS_FULLY_SUBSCRIBED
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <vector>
#include <algorithm>
//#include <stdexcept>
#include <stack>
#endif // ISPC_USE_PTHREADS_FULLY_SUBSCRIBED
#ifdef ISPC_USE_TBB_PARALLEL_FOR
#include <tbb/parallel_for.h>
#endif // ISPC_USE_TBB_PARALLEL_FOR
#ifdef ISPC_USE_TBB_TASK_GROUP
#include <tbb/task_group.h>
#endif // ISPC_USE_TBB_TASK_GROUP
#ifdef ISPC_USE_CILK
#include <cilk/cilk.h>
#endif // ISPC_USE_TBB
#ifdef ISPC_USE_OMP
#include <omp.h>
#endif // ISPC_USE_OMP
#ifdef ISPC_USE_HPX
#include <hpx/include/async.hpp>
#include <hpx/lcos/wait_all.hpp>
#endif // ISPC_USE_HPX
#ifdef ISPC_IS_LINUX
#include <malloc.h>
#endif // ISPC_IS_LINUX
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <algorithm>
// Signature of ispc-generated 'task' functions
typedef void (*TaskFuncType)(void *data, int threadIndex, int threadCount,
int taskIndex, int taskCount,
int taskIndex0, int taskIndex1, int taskIndex2,
int taskCount0, int taskCount1, int taskCount2);
// Small structure used to hold the data for each task
#ifdef _MSC_VER
__declspec(align(16))
#endif
struct TaskInfo {
TaskFuncType func;
void *data;
int taskIndex;
int taskCount3d[3];
#if defined( ISPC_USE_CONCRT)
event taskEvent;
#endif
int taskCount() const { return taskCount3d[0]*taskCount3d[1]*taskCount3d[2]; }
int taskIndex0() const
{
return taskIndex % taskCount3d[0];
}
int taskIndex1() const
{
return ( taskIndex / taskCount3d[0] ) % taskCount3d[1];
}
int taskIndex2() const
{
return taskIndex / ( taskCount3d[0]*taskCount3d[1] );
}
int taskCount0() const { return taskCount3d[0]; }
int taskCount1() const { return taskCount3d[1]; }
int taskCount2() const { return taskCount3d[2]; }
TaskInfo() { assert(sizeof(TaskInfo) % 32 == 0); }
}
#ifndef _MSC_VER
__attribute__((aligned(32)));
#endif
;
// ispc expects these functions to have C linkage / not be mangled
extern "C" {
void ISPCLaunch(void **handlePtr, void *f, void *data, int countx, int county, int countz);
void *ISPCAlloc(void **handlePtr, int64_t size, int32_t alignment);
void ISPCSync(void *handle);
}
///////////////////////////////////////////////////////////////////////////
// TaskGroupBase
#define LOG_TASK_QUEUE_CHUNK_SIZE 14
#define MAX_TASK_QUEUE_CHUNKS 8
#define TASK_QUEUE_CHUNK_SIZE (1<<LOG_TASK_QUEUE_CHUNK_SIZE)
#define MAX_LAUNCHED_TASKS (MAX_TASK_QUEUE_CHUNKS * TASK_QUEUE_CHUNK_SIZE)
#define NUM_MEM_BUFFERS 16
class TaskGroup;
/** The TaskGroupBase structure provides common functionality for "task
groups"; a task group is the set of tasks launched from within a single
ispc function. When the function is ready to return, it waits for all
of the tasks in its task group to finish before it actually returns.
*/
class TaskGroupBase {
public:
void Reset();
int AllocTaskInfo(int count);
TaskInfo *GetTaskInfo(int index);
void *AllocMemory(int64_t size, int32_t alignment);
protected:
TaskGroupBase();
~TaskGroupBase();
int nextTaskInfoIndex;
private:
/* We allocate blocks of TASK_QUEUE_CHUNK_SIZE TaskInfo structures as
needed by the calling function. We hold up to MAX_TASK_QUEUE_CHUNKS
of these (and then exit at runtime if more than this many tasks are
launched.)
*/
TaskInfo *taskInfo[MAX_TASK_QUEUE_CHUNKS];
/* We also allocate chunks of memory to service ISPCAlloc() calls. The
memBuffers[] array holds pointers to this memory. The first element
of this array is initialized to point to mem and then any subsequent
elements required are initialized with dynamic allocation.
*/
int curMemBuffer, curMemBufferOffset;
int memBufferSize[NUM_MEM_BUFFERS];
char *memBuffers[NUM_MEM_BUFFERS];
char mem[256];
};
inline TaskGroupBase::TaskGroupBase() {
nextTaskInfoIndex = 0;
curMemBuffer = 0;
curMemBufferOffset = 0;
memBuffers[0] = mem;
memBufferSize[0] = sizeof(mem) / sizeof(mem[0]);
for (int i = 1; i < NUM_MEM_BUFFERS; ++i) {
memBuffers[i] = NULL;
memBufferSize[i] = 0;
}
for (int i = 0; i < MAX_TASK_QUEUE_CHUNKS; ++i)
taskInfo[i] = NULL;
}
inline TaskGroupBase::~TaskGroupBase() {
// Note: don't delete memBuffers[0], since it points to the start of
// the "mem" member!
for (int i = 1; i < NUM_MEM_BUFFERS; ++i)
delete[](memBuffers[i]);
}
inline void
TaskGroupBase::Reset() {
nextTaskInfoIndex = 0;
curMemBuffer = 0;
curMemBufferOffset = 0;
}
inline int
TaskGroupBase::AllocTaskInfo(int count) {
int ret = nextTaskInfoIndex;
nextTaskInfoIndex += count;
return ret;
}
inline TaskInfo *
TaskGroupBase::GetTaskInfo(int index) {
int chunk = (index >> LOG_TASK_QUEUE_CHUNK_SIZE);
int offset = index & (TASK_QUEUE_CHUNK_SIZE-1);
if (chunk == MAX_TASK_QUEUE_CHUNKS) {
fprintf(stderr, "A total of %d tasks have been launched from the "
"current function--the simple built-in task system can handle "
"no more. You can increase the values of TASK_QUEUE_CHUNK_SIZE "
"and LOG_TASK_QUEUE_CHUNK_SIZE to work around this limitation. "
"Sorry! Exiting.\n", index);
exit(1);
}
if (taskInfo[chunk] == NULL)
taskInfo[chunk] = new TaskInfo[TASK_QUEUE_CHUNK_SIZE];
return &taskInfo[chunk][offset];
}
inline void *
TaskGroupBase::AllocMemory(int64_t size, int32_t alignment) {
char *basePtr = memBuffers[curMemBuffer];
intptr_t iptr = (intptr_t)(basePtr + curMemBufferOffset);
iptr = (iptr + (alignment-1)) & ~(alignment-1);
int newOffset = int(iptr - (intptr_t)basePtr + size);
if (newOffset < memBufferSize[curMemBuffer]) {
curMemBufferOffset = newOffset;
return (char *)iptr;
}
++curMemBuffer;
curMemBufferOffset = 0;
assert(curMemBuffer < NUM_MEM_BUFFERS);
int allocSize = 1 << (12 + curMemBuffer);
allocSize = std::max(int(size+alignment), allocSize);
char *newBuf = new char[allocSize];
memBufferSize[curMemBuffer] = allocSize;
memBuffers[curMemBuffer] = newBuf;
return AllocMemory(size, alignment);
}
///////////////////////////////////////////////////////////////////////////
// Atomics and the like
static inline void
lMemFence() {
// Windows atomic functions already contain the fence
// KNC doesn't need the memory barrier
#if !defined ISPC_IS_KNC && !defined ISPC_IS_WINDOWS
__sync_synchronize();
#endif
}
static void *
lAtomicCompareAndSwapPointer(void **v, void *newValue, void *oldValue) {
#ifdef ISPC_IS_WINDOWS
return InterlockedCompareExchangePointer(v, newValue, oldValue);
#else
void *result = __sync_val_compare_and_swap(v, oldValue, newValue);
lMemFence();
return result;
#endif // ISPC_IS_WINDOWS
}
static int32_t
lAtomicCompareAndSwap32(volatile int32_t *v, int32_t newValue, int32_t oldValue) {
#ifdef ISPC_IS_WINDOWS
return InterlockedCompareExchange((volatile LONG *)v, newValue, oldValue);
#else
int32_t result = __sync_val_compare_and_swap(v, oldValue, newValue);
lMemFence();
return result;
#endif // ISPC_IS_WINDOWS
}
static inline int32_t
lAtomicAdd(volatile int32_t *v, int32_t delta) {
#ifdef ISPC_IS_WINDOWS
return InterlockedExchangeAdd((volatile LONG *)v, delta)+delta;
#else
return __sync_fetch_and_add(v, delta);
#endif
}
///////////////////////////////////////////////////////////////////////////
#ifdef ISPC_USE_CONCRT
// With ConcRT, we don't need to extend TaskGroupBase at all.
class TaskGroup : public TaskGroupBase {
public:
void Launch(int baseIndex, int count);
void Sync();
};
#endif // ISPC_USE_CONCRT
#ifdef ISPC_USE_GCD
/* With Grand Central Dispatch, we associate a GCD dispatch group with each
task group. (We'll later wait on this dispatch group when we need to
wait on all of the tasks in the group to finish.)
*/
class TaskGroup : public TaskGroupBase {
public:
TaskGroup() {
gcdGroup = dispatch_group_create();
}
void Launch(int baseIndex, int count);
void Sync();
private:
dispatch_group_t gcdGroup;
};
#endif // ISPC_USE_GCD
#ifdef ISPC_USE_PTHREADS
static void *lTaskEntry(void *arg);
class TaskGroup : public TaskGroupBase {
public:
TaskGroup() {
numUnfinishedTasks = 0;
waitingTasks.reserve(128);
inActiveList = false;
}
void Reset() {
TaskGroupBase::Reset();
numUnfinishedTasks = 0;
assert(inActiveList == false);
lMemFence();
}
void Launch(int baseIndex, int count);
void Sync();
private:
friend void *lTaskEntry(void *arg);
int32_t numUnfinishedTasks;
int32_t pad[3];
std::vector<int> waitingTasks;
bool inActiveList;
};
#endif // ISPC_USE_PTHREADS
#ifdef ISPC_USE_CILK
class TaskGroup : public TaskGroupBase {
public:
void Launch(int baseIndex, int count);
void Sync();
};
#endif // ISPC_USE_CILK
#ifdef ISPC_USE_OMP
class TaskGroup : public TaskGroupBase {
public:
void Launch(int baseIndex, int count);
void Sync();
};
#endif // ISPC_USE_OMP
#ifdef ISPC_USE_TBB_PARALLEL_FOR
class TaskGroup : public TaskGroupBase {
public:
void Launch(int baseIndex, int count);
void Sync();
};
#endif // ISPC_USE_TBB_PARALLEL_FOR
#ifdef ISPC_USE_TBB_TASK_GROUP
class TaskGroup : public TaskGroupBase {
public:
void Launch(int baseIndex, int count);
void Sync();
private:
tbb::task_group tbbTaskGroup;
};
#endif // ISPC_USE_TBB_TASK_GROUP
#ifdef ISPC_USE_HPX
class TaskGroup : public TaskGroupBase {
public:
void Launch(int baseIndex, int count);
void Sync();
private:
std::vector<hpx::future<void>> futures;
};
#endif // ISPC_USE_HPX
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Grand Central Dispatch
#ifdef ISPC_USE_GCD
/* A simple task system for ispc programs based on Apple's Grand Central
Dispatch. */
static dispatch_queue_t gcdQueue;
static volatile int32_t lock = 0;
static void
InitTaskSystem() {
if (gcdQueue != NULL)
return;
while (1) {
if (lAtomicCompareAndSwap32(&lock, 1, 0) == 0) {
if (gcdQueue == NULL) {
gcdQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
assert(gcdQueue != NULL);
lMemFence();
}
lock = 0;
break;
}
}
}
static void
lRunTask(void *ti) {
TaskInfo *taskInfo = (TaskInfo *)ti;
// FIXME: these are bogus values; may cause bugs in code that depends
// on them having unique values in different threads.
int threadIndex = 0;
int threadCount = 1;
// Actually run the task
taskInfo->func(taskInfo->data, threadIndex, threadCount,
taskInfo->taskIndex, taskInfo->taskCount(),
taskInfo->taskIndex0(), taskInfo->taskIndex1(), taskInfo->taskIndex2(),
taskInfo->taskCount0(), taskInfo->taskCount1(), taskInfo->taskCount2());
}
inline void
TaskGroup::Launch(int baseIndex, int count) {
for (int i = 0; i < count; ++i) {
TaskInfo *ti = GetTaskInfo(baseIndex + i);
dispatch_group_async_f(gcdGroup, gcdQueue, ti, lRunTask);
}
}
inline void
TaskGroup::Sync() {
dispatch_group_wait(gcdGroup, DISPATCH_TIME_FOREVER);
}
#endif // ISPC_USE_GCD
///////////////////////////////////////////////////////////////////////////
// Concurrency Runtime
#ifdef ISPC_USE_CONCRT
static void
InitTaskSystem() {
// No initialization needed
}
static void __cdecl
lRunTask(LPVOID param) {
TaskInfo *ti = (TaskInfo *)param;
// Actually run the task.
// FIXME: like the GCD implementation for OS X, this is passing bogus
// values for the threadIndex and threadCount builtins, which in turn
// will cause bugs in code that uses those.
int threadIndex = 0;
int threadCount = 1;
ti->func(ti->data, threadIndex, threadCount, ti->taskIndex, ti->taskCount(),
ti->taskIndex0(), ti->taskIndex1(), ti->taskIndex2(),
ti->taskCount0(), ti->taskCount1(), ti->taskCount2());
// Signal the event that this task is done
ti->taskEvent.set();
}
inline void
TaskGroup::Launch(int baseIndex, int count) {
for (int i = 0; i < count; ++i)
CurrentScheduler::ScheduleTask(lRunTask, GetTaskInfo(baseIndex + i));
}
inline void
TaskGroup::Sync() {
for (int i = 0; i < nextTaskInfoIndex; ++i) {
TaskInfo *ti = GetTaskInfo(i);
ti->taskEvent.wait();
ti->taskEvent.reset();
}
}
#endif // ISPC_USE_CONCRT
///////////////////////////////////////////////////////////////////////////
// pthreads
#ifdef ISPC_USE_PTHREADS
static volatile int32_t lock = 0;
static int nThreads;
static pthread_t *threads = NULL;
static pthread_mutex_t taskSysMutex;
static std::vector<TaskGroup *> activeTaskGroups;
static sem_t *workerSemaphore;
static void *
lTaskEntry(void *arg) {
int threadIndex = (int)((int64_t)arg);
int threadCount = nThreads;
while (1) {
int err;
//
// Wait on the semaphore until we're woken up due to the arrival of
// more work.
//
if ((err = sem_wait(workerSemaphore)) != 0) {
fprintf(stderr, "Error from sem_wait: %s\n", strerror(err));
exit(1);
}
//
// Acquire the mutex
//
if ((err = pthread_mutex_lock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_lock: %s\n", strerror(err));
exit(1);
}
if (activeTaskGroups.size() == 0) {
//
// Task queue is empty, go back and wait on the semaphore
//
if ((err = pthread_mutex_unlock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_unlock: %s\n", strerror(err));
exit(1);
}
continue;
}
//
// Get the last task group on the active list and the last task
// from its waiting tasks list.
//
TaskGroup *tg = activeTaskGroups.back();
assert(tg->waitingTasks.size() > 0);
int taskNumber = tg->waitingTasks.back();
tg->waitingTasks.pop_back();
if (tg->waitingTasks.size() == 0) {
// We just took the last task from this task group, so remove
// it from the active list.
activeTaskGroups.pop_back();
tg->inActiveList = false;
}
if ((err = pthread_mutex_unlock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_unlock: %s\n", strerror(err));
exit(1);
}
//
// And now actually run the task
//
DBG(fprintf(stderr, "running task %d from group %p\n", taskNumber, tg));
TaskInfo *myTask = tg->GetTaskInfo(taskNumber);
myTask->func(myTask->data, threadIndex, threadCount, myTask->taskIndex,
myTask->taskCount(),
myTask->taskIndex0(), myTask->taskIndex1(), myTask->taskIndex2(),
myTask->taskCount0(), myTask->taskCount1(), myTask->taskCount2());
//
// Decrement the "number of unfinished tasks" counter in the task
// group.
//
lMemFence();
lAtomicAdd(&tg->numUnfinishedTasks, -1);
}
pthread_exit(NULL);
return 0;
}
static void
InitTaskSystem() {
if (threads == NULL) {
while (1) {
if (lAtomicCompareAndSwap32(&lock, 1, 0) == 0) {
if (threads == NULL) {
// We launch one fewer thread than there are cores,
// since the main thread here will also grab jobs from
// the task queue itself.
nThreads = sysconf(_SC_NPROCESSORS_ONLN) - 1;
int err;
if ((err = pthread_mutex_init(&taskSysMutex, NULL)) != 0) {
fprintf(stderr, "Error creating mutex: %s\n", strerror(err));
exit(1);
}
char name[32];
bool success = false;
srand(time(NULL));
for (int i = 0; i < 10; i++) {
sprintf(name, "ispc_task.%d.%d", (int)getpid(), (int)rand());
workerSemaphore = sem_open(name, O_CREAT, S_IRUSR|S_IWUSR, 0);
if (workerSemaphore != SEM_FAILED) {
success = true;
break;
}
fprintf(stderr, "Failed to create %s\n", name);
}
if (!success) {
fprintf(stderr, "Error creating semaphore (%s): %s\n", name, strerror(errno));
exit(1);
}
threads = (pthread_t *)malloc(nThreads * sizeof(pthread_t));
for (int i = 0; i < nThreads; ++i) {
err = pthread_create(&threads[i], NULL, &lTaskEntry, (void *)((long long)i));
if (err != 0) {
fprintf(stderr, "Error creating pthread %d: %s\n", i, strerror(err));
exit(1);
}
}
activeTaskGroups.reserve(64);
}
// Make sure all of the above goes to memory before we
// clear the lock.
lMemFence();
lock = 0;
break;
}
}
}
}
inline void
TaskGroup::Launch(int baseCoord, int count) {
//
// Acquire mutex, add task
//
int err;
if ((err = pthread_mutex_lock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_lock: %s\n", strerror(err));
exit(1);
}
// Add the corresponding set of tasks to the waiting-to-be-run list for
// this task group.
//
// FIXME: it's a little ugly to hold a global mutex for this when we
// only need to make sure no one else is accessing this task group's
// waitingTasks list. (But a small experiment in switching to a
// per-TaskGroup mutex showed worse performance!)
for (int i = 0; i < count; ++i)
waitingTasks.push_back(baseCoord + i);
// Add the task group to the global active list if it isn't there
// already.
if (inActiveList == false) {
activeTaskGroups.push_back(this);
inActiveList = true;
}
if ((err = pthread_mutex_unlock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_unlock: %s\n", strerror(err));
exit(1);
}
//
// Update the count of the number of tasks left to run in this task
// group.
//
lMemFence();
lAtomicAdd(&numUnfinishedTasks, count);
//
// Post to the worker semaphore to wake up worker threads that are
// sleeping waiting for tasks to show up
//
for (int i = 0; i < count; ++i)
if ((err = sem_post(workerSemaphore)) != 0) {
fprintf(stderr, "Error from sem_post: %s\n", strerror(err));
exit(1);
}
}
inline void
TaskGroup::Sync() {
DBG(fprintf(stderr, "syncing %p - %d unfinished\n", tg, numUnfinishedTasks));
while (numUnfinishedTasks > 0) {
// All of the tasks in this group aren't finished yet. We'll try
// to help out here since we don't have anything else to do...
DBG(fprintf(stderr, "while syncing %p - %d unfinished\n", tg,
numUnfinishedTasks));
//
// Acquire the global task system mutex to grab a task to work on
//
int err;
if ((err = pthread_mutex_lock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_lock: %s\n", strerror(err));
exit(1);
}
TaskInfo *myTask = NULL;
TaskGroup *runtg = this;
if (waitingTasks.size() > 0) {
int taskNumber = waitingTasks.back();
waitingTasks.pop_back();
if (waitingTasks.size() == 0) {
// There's nothing left to start running from this group,
// so remove it from the active task list.
activeTaskGroups.erase(std::find(activeTaskGroups.begin(),
activeTaskGroups.end(), this));
inActiveList = false;
}
myTask = GetTaskInfo(taskNumber);
DBG(fprintf(stderr, "running task %d from group %p in sync\n", taskNumber, tg));
}
else {
// Other threads are already working on all of the tasks in
// this group, so we can't help out by running one ourself.
// We'll try to run one from another group to make ourselves
// useful here.
if (activeTaskGroups.size() == 0) {
// No active task groups left--there's nothing for us to do.
if ((err = pthread_mutex_unlock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_unlock: %s\n", strerror(err));
exit(1);
}
// FIXME: We basically end up busy-waiting here, which is
// extra wasteful in a world with hyper-threading. It would
// be much better to put this thread to sleep on a
// condition variable that was signaled when the last task
// in this group was finished.
#ifndef ISPC_IS_KNC
usleep(1);
#else
_mm_delay_32(8);
#endif
continue;
}
// Get a task to run from another task group.
runtg = activeTaskGroups.back();
assert(runtg->waitingTasks.size() > 0);
int taskNumber = runtg->waitingTasks.back();
runtg->waitingTasks.pop_back();
if (runtg->waitingTasks.size() == 0) {
// There's left to start running from this group, so remove
// it from the active task list.
activeTaskGroups.pop_back();
runtg->inActiveList = false;
}
myTask = runtg->GetTaskInfo(taskNumber);
DBG(fprintf(stderr, "running task %d from other group %p in sync\n",
taskNumber, runtg));
}
if ((err = pthread_mutex_unlock(&taskSysMutex)) != 0) {
fprintf(stderr, "Error from pthread_mutex_unlock: %s\n", strerror(err));
exit(1);
}
//
// Do work for _myTask_
//
// FIXME: bogus values for thread index/thread count here as well..
myTask->func(myTask->data, 0, 1, myTask->taskIndex, myTask->taskCount(),
myTask->taskIndex0(), myTask->taskIndex1(), myTask->taskIndex2(),
myTask->taskCount0(), myTask->taskCount1(), myTask->taskCount2());
//
// Decrement the number of unfinished tasks counter
//
lMemFence();
lAtomicAdd(&runtg->numUnfinishedTasks, -1);
}
DBG(fprintf(stderr, "sync for %p done!n", tg));
}
#endif // ISPC_USE_PTHREADS
///////////////////////////////////////////////////////////////////////////
// Cilk Plus
#ifdef ISPC_USE_CILK
static void
InitTaskSystem() {
// No initialization needed
}
inline void
TaskGroup::Launch(int baseIndex, int count) {
cilk_for(int i = 0; i < count; i++) {
TaskInfo *ti = GetTaskInfo(baseIndex + i);
// Actually run the task.
// Cilk does not expose the task -> thread mapping so we pretend it's 1:1
ti->func(ti->data, ti->taskIndex, ti->taskCount(),
ti->taskIndex0(), ti->taskIndex1(), ti->taskIndex2(),
ti->taskCount0(), ti->taskCount1(), ti->taskCount2());
}
}
inline void
TaskGroup::Sync() {
}
#endif // ISPC_USE_CILK
///////////////////////////////////////////////////////////////////////////
// OpenMP
#ifdef ISPC_USE_OMP
static void
InitTaskSystem() {
// No initialization needed
}
inline void
TaskGroup::Launch(int baseIndex, int count) {
#pragma omp parallel
{
const int threadIndex = omp_get_thread_num();
const int threadCount = omp_get_num_threads();
#pragma omp for schedule(runtime)
for(int i = 0; i < count; i++)
{
TaskInfo *ti = GetTaskInfo(baseIndex + i);
// Actually run the task.
ti->func(ti->data, threadIndex, threadCount, ti->taskIndex, ti->taskCount(),