-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparallelism.d
More file actions
3488 lines (2872 loc) · 111 KB
/
Copy pathparallelism.d
File metadata and controls
3488 lines (2872 loc) · 111 KB
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
/**
$(D std._parallelism) implements high-level primitives for SMP _parallelism.
These include parallel foreach, parallel reduce, parallel eager map, pipelining
and future/promise _parallelism. $(D std._parallelism) is recommended when the
same operation is to be executed in parallel on different data, or when a
function is to be executed in a background thread and its result returned to a
well-defined main thread. For communication between arbitrary threads, see
$(D std.concurrency).
$(D std._parallelism) is based on the concept of a $(D Task). A $(D Task) is an
object that represents the fundamental unit of work in this library and may be
executed in parallel with any other $(D Task). Using $(D Task)
directly allows programming with a future/promise paradigm. All other
supported _parallelism paradigms (parallel foreach, map, reduce, pipelining)
represent an additional level of abstraction over $(D Task). They
automatically create one or more $(D Task) objects, or closely related types
that are conceptually identical but not part of the public API.
After creation, a $(D Task) may be executed in a new thread, or submitted
to a $(D TaskPool) for execution. A $(D TaskPool) encapsulates a task queue
and its worker threads. Its purpose is to efficiently map a large
number of $(D Task)s onto a smaller number of threads. A task queue is a
FIFO queue of $(D Task) objects that have been submitted to the
$(D TaskPool) and are awaiting execution. A worker thread is a thread that
is associated with exactly one task queue. It executes the $(D Task) at the
front of its queue when the queue has work available, or sleeps when
no work is available. Each task queue is associated with zero or
more worker threads. If the result of a $(D Task) is needed before execution
by a worker thread has begun, the $(D Task) can be removed from the task queue
and executed immediately in the thread where the result is needed.
Warning: Unless marked as $(D @trusted) or $(D @safe), artifacts in
this module allow implicit data sharing between threads and cannot
guarantee that client code is free from low level data races.
Synopsis:
---
import std.algorithm, std.parallelism, std.range;
void main() {
// Parallel reduce can be combined with std.algorithm.map to interesting
// effect. The following example (thanks to Russel Winder) calculates
// pi by quadrature using std.algorithm.map and TaskPool.reduce.
// getTerm is evaluated in parallel as needed by TaskPool.reduce.
//
// Timings on an Athlon 64 X2 dual core machine:
//
// TaskPool.reduce: 12.170 s
// std.algorithm.reduce: 24.065 s
immutable n = 1_000_000_000;
immutable delta = 1.0 / n;
real getTerm(int i) {
immutable x = ( i - 0.5 ) * delta;
return delta / ( 1.0 + x * x ) ;
}
immutable pi = 4.0 * taskPool.reduce!"a + b"(
std.algorithm.map!getTerm(iota(n))
);
}
---
Author: David Simcha
Copyright: Copyright (c) 2009-2011, David Simcha.
License: $(WEB boost.org/LICENSE_1_0.txt, Boost License 1.0)
*/
module std.parallelism;
import core.thread, core.cpuid, std.algorithm, std.range, std.c.stdlib,
std.stdio, std.exception, std.functional, std.conv, std.math, core.memory,
std.traits, std.typetuple, core.stdc.string, std.typecons;
import core.sync.condition, core.sync.mutex, core.atomic;
// Workaround for bug 3753.
version(Posix) {
// Can't use alloca() because it can't be used with exception handling.
// Use the GC instead even though it's slightly less efficient.
void* alloca(size_t nBytes) {
return GC.malloc(nBytes);
}
} else {
// Can really use alloca().
import core.stdc.stdlib : alloca;
}
version(Windows) {
// BUGS: Only works on Windows 2000 and above.
import core.sys.windows.windows;
struct SYSTEM_INFO {
union {
DWORD dwOemId;
struct {
WORD wProcessorArchitecture;
WORD wReserved;
};
};
DWORD dwPageSize;
LPVOID lpMinimumApplicationAddress;
LPVOID lpMaximumApplicationAddress;
LPVOID dwActiveProcessorMask;
DWORD dwNumberOfProcessors;
DWORD dwProcessorType;
DWORD dwAllocationGranularity;
WORD wProcessorLevel;
WORD wProcessorRevision;
}
private extern(Windows) void GetSystemInfo(void*);
shared static this() {
SYSTEM_INFO si;
GetSystemInfo(&si);
totalCPUs = max(1, cast(uint) si.dwNumberOfProcessors);
}
} else version(linux) {
import core.sys.posix.unistd;
shared static this() {
totalCPUs = cast(uint) sysconf(_SC_NPROCESSORS_ONLN );
}
} else version(OSX) {
extern(C) int sysctlbyname(
const char *, void *, size_t *, void *, size_t
);
shared static this() {
uint ans;
size_t len = uint.sizeof;
sysctlbyname("machdep.cpu.core_count\0".ptr, &ans, &len, null, 0);
osReportedNcpu = ans;
}
} else {
static assert(0, "Don't know how to get N CPUs on this OS.");
}
/* Atomics code. These forward to core.atomic, but are written like this
for two reasons:
1. They used to actually contain ASM code and I don' want to have to change
to directly calling core.atomic in a zillion different places.
2. core.atomic has some misc. issues that make my use cases difficult
without wrapping it. If I didn't wrap it, casts would be required
basically everywhere.
*/
private void atomicSetUbyte(ref ubyte stuff, ubyte newVal) {
core.atomic.cas(cast(shared) &stuff, stuff, newVal);
}
private ubyte atomicReadUbyte(ref ubyte val) {
return atomicLoad(cast(shared) val);
}
// This gets rid of the need for a lot of annoying casts in other parts of the
// code, when enums are involved.
private bool atomicCasUbyte(ref ubyte stuff, ubyte testVal, ubyte newVal) {
return core.atomic.cas(cast(shared) &stuff, testVal, newVal);
}
// TODO: Put something more efficient here, or lobby for it to be put in
// core.atomic. This should really just use lock; inc; on x86. This function
// is not called frequently, though, so it might not matter in practice.
private void atomicIncUint(ref uint num) {
auto ptr = cast(shared) #
atomicOp!"+="(*ptr, 1U);
}
//-----------------------------------------------------------------------------
/*--------------------- Generic helper functions, etc.------------------------*/
private template MapType(R, functions...) {
static if(functions.length == 0) {
alias typeof(unaryFun!(functions[0])(ElementType!(R).init)) MapType;
} else {
alias typeof(adjoin!(staticMap!(unaryFun, functions))
(ElementType!(R).init)) MapType;
}
}
private template ReduceType(alias fun, R, E) {
alias typeof(binaryFun!(fun)(E.init, ElementType!(R).init)) ReduceType;
}
private template noUnsharedAliasing(T) {
enum bool noUnsharedAliasing = !hasUnsharedAliasing!T;
}
// This template tests whether a function may be executed in parallel from
// @safe code via Task.executeInNewThread(). There is an additional
// requirement for executing it via a TaskPool. (See isSafeReturn).
private template isSafeTask(F) {
enum bool isSafeTask =
((functionAttributes!(F) & FunctionAttribute.SAFE) ||
(functionAttributes!(F) & FunctionAttribute.TRUSTED)) &&
!(functionAttributes!F & FunctionAttribute.REF) &&
(isFunctionPointer!F || !hasUnsharedAliasing!F) &&
allSatisfy!(noUnsharedAliasing, ParameterTypeTuple!F);
}
unittest {
alias void function() @safe F1;
alias void function() F2;
alias void function(uint, string) @trusted F3;
alias void function(uint, char[]) F4;
static assert(isSafeTask!(F1));
static assert(!isSafeTask!(F2));
static assert(isSafeTask!(F3));
static assert(!isSafeTask!(F4));
alias uint[] function(uint, string) pure @trusted F5;
static assert(isSafeTask!(F5));
}
// This function decides whether Tasks that meet all of the other requirements
// for being executed from @safe code can be executed on a TaskPool.
// When executing via TaskPool, it's theoretically possible
// to return a value that is also pointed to by a worker thread's thread local
// storage. When executing from executeInNewThread(), the thread that executed
// the Task is terminated by the time the return value is visible in the calling
// thread, so this is a non-issue. It's also a non-issue for pure functions
// since they can't read global state.
private template isSafeReturn(T) {
static if(!hasUnsharedAliasing!(T.ReturnType)) {
enum isSafeReturn = true;
} else static if(T.isPure) {
enum isSafeReturn = true;
} else {
enum isSafeReturn = false;
}
}
private T* moveToHeap(T)(ref T object) {
GC.BlkAttr gcFlags = (typeid(T).flags & 1) ?
cast(GC.BlkAttr) 0 :
GC.BlkAttr.NO_SCAN;
T* myPtr = cast(T*) GC.malloc(T.sizeof, gcFlags);
core.stdc.string.memcpy(myPtr, &object, T.sizeof);
object = T.init;
return myPtr;
}
//------------------------------------------------------------------------------
/* Various classes of task. These use manual C-style polymorphism, the kind
* with lots of structs and pointer casting. This is because real classes
* would prevent some of the allocation tricks I'm using and waste space on
* monitors and vtbls for something that needs to be ultra-efficient.
*/
private enum TaskState : ubyte {
notStarted,
inProgress,
done
}
// This is conceptually the base class for all Task types. The only Task type
// that is public is the one actually named Task. There is also a slightly
// customized ParallelForeachTask and MapTask.
private template BaseMixin(ubyte initTaskStatus) {
AbstractTask* prev;
AbstractTask* next;
static if(is(typeof(&impl))) {
void function(void*) runTask = &impl;
} else {
void function(void*) runTask;
}
Throwable exception;
ubyte taskStatus = initTaskStatus;
/* Kludge: Some tasks need to re-submit themselves after they finish.
* In this case, they will set themselves to TaskState.notStarted before
* resubmitting themselves. Setting this flag to false prevents them
* from being set to done in tryDeleteExecute.*/
bool shouldSetDone = true;
bool done() @property {
if(atomicReadUbyte(taskStatus) == TaskState.done) {
if(exception) {
throw exception;
}
return true;
}
return false;
}
}
// This is physically base "class" for all of the other tasks.
private struct AbstractTask {
mixin BaseMixin!(TaskState.notStarted);
void job() {
runTask(&this);
}
}
private template AliasReturn(alias fun, T...) {
alias AliasReturnImpl!(fun, T).ret AliasReturn;
}
private template AliasReturnImpl(alias fun, T...) {
private T args;
alias typeof(fun(args)) ret;
}
// Should be private, but std.algorithm.reduce is used in the zero-thread case
// and won't work w/ private.
template reduceAdjoin(functions...) {
static if(functions.length == 1) {
alias binaryFun!(functions[0]) reduceAdjoin;
} else {
T reduceAdjoin(T, U)(T lhs, U rhs) {
alias staticMap!(binaryFun, functions) funs;
foreach(i, Unused; typeof(lhs.expand)) {
lhs.expand[i] = funs[i](lhs.expand[i], rhs);
}
return lhs;
}
}
}
private template reduceFinish(functions...) {
static if(functions.length == 1) {
alias binaryFun!(functions[0]) reduceFinish;
} else {
T reduceFinish(T)(T lhs, T rhs) {
alias staticMap!(binaryFun, functions) funs;
foreach(i, Unused; typeof(lhs.expand)) {
lhs.expand[i] = funs[i](lhs.expand[i], rhs.expand[i]);
}
return lhs;
}
}
}
private template ElementsCompatible(R, A) {
static if(!isArray!A) {
enum bool ElementsCompatible = false;
} else {
enum bool ElementsCompatible =
is(ElementType!R : ElementType!A);
}
}
/**
$(D Task) represents the fundamental unit of work. A $(D Task) may be
executed in parallel with any other $(D Task). Using this struct directly
allows future/promise _parallelism. In this paradigm, a function (or delegate
or other callable) is executed in a thread other than the one it was called
from. The calling thread does not block while the function is being executed.
A call to $(D workForce), $(D yieldForce), or $(D spinForce) is used to
ensure that the $(D Task) has finished executing and to obtain the return
value, if any. These functions and $(D done) also act as full memory barriers,
meaning that any memory writes made in the thread that executed the $(D Task)
are guaranteed to be visible in the calling thread after one of these functions
returns.
The $(XREF parallelism, task) and $(XREF parallelism, scopedTask) functions can
be used to create an instance of this struct. See $(D task) for usage examples.
Function results are returned from $(D yieldForce), $(D spinForce) and
$(D workForce) by ref. If $(D fun) returns by ref, the reference will point
to the returned reference of $(D fun). Otherwise it will point to a
field in this struct.
Copying of this struct is disabled, since it would provide no useful semantics.
If you want to pass this struct around, you should do so by reference or
pointer.
Bugs: Changes to $(D ref) and $(D out) arguments are not propagated to the
call site, only to $(D args) in this struct.
Copying is not actually disabled yet due to compiler bugs. In the
mean time, please understand that if you copy this struct, you're
relying on implementation bugs.
*/
struct Task(alias fun, Args...) {
// Work around syntactic ambiguity w.r.t. address of function return vals.
private static T* addressOf(T)(ref T val) {
return &val;
}
private static void impl(void* myTask) {
Task* myCastedTask = cast(typeof(this)*) myTask;
static if(is(ReturnType == void)) {
fun(myCastedTask._args);
} else static if(is(typeof(addressOf(fun(myCastedTask._args))))) {
myCastedTask.returnVal = addressOf(fun(myCastedTask._args));
} else {
myCastedTask.returnVal = fun(myCastedTask._args);
}
}
mixin BaseMixin!(TaskState.notStarted) Base;
private TaskPool pool;
private bool isScoped; // True if created with scopedTask.
Args _args;
/**
The arguments the function was called with. Changes to $(D out) and
$(D ref) arguments will be visible here.
*/
static if(__traits(isSame, fun, run)) {
alias _args[1..$] args;
} else {
alias _args args;
}
// The purpose of this code is to decide whether functions whose
// return values have unshared aliasing can be executed via
// TaskPool from @safe code. See isSafeReturn.
static if(__traits(isSame, fun, run)) {
static if(isFunctionPointer!(_args[0])) {
private enum bool isPure =
functionAttributes!(Args[0]) & FunctionAttribute.PURE;
} else {
// BUG: Should check this for delegates too, but std.traits
// apparently doesn't allow this. isPure is irrelevant
// for delegates, at least for now since shared delegates
// don't work.
private enum bool isPure = false;
}
} else {
// We already know that we can't execute aliases in @safe code, so
// just put a dummy value here.
private enum bool isPure = false;
}
/**
The return type of the function called by this $(D Task). This can be
$(D void).
*/
alias typeof(fun(_args)) ReturnType;
static if(!is(ReturnType == void)) {
static if(is(typeof(&fun(_args)))) {
// Ref return.
ReturnType* returnVal;
ref ReturnType fixRef(ReturnType* val) {
return *val;
}
} else {
ReturnType returnVal;
ref ReturnType fixRef(ref ReturnType val) {
return val;
}
}
}
private void enforcePool() {
enforce(this.pool !is null, "Job not submitted yet.");
}
private this(Args args) {
static if(args.length > 0) {
_args = args;
}
}
/**
If the $(D Task) isn't started yet, execute it in the current thread.
If it's done, return its return value, if any. If it's in progress,
busy spin until it's done, then return the return value. If it threw
an exception, rethrow that exception.
This function should be used when you expect the result of the
$(D Task) to be available on a timescale shorter than that of an OS
context switch.
*/
@property ref ReturnType spinForce() @trusted {
enforcePool();
this.pool.tryDeleteExecute( cast(AbstractTask*) &this);
while(atomicReadUbyte(this.taskStatus) != TaskState.done) {}
if(exception) {
throw exception;
}
static if(!is(ReturnType == void)) {
return fixRef(this.returnVal);
}
}
/**
If the $(D Task) isn't started yet, execute it in the current thread.
If it's done, return its return value, if any. If it's in progress,
wait on a condition variable. If it threw an exception, rethrow that
exception.
This function should be used for expensive functions, as waiting on a
condition variable introduces latency, but avoids wasted CPU cycles.
*/
@property ref ReturnType yieldForce() @trusted {
enforcePool();
this.pool.tryDeleteExecute( cast(AbstractTask*) &this);
if(done) {
static if(is(ReturnType == void)) {
return;
} else {
return fixRef(this.returnVal);
}
}
pool.lock();
scope(exit) pool.unlock();
while(atomicReadUbyte(this.taskStatus) != TaskState.done) {
pool.waitUntilCompletion();
}
if(exception) {
throw exception;
}
static if(!is(ReturnType == void)) {
return fixRef(this.returnVal);
}
}
/**
If this $(D Task) was not started yet, execute it in the current
thread. If it is finished, return its result. If it is in progress,
execute any other $(D Task) from the $(D TaskPool) instance that
this $(D Task) was submitted to until this one
is finished. If it threw an exception, rethrow that exception.
If no other tasks are available or this $(D Task) was executed using
$(D executeInNewThread), wait on a condition variable.
*/
@property ref ReturnType workForce() @trusted {
enforcePool();
this.pool.tryDeleteExecute( cast(AbstractTask*) &this);
while(true) {
if(done) { // done() implicitly checks for exceptions.
static if(is(ReturnType == void)) {
return;
} else {
return fixRef(this.returnVal);
}
}
pool.lock();
AbstractTask* job;
try {
// Locking explicitly and calling popNoSync() because
// pop() waits on a condition variable if there are no Tasks
// in the queue.
job = pool.popNoSync();
} finally {
pool.unlock();
}
if(job !is null) {
version(verboseUnittest) {
stderr.writeln("Doing workForce work.");
}
pool.doJob(job);
if(done) {
static if(is(ReturnType == void)) {
return;
} else {
return fixRef(this.returnVal);
}
}
} else {
version(verboseUnittest) {
stderr.writeln("Yield from workForce.");
}
return yieldForce();
}
}
}
/**
Returns $(D true) if the $(D Task) is finished executing.
Throws: Rethrows any exception thrown during the execution of the
$(D Task).
*/
@property bool done() @trusted {
// Explicitly forwarded for documentation purposes.
return Base.done;
}
/**
Create a new thread for executing this $(D Task), execute it in the
newly created thread, then terminate the thread. This can be used for
future/promise parallelism. An explicit priority may be given
to the $(D Task). If one is provided, its value is forwarded to
$(D core.thread.Thread.priority). See $(XREF parallelism, task) for
usage example.
*/
void executeInNewThread() @trusted {
pool = new TaskPool(cast(AbstractTask*) &this);
}
/// Ditto
void executeInNewThread(int priority) @trusted {
pool = new TaskPool(cast(AbstractTask*) &this, priority);
}
@safe ~this() {
if(isScoped && pool !is null && taskStatus != TaskState.done) {
yieldForce();
}
}
// When this is uncommented, it somehow gets called even though it's
// disabled and Bad Things Happen.
//@disable this(this) { assert(0);}
}
// Calls $(D fpOrDelegate) with $(D args). This is an
// adapter that makes $(D Task) work with delegates, function pointers and
// functors instead of just aliases.
ReturnType!(F) run(F, Args...)(F fpOrDelegate, ref Args args) {
return fpOrDelegate(args);
}
/**
Creates a $(D Task) on the GC heap that calls an alias. This may be executed
via $(D Task.executeInNewThread) or by submitting to a
$(XREF parallelism, TaskPool). A globally accessible instance of
$(D TaskPool) is provided by $(XREF parallelism, taskPool).
Returns: A pointer to the $(D Task).
Examples:
---
// Read two files into memory at the same time.
import std.file;
void main() {
// Create and execute a Task for reading foo.txt.
auto file1Task = task!read("foo.txt");
file1Task.executeInNewThread();
// Read bar.txt in parallel.
auto file2Data = read("bar.txt");
// Get the results of reading foo.txt.
auto file1Data = file1Task.yieldForce();
}
---
---
// Sorts an array using a parallel quick sort algorithm. The first partition
// is done serially. Both recursion branches are then executed in
// parallel.
//
// Timings for sorting an array of 1,000,000 doubles on an Athlon 64 X2
// dual core machine:
//
// This implementation: 176 milliseconds.
// Equivalent serial implementation: 280 milliseconds
void parallelSort(T)(T[] data) {
// Sort small subarrays serially.
if(data.length < 100) {
std.algorithm.sort(data);
return;
}
// Partition the array.
swap(data[$ / 2], data[$ - 1]);
auto pivot = data[$ - 1];
bool lessThanPivot(T elem) { return elem < pivot; }
auto greaterEqual = partition!lessThanPivot(data[0..$ - 1]);
swap(data[$ - greaterEqual.length - 1], data[$ - 1]);
auto less = data[0..$ - greaterEqual.length - 1];
greaterEqual = data[$ - greaterEqual.length..$];
// Execute both recursion branches in parallel.
auto recurseTask = task!(parallelSort)(greaterEqual);
taskPool.put(recurseTask);
parallelSort(less);
recurseTask.yieldForce();
}
---
*/
auto task(alias fun, Args...)(Args args) {
alias Task!(fun, Args) RetType;
auto stack = RetType(args);
return moveToHeap(stack);
}
/**
Creates a $(D Task) on the GC heap that calls a function pointer, delegate, or
class/struct with overloaded opCall.
Examples:
---
// Read two files in at the same time again, but this time use a function
// pointer instead of an alias to represent std.file.read.
import std.file;
void main() {
// Create and execute a Task for reading foo.txt.
auto file1Task = task(&read, "foo.txt");
file1Task.executeInNewThread();
// Read bar.txt in parallel.
auto file2Data = read("bar.txt");
// Get the results of reading foo.txt.
auto file1Data = file1Task.yieldForce();
}
---
Notes: This function takes a non-scope delegate, meaning it can be
used with closures. If you can't allocate a closure due to objects
on the stack that have scoped destruction, see $(D scopedTask), which
takes a scope delegate.
*/
auto task(F, Args...)(F delegateOrFp, Args args)
if(is(typeof(delegateOrFp(args))) && !isSafeTask!F) {
auto stack = Task!(run, TypeTuple!(F, Args))(delegateOrFp, args);
return moveToHeap(stack);
}
/**
Version of $(D task) usable from $(D @safe) code. Usage mechanics are
identical to the non-@safe case, but safety introduces the some restrictions.
1. $(D fun) must be @safe or @trusted.
2. $(D F) must not have any unshared aliasing as defined by
$(XREF traits, hasUnsharedAliasing). This means it
may not be an unshared delegate or a non-shared class or struct
with overloaded $(D opCall). This also precludes accepting template
alias parameters.
3. $(D Args) must not have unshared aliasing.
4. $(D fun) must not return by reference.
5. The return type must not have unshared aliasing unless $(D fun) is
$(D pure) or the $(D Task) is executed via $(D executeInNewThread) instead
of using a $(D TaskPool).
*/
@trusted auto task(F, Args...)(F fun, Args args)
if(is(typeof(fun(args))) && isSafeTask!F) {
auto stack = Task!(run, TypeTuple!(F, Args))(fun, args);
return moveToHeap(stack);
}
/**
These functions allow the creation of $(D Task) objects on the stack rather
than the GC heap. The lifetime of a $(D Task) created by $(D scopedTask)
cannot exceed the lifetime of the scope it was created in.
$(D scopedTask) might be preferred over $(D task):
1. When a $(D Task) that calls a delegate is being created and a closure
cannot be allocated due to objects on the stack that have scoped
destruction. The delegate overload of $(D scopedTask) takes a $(D scope)
delegate.
2. As a micro-optimization, to avoid the heap allocation associated with
$(D task) or with the creation of a closure.
Usage is otherwise identical to $(D task).
Notes: $(D Task) objects created using $(D scopedTask) will automatically
call $(D Task.yieldForce) in their destructor if necessary to ensure
the $(D Task) is complete before the stack frame they reside on is destroyed.
*/
auto scopedTask(alias fun, Args...)(Args args) {
auto ret = Task!(fun, Args)(args);
ret.isScoped = true;
return ret;
}
/// Ditto
auto scopedTask(F, Args...)(scope F delegateOrFp, Args args)
if(is(typeof(delegateOrFp(args))) && !isSafeTask!F) {
auto ret = Task!(run, TypeTuple!(F, Args))(delegateOrFp, args);
ret.isScoped = true;
return ret;
}
/// Ditto
@trusted auto scopedTask(F, Args...)(F fun, Args args)
if(is(typeof(fun(args))) && isSafeTask!F) {
auto ret = typeof(return)(fun, args);
ret.isScoped = true;
return ret;
}
/**
The total number of CPU cores available on the current machine, as reported by
the operating system.
*/
immutable uint totalCPUs;
/**
This class encapsulates a task queue and a set of worker threads. Its purpose
is to efficiently map a large number of $(D Task)s onto a smaller number of
threads. A task queue is a FIFO queue of $(D Task) objects that have been
submitted to the $(D TaskPool) and are awaiting execution. A worker thread is a
thread that executes the $(D Task) at the front of the queue when one is
available and sleeps when the queue is empty.
This class should usually be used via the global instantiation
available via the $(XREF parallelism, taskPool) property.
Occasionally it is useful to explicitly instantiate a $(D TaskPool):
1. When you want $(D TaskPool) instances with multiple priorities, for example
a low priority pool and a high priority pool.
2. When the threads in the global task pool are waiting on a synchronization
primitive (for example a mutex), and you want to parallelize the code that
needs to run before these threads can be resumed.
*/
final class TaskPool {
private:
// A pool can either be a regular pool or a single-task pool. A
// single-task pool is a dummy pool that's fired up for
// Task.executeInNewThread().
bool isSingleTask;
union {
Thread[] pool;
Thread singleTaskThread;
}
AbstractTask* head;
AbstractTask* tail;
PoolState status = PoolState.running;
Condition workerCondition;
Condition waiterCondition;
Mutex mutex;
// The instanceStartIndex of the next instance that will be created.
__gshared static size_t nextInstanceIndex = 1;
// The index of the current thread.
static size_t threadIndex;
// The index of the first thread in this instance.
immutable size_t instanceStartIndex;
// The index that the next thread to be initialized in this pool will have.
size_t nextThreadIndex;
enum PoolState : ubyte {
running,
finishing,
stopNow
}
void doJob(AbstractTask* job) {
assert(job.taskStatus == TaskState.inProgress);
assert(job.next is null);
assert(job.prev is null);
scope(exit) {
if(!isSingleTask) {
lock();
notifyWaiters();
unlock();
}
}
try {
job.job();
} catch(Throwable e) {
job.exception = e;
}
if(job.shouldSetDone) {
atomicSetUbyte(job.taskStatus, TaskState.done);
}
}
// This function is used for dummy pools created by Task.executeInNewThread().
void doSingleTask() {
// No synchronization. Pool is guaranteed to only have one thread,
// and the queue is submitted to before this thread is created.
assert(head);
auto t = head;
t.next = t.prev = head = null;
doJob(t);
}
// This work loop is used for a "normal" task pool where a worker thread
// does more than one task.
void workLoop() {
// Initialize thread index.
lock();
threadIndex = nextThreadIndex;
nextThreadIndex++;
unlock();
while(atomicReadUbyte(status) != PoolState.stopNow) {
AbstractTask* task = pop();
if (task is null) {
if(atomicReadUbyte(status) == PoolState.finishing) {
atomicSetUbyte(status, PoolState.stopNow);
return;
}
} else {
doJob(task);
}
}
}
bool deleteItem(AbstractTask* item) {
lock();
auto ret = deleteItemNoSync(item);
unlock();
return ret;
}
bool deleteItemNoSync(AbstractTask* item)
out {
assert(item.next is null);
assert(item.prev is null);
} body {
if(item.taskStatus != TaskState.notStarted) {
return false;
}
item.taskStatus = TaskState.inProgress;
if(item is head) {
// Make sure head gets set properly.
popNoSync();
return true;;
}
if(item is tail) {
tail = tail.prev;
if(tail !is null) {
tail.next = null;
}
item.next = null;
item.prev = null;
return true;
}
if(item.next !is null) {
assert(item.next.prev is item); // Check queue consistency.
item.next.prev = item.prev;
}
if(item.prev !is null) {
assert(item.prev.next is item); // Check queue consistency.
item.prev.next = item.next;
}
item.next = null;
item.prev = null;
return true;
}
// Pop a task off the queue.
AbstractTask* pop() {
lock();
auto ret = popNoSync();
while(ret is null && status == PoolState.running) {
wait();
ret = popNoSync();
}
unlock();