-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMT.d
98 lines (76 loc) · 2.11 KB
/
MT.d
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
/**
Taken from Defend's engine.util.MT
*/
module xfbuild.MT;
import xfbuild.Exception;
import std.string : format;
import std.exception;
import std.stdio;
version (MultiThreaded)
{
import core.atomic;
import std.parallelism;
import std.c.process;
struct MTFor
{
TaskPool taskPool;
int from, to;
int numPerTask;
static MTFor opCall(TaskPool taskPool, int from, int to, int numPerTask = 0)
{
assert(to >= from);
MTFor result;
result.taskPool = taskPool;
result.from = from;
result.to = to;
if (numPerTask == 0)
{
result.numPerTask = (to - from) / 4;
if (result.numPerTask == 0) // (to - from) < 4
result.numPerTask = 1;
}
else
result.numPerTask = numPerTask;
return result;
}
int opApply(int delegate(ref int) dg)
{
if (to == from)
return 0;
assert(numPerTask > 0);
shared int numLeft;
int numTasks = (to - from) / numPerTask;
assert(numTasks > 0);
atomicStore(numLeft, numTasks - 1);
void run(int idx)
{
int i, start;
i = start = idx * numPerTask;
while (i < to && i - start < numPerTask)
{
dg(i);
++i;
}
}
void theTask(int arg)
{
run(arg);
atomicOp!"+="(numLeft, -1);
}
for (int i = 0; i < numTasks - 1; ++i)
{
auto aTask = task(&theTask, i);
taskPool.put(aTask);
}
run(numTasks - 1);
while (atomicLoad(numLeft) > 0)
{
}
return 0;
}
}
MTFor mtFor(TaskPool taskPool, int from, int to, int numPerTask = 0)
{
return MTFor(taskPool, from, to, numPerTask);
}
}